app.js 525 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441
  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. function openAddL2TPModal() {
  2120. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2121. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2122. document.getElementById('l2tp-modal-name').readOnly = false;
  2123. document.getElementById('l2tp-modal-server').value = '';
  2124. document.getElementById('l2tp-modal-user').value = '';
  2125. document.getElementById('l2tp-modal-pass').value = '';
  2126. document.getElementById('l2tp-modal-ipsec').value = '';
  2127. document.getElementById('l2tp-modal-defroute').checked = true;
  2128. document.getElementById('l2tp-modal-disabled').checked = false;
  2129. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2130. document.getElementById('l2tp-modal').classList.remove('hidden');
  2131. }
  2132. function openEditL2TPModal(name) {
  2133. const inst = (state.l2tpList || []).find(i => i.name === name);
  2134. if (!inst) return;
  2135. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2136. document.getElementById('l2tp-modal-name').value = inst.name;
  2137. document.getElementById('l2tp-modal-name').readOnly = true;
  2138. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2139. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2140. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2141. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2142. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2143. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2144. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2145. document.getElementById('l2tp-modal').classList.remove('hidden');
  2146. }
  2147. function closeL2TPModal() {
  2148. document.getElementById('l2tp-modal').classList.add('hidden');
  2149. }
  2150. async function submitSaveL2TP(e) {
  2151. e.preventDefault();
  2152. const name = document.getElementById('l2tp-modal-name').value.trim();
  2153. const server = document.getElementById('l2tp-modal-server').value.trim();
  2154. const user = document.getElementById('l2tp-modal-user').value.trim();
  2155. const pass = document.getElementById('l2tp-modal-pass').value;
  2156. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2157. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2158. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2159. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2160. try {
  2161. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2162. method: 'POST',
  2163. headers: { 'Content-Type': 'application/json' },
  2164. body: JSON.stringify({
  2165. name,
  2166. connect_to: server,
  2167. username: user,
  2168. password: pass,
  2169. profile: profile,
  2170. ipsec_secret: ipsec,
  2171. default_route: defRoute,
  2172. disabled
  2173. })
  2174. });
  2175. if (res.ok) {
  2176. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2177. closeL2TPModal();
  2178. loadL2TP(false);
  2179. fetchData(false);
  2180. }
  2181. } catch (err) {
  2182. showToast('Error', err.message, 'error');
  2183. }
  2184. }
  2185. async function connectL2TPInstance(name) {
  2186. try {
  2187. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2188. if (res.ok) {
  2189. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2190. setTimeout(() => loadL2TP(false), 2000);
  2191. }
  2192. } catch (err) {
  2193. showToast('Error', err.message, 'error');
  2194. }
  2195. }
  2196. async function disconnectL2TPInstance(name) {
  2197. try {
  2198. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2199. if (res.ok) {
  2200. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2201. loadL2TP(false);
  2202. }
  2203. } catch (err) {
  2204. showToast('Error', err.message, 'error');
  2205. }
  2206. }
  2207. async function toggleL2TPState(name, enable) {
  2208. try {
  2209. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2210. method: 'POST',
  2211. headers: { 'Content-Type': 'application/json' },
  2212. body: JSON.stringify({ enabled: enable })
  2213. });
  2214. if (res.ok) {
  2215. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2216. loadL2TP(false);
  2217. }
  2218. } catch (err) {
  2219. showToast('Error', err.message, 'error');
  2220. }
  2221. }
  2222. async function deleteL2TPInstance(name) {
  2223. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2224. try {
  2225. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2226. if (res.ok) {
  2227. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2228. loadL2TP(false);
  2229. fetchData(false);
  2230. }
  2231. } catch (err) {
  2232. showToast('Error', err.message, 'error');
  2233. }
  2234. }
  2235. // ======================== PPTP Multi-Instance ========================
  2236. async function loadPPTP(populateInputs = true) {
  2237. try {
  2238. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2239. await fetchPPPProfilesList();
  2240. }
  2241. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2242. const list = await res.json();
  2243. state.pptpList = Array.isArray(list) ? list : [];
  2244. const badge = document.getElementById('pptp-count-badge');
  2245. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2246. const tbody = document.getElementById('pptp-table-body');
  2247. const empty = document.getElementById('pptp-empty');
  2248. if (!tbody) return;
  2249. tbody.innerHTML = '';
  2250. if (state.pptpList.length === 0) {
  2251. if (empty) empty.classList.remove('hidden');
  2252. } else {
  2253. if (empty) empty.classList.add('hidden');
  2254. state.pptpList.forEach(inst => {
  2255. const tr = document.createElement('tr');
  2256. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2257. tr.innerHTML = `
  2258. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2259. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2260. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2261. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2262. <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>
  2263. <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>
  2264. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2265. <td class="py-2.5 px-3 text-center">
  2266. <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'}">
  2267. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2268. </span>
  2269. </td>
  2270. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2271. ${inst.running ? `
  2272. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2273. ` : `
  2274. <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>
  2275. `}
  2276. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2277. ${inst.disabled ? 'Enable' : 'Disable'}
  2278. </button>
  2279. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2280. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2281. </td>
  2282. `;
  2283. tbody.appendChild(tr);
  2284. });
  2285. }
  2286. } catch (err) {
  2287. console.error('Failed to load PPTP:', err);
  2288. }
  2289. }
  2290. function openAddPPTPModal() {
  2291. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2292. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2293. document.getElementById('pptp-modal-name').readOnly = false;
  2294. document.getElementById('pptp-modal-server').value = '';
  2295. document.getElementById('pptp-modal-user').value = '';
  2296. document.getElementById('pptp-modal-pass').value = '';
  2297. document.getElementById('pptp-modal-mppe').checked = true;
  2298. document.getElementById('pptp-modal-defroute').checked = true;
  2299. document.getElementById('pptp-modal-disabled').checked = false;
  2300. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2301. document.getElementById('pptp-modal').classList.remove('hidden');
  2302. }
  2303. function openEditPPTPModal(name) {
  2304. const inst = (state.pptpList || []).find(i => i.name === name);
  2305. if (!inst) return;
  2306. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2307. document.getElementById('pptp-modal-name').value = inst.name;
  2308. document.getElementById('pptp-modal-name').readOnly = true;
  2309. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2310. document.getElementById('pptp-modal-user').value = inst.username || '';
  2311. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2312. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2313. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2314. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2315. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2316. document.getElementById('pptp-modal').classList.remove('hidden');
  2317. }
  2318. function closePPTPModal() {
  2319. document.getElementById('pptp-modal').classList.add('hidden');
  2320. }
  2321. async function submitSavePPTP(e) {
  2322. e.preventDefault();
  2323. const name = document.getElementById('pptp-modal-name').value.trim();
  2324. const server = document.getElementById('pptp-modal-server').value.trim();
  2325. const user = document.getElementById('pptp-modal-user').value.trim();
  2326. const pass = document.getElementById('pptp-modal-pass').value;
  2327. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2328. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2329. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2330. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2331. try {
  2332. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2333. method: 'POST',
  2334. headers: { 'Content-Type': 'application/json' },
  2335. body: JSON.stringify({
  2336. name,
  2337. connect_to: server,
  2338. username: user,
  2339. password: pass,
  2340. profile: profile,
  2341. require_mppe: mppe,
  2342. default_route: defRoute,
  2343. auto_reconnect: true,
  2344. disabled
  2345. })
  2346. });
  2347. if (res.ok) {
  2348. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2349. closePPTPModal();
  2350. loadPPTP(false);
  2351. fetchData(false);
  2352. }
  2353. } catch (err) {
  2354. showToast('Error', err.message, 'error');
  2355. }
  2356. }
  2357. async function connectPPTPInstance(name) {
  2358. try {
  2359. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2360. if (res.ok) {
  2361. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2362. setTimeout(() => loadPPTP(false), 2000);
  2363. }
  2364. } catch (err) {
  2365. showToast('Error', err.message, 'error');
  2366. }
  2367. }
  2368. async function disconnectPPTPInstance(name) {
  2369. try {
  2370. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2371. if (res.ok) {
  2372. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2373. loadPPTP(false);
  2374. }
  2375. } catch (err) {
  2376. showToast('Error', err.message, 'error');
  2377. }
  2378. }
  2379. async function togglePPTPState(name, enable) {
  2380. try {
  2381. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2382. method: 'POST',
  2383. headers: { 'Content-Type': 'application/json' },
  2384. body: JSON.stringify({ enabled: enable })
  2385. });
  2386. if (res.ok) {
  2387. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2388. loadPPTP(false);
  2389. }
  2390. } catch (err) {
  2391. showToast('Error', err.message, 'error');
  2392. }
  2393. }
  2394. async function deletePPTPInstance(name) {
  2395. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2396. try {
  2397. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2398. if (res.ok) {
  2399. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2400. loadPPTP(false);
  2401. fetchData(false);
  2402. }
  2403. } catch (err) {
  2404. showToast('Error', err.message, 'error');
  2405. }
  2406. }
  2407. // ---------------- Modal & Helper Functions ----------------
  2408. function openVlanModal(defaultParent = '') {
  2409. const select = document.getElementById('vlan-parent');
  2410. select.innerHTML = '';
  2411. const allIfaces = state.interfaces || [];
  2412. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2413. if (eligible.length === 0) {
  2414. const opt = document.createElement('option');
  2415. opt.value = '';
  2416. opt.innerText = 'No VLAN-capable interfaces available';
  2417. select.appendChild(opt);
  2418. } else {
  2419. eligible.forEach(i => {
  2420. const opt = document.createElement('option');
  2421. opt.value = i.name;
  2422. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2423. if (i.name === defaultParent) opt.selected = true;
  2424. select.appendChild(opt);
  2425. });
  2426. }
  2427. document.getElementById('vlan-id').value = '';
  2428. document.getElementById('vlan-name').value = '';
  2429. document.getElementById('vlan-ip').value = '';
  2430. document.getElementById('vlan-desc').value = '';
  2431. autoSuggestVlanName();
  2432. document.getElementById('vlan-modal').classList.remove('hidden');
  2433. }
  2434. function closeVlanModal() {
  2435. document.getElementById('vlan-modal').classList.add('hidden');
  2436. }
  2437. function autoSuggestVlanName() {
  2438. const parent = document.getElementById('vlan-parent').value;
  2439. if (!parent) return;
  2440. const id = document.getElementById('vlan-id').value;
  2441. const nameInput = document.getElementById('vlan-name');
  2442. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2443. }
  2444. function setSubnetPreset(cidr) {
  2445. const ipInput = document.getElementById('vlan-ip');
  2446. const id = document.getElementById('vlan-id').value || '10';
  2447. ipInput.value = `192.168.${id}.1${cidr}`;
  2448. }
  2449. async function submitCreateVlan(e) {
  2450. e.preventDefault();
  2451. const btn = document.getElementById('vlan-submit-btn');
  2452. btn.disabled = true;
  2453. btn.innerText = 'Creating...';
  2454. const parent = document.getElementById('vlan-parent').value;
  2455. if (!parent) {
  2456. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2457. btn.disabled = false;
  2458. btn.innerText = 'Create VLAN';
  2459. return;
  2460. }
  2461. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2462. const name = document.getElementById('vlan-name').value.trim();
  2463. const ip = document.getElementById('vlan-ip').value.trim();
  2464. const role = document.getElementById('vlan-role').value;
  2465. const desc = document.getElementById('vlan-desc').value.trim();
  2466. try {
  2467. const res = await fetch(`${API_BASE}/vlans`, {
  2468. method: 'POST',
  2469. headers: { 'Content-Type': 'application/json' },
  2470. body: JSON.stringify({
  2471. parent_name: parent,
  2472. vlan_id: id,
  2473. name: name,
  2474. ip_address: ip,
  2475. role: role,
  2476. description: desc,
  2477. mtu: 1500,
  2478. auto_up: true
  2479. })
  2480. });
  2481. const data = await res.json();
  2482. if (res.ok) {
  2483. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2484. state.expandedParents.add(parent);
  2485. closeVlanModal();
  2486. await fetchData(true);
  2487. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2488. } else {
  2489. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2490. }
  2491. } catch (err) {
  2492. showToast('Error', err.message, 'error');
  2493. } finally {
  2494. btn.disabled = false;
  2495. btn.innerText = 'Create VLAN';
  2496. }
  2497. }
  2498. async function confirmDeleteVlan(name) {
  2499. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2500. try {
  2501. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2502. if (res.ok) {
  2503. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2504. closeIfaceModal();
  2505. fetchData(true);
  2506. }
  2507. } catch (err) {
  2508. showToast('Error', err.message, 'error');
  2509. }
  2510. }
  2511. function openIfaceModal(name) {
  2512. const iface = (state.interfaces || []).find(i => i.name === name);
  2513. if (!iface) return;
  2514. state.currentModalIface = iface.name;
  2515. document.getElementById('modal-iface-name').innerText = iface.name;
  2516. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2517. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2518. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2519. document.getElementById('modal-iface-desc').value = iface.description || '';
  2520. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2521. if (iface.is_vlan) {
  2522. delBtn.classList.remove('hidden');
  2523. } else {
  2524. delBtn.classList.add('hidden');
  2525. }
  2526. renderModalIPs(iface);
  2527. document.getElementById('iface-modal').classList.remove('hidden');
  2528. }
  2529. function renderModalIPs(iface) {
  2530. const container = document.getElementById('modal-ip-list');
  2531. container.innerHTML = '';
  2532. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2533. if (addrs.length === 0) {
  2534. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2535. return;
  2536. }
  2537. addrs.forEach(addr => {
  2538. const row = document.createElement('div');
  2539. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2540. row.innerHTML = `
  2541. <span class="text-white">${addr}</span>
  2542. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2543. `;
  2544. container.appendChild(row);
  2545. });
  2546. }
  2547. function closeIfaceModal() {
  2548. document.getElementById('iface-modal').classList.add('hidden');
  2549. state.currentModalIface = null;
  2550. }
  2551. async function setIfaceState(name, newState) {
  2552. await toggleInterfaceState(name, newState);
  2553. const updated = (state.interfaces || []).find(i => i.name === name);
  2554. if (updated) openIfaceModal(name);
  2555. }
  2556. async function applyMTU() {
  2557. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2558. try {
  2559. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2560. method: 'POST',
  2561. headers: { 'Content-Type': 'application/json' },
  2562. body: JSON.stringify({ mtu })
  2563. });
  2564. if (res.ok) {
  2565. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2566. fetchData(false);
  2567. }
  2568. } catch (err) {
  2569. showToast('Error', err.message, 'error');
  2570. }
  2571. }
  2572. async function addInterfaceIP() {
  2573. const ip = document.getElementById('modal-new-ip').value.trim();
  2574. if (!ip) return;
  2575. try {
  2576. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2577. method: 'POST',
  2578. headers: { 'Content-Type': 'application/json' },
  2579. body: JSON.stringify({ ip })
  2580. });
  2581. if (res.ok) {
  2582. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2583. document.getElementById('modal-new-ip').value = '';
  2584. await fetchData(false);
  2585. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2586. if (iface) renderModalIPs(iface);
  2587. } else {
  2588. const err = await res.json();
  2589. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2590. }
  2591. } catch (err) {
  2592. showToast('Error', err.message, 'error');
  2593. }
  2594. }
  2595. async function removeInterfaceIP(ip) {
  2596. if (!confirm(`Remove IP ${ip}?`)) return;
  2597. try {
  2598. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2599. method: 'DELETE',
  2600. headers: { 'Content-Type': 'application/json' },
  2601. body: JSON.stringify({ ip })
  2602. });
  2603. if (res.ok) {
  2604. showToast('IP Removed', `Removed ${ip}`, 'success');
  2605. await fetchData(false);
  2606. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2607. if (iface) renderModalIPs(iface);
  2608. }
  2609. } catch (err) {
  2610. showToast('Error', err.message, 'error');
  2611. }
  2612. }
  2613. async function saveInterfaceMetadata() {
  2614. const role = document.getElementById('modal-iface-role').value;
  2615. const desc = document.getElementById('modal-iface-desc').value.trim();
  2616. try {
  2617. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2618. method: 'POST',
  2619. headers: { 'Content-Type': 'application/json' },
  2620. body: JSON.stringify({ role, description: desc })
  2621. });
  2622. if (res.ok) {
  2623. showToast('Saved', 'Metadata updated', 'success');
  2624. closeIfaceModal();
  2625. fetchData(false);
  2626. }
  2627. } catch (err) {
  2628. showToast('Error', err.message, 'error');
  2629. }
  2630. }
  2631. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2632. state.fwSubTab = 'filter';
  2633. state.routesSubTab = 'routes';
  2634. function renderRuleFlag(disabled, hasComment) {
  2635. let flags = '';
  2636. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2637. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2638. return flags || '<span class="text-slate-600">-</span>';
  2639. }
  2640. function renderActionBadge(action) {
  2641. const act = (action || '').toLowerCase();
  2642. let color = 'bg-slate-800 text-slate-300';
  2643. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2644. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2645. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2646. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2647. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2648. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2649. }
  2650. function switchFWSubTab(tab) {
  2651. state.fwSubTab = tab;
  2652. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2653. tabs.forEach(t => {
  2654. const panel = document.getElementById(`fw-subtab-${t}`);
  2655. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2656. if (panel) {
  2657. if (t === tab) panel.classList.remove('hidden');
  2658. else panel.classList.add('hidden');
  2659. }
  2660. if (btn) {
  2661. if (t === tab) {
  2662. 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';
  2663. } else {
  2664. 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';
  2665. }
  2666. }
  2667. });
  2668. const addBtn = document.getElementById('fw-primary-add-btn');
  2669. if (addBtn) {
  2670. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2671. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2672. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2673. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2674. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2675. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2676. }
  2677. if (tab === 'geo') loadGeoIP();
  2678. if (tab === 'connections') loadConnections();
  2679. setTimeout(initTableSorting, 50);
  2680. }
  2681. function openCurrentFWModal() {
  2682. if (state.fwSubTab === 'filter') openAddFilterModal();
  2683. else if (state.fwSubTab === 'nat') openAddNATModal();
  2684. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2685. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2686. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2687. else if (state.fwSubTab === 'connections') loadConnections();
  2688. }
  2689. async function loadFirewall(populateDropdowns = true) {
  2690. try {
  2691. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2692. fetch(`${API_BASE}/firewall/summary`),
  2693. fetch(`${API_BASE}/firewall/filter`),
  2694. fetch(`${API_BASE}/firewall/nat`),
  2695. fetch(`${API_BASE}/firewall/mangle`),
  2696. fetch(`${API_BASE}/firewall/address-lists`),
  2697. fetch(`${API_BASE}/firewall/geoip/status`),
  2698. fetch(`${API_BASE}/firewall/geoip/countries`)
  2699. ]);
  2700. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2701. if (filterRes.ok) state.filterRules = await filterRes.json();
  2702. if (natRes.ok) state.natRules = await natRes.json();
  2703. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2704. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2705. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2706. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2707. // Badges
  2708. const bFilter = document.getElementById('fw-badge-filter');
  2709. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2710. const bNat = document.getElementById('fw-badge-nat');
  2711. if (bNat) bNat.innerText = (state.natRules || []).length;
  2712. const bMangle = document.getElementById('fw-badge-mangle');
  2713. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2714. const bAddr = document.getElementById('fw-badge-addrlist');
  2715. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2716. const bGeo = document.getElementById('fw-badge-geo');
  2717. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2718. renderFilterRules();
  2719. renderNATRules();
  2720. renderMangleRules();
  2721. renderAddressLists();
  2722. renderGeoCountries();
  2723. if (state.fwSubTab === 'connections') {
  2724. loadConnections();
  2725. }
  2726. } catch (err) {
  2727. console.error('Failed to load firewall:', err);
  2728. }
  2729. }
  2730. // ----------------- Filter Rules -----------------
  2731. function renderFilterRules() {
  2732. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2733. const tbody = document.getElementById('filter-table-body');
  2734. const empty = document.getElementById('filter-empty');
  2735. if (!tbody) return;
  2736. tbody.innerHTML = '';
  2737. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2738. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2739. if (rules.length === 0) {
  2740. empty?.classList.remove('hidden');
  2741. return;
  2742. }
  2743. empty?.classList.add('hidden');
  2744. rules.forEach((r, idx) => {
  2745. const tr = document.createElement('tr');
  2746. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2747. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2748. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2749. let actionExtra = '';
  2750. if (r.action === 'reject') {
  2751. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2752. } else if (r.action === 'jump') {
  2753. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2754. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2755. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2756. } else if (r.action === 'log' && r.log_prefix) {
  2757. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2758. }
  2759. tr.innerHTML = `
  2760. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2761. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2762. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2763. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2764. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2765. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2766. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2767. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2768. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2769. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2770. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2771. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2772. </td>
  2773. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2774. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2775. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2776. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2777. <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>
  2778. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2779. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2780. </td>
  2781. `;
  2782. tbody.appendChild(tr);
  2783. });
  2784. }
  2785. function formatTarget(addr, list, geo) {
  2786. const parts = [];
  2787. if (addr) parts.push(`<span>${addr}</span>`);
  2788. if (list) {
  2789. const inv = list.startsWith('!') ? '!' : '';
  2790. const clean = list.replace(/^!/, '');
  2791. 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>`);
  2792. }
  2793. if (geo) {
  2794. const inv = geo.startsWith('!') ? '!' : '';
  2795. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2796. 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>`);
  2797. }
  2798. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2799. return parts.join(' ');
  2800. }
  2801. function populateInterfaceSelect(selectId, currentVal = '') {
  2802. const sel = document.getElementById(selectId);
  2803. if (!sel) return;
  2804. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2805. (state.interfaces || []).forEach(i => {
  2806. const opt = document.createElement('option');
  2807. opt.value = i.name;
  2808. opt.innerText = `${i.name} (${i.role || i.type})`;
  2809. if (i.name === currentVal) opt.selected = true;
  2810. sel.appendChild(opt);
  2811. });
  2812. }
  2813. function populateAddressListSelect(selectId, currentVal = '') {
  2814. const sel = document.getElementById(selectId);
  2815. if (!sel) return;
  2816. sel.innerHTML = '<option value="">(None)</option>';
  2817. const cleanVal = (currentVal || '').replace(/^!/, '');
  2818. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2819. customNames.forEach(name => {
  2820. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2821. const opt = document.createElement('option');
  2822. opt.value = name;
  2823. opt.innerText = `${name} (${count} entries)`;
  2824. if (name === cleanVal) opt.selected = true;
  2825. sel.appendChild(opt);
  2826. });
  2827. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2828. const opt = document.createElement('option');
  2829. opt.value = cleanVal;
  2830. opt.innerText = cleanVal;
  2831. opt.selected = true;
  2832. sel.appendChild(opt);
  2833. }
  2834. populateCommonAddrListDatalist();
  2835. }
  2836. function populateCommonAddrListDatalist() {
  2837. const dl = document.getElementById('fw-addrlist-datalist');
  2838. if (!dl) return;
  2839. dl.innerHTML = '';
  2840. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2841. names.forEach(name => {
  2842. const opt = document.createElement('option');
  2843. opt.value = name;
  2844. dl.appendChild(opt);
  2845. });
  2846. }
  2847. function populateGeoIPSelect(selectId, currentVal = '') {
  2848. const sel = document.getElementById(selectId);
  2849. if (!sel) return;
  2850. sel.innerHTML = '<option value="">(None)</option>';
  2851. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2852. // Presets optgroup
  2853. const grpPresets = document.createElement('optgroup');
  2854. grpPresets.label = '⚡ Regional Presets';
  2855. const presets = [
  2856. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2857. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2858. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2859. ];
  2860. presets.forEach(p => {
  2861. const opt = document.createElement('option');
  2862. opt.value = p.code;
  2863. opt.innerText = p.label;
  2864. if (p.code === cleanVal) opt.selected = true;
  2865. grpPresets.appendChild(opt);
  2866. });
  2867. sel.appendChild(grpPresets);
  2868. // All Countries optgroup
  2869. const grpCountries = document.createElement('optgroup');
  2870. grpCountries.label = '🌍 All Countries';
  2871. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2872. countries.forEach(c => {
  2873. const opt = document.createElement('option');
  2874. opt.value = c.code;
  2875. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2876. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2877. if (c.code === cleanVal) opt.selected = true;
  2878. grpCountries.appendChild(opt);
  2879. });
  2880. sel.appendChild(grpCountries);
  2881. }
  2882. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2883. function switchFwRuleTab(tab) {
  2884. state.activeFwRuleTab = tab;
  2885. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2886. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2887. btn.classList.add('text-slate-400', 'border-transparent');
  2888. });
  2889. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2890. if (activeBtn) {
  2891. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2892. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2893. }
  2894. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2895. const activePane = document.getElementById(`fw-pane-${tab}`);
  2896. if (activePane) activePane.classList.remove('hidden');
  2897. if (tab === 'statistics') {
  2898. startFwStatPolling();
  2899. } else {
  2900. stopFwStatPolling();
  2901. }
  2902. }
  2903. function toggleFwField(fieldKey, expand) {
  2904. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2905. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2906. if (!plusBtn || !fieldBox) return;
  2907. if (expand) {
  2908. plusBtn.classList.add('hidden');
  2909. fieldBox.classList.remove('hidden');
  2910. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2911. if (valInput) valInput.focus();
  2912. } else {
  2913. fieldBox.classList.add('hidden');
  2914. plusBtn.classList.remove('hidden');
  2915. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2916. if (valInput) {
  2917. if (valInput.tagName === 'SELECT') {
  2918. valInput.selectedIndex = 0;
  2919. } else {
  2920. valInput.value = '';
  2921. }
  2922. }
  2923. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2924. if (invInput) invInput.checked = false;
  2925. if (fieldKey === 'cs') {
  2926. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2927. const el = document.getElementById(id);
  2928. if (el) el.checked = false;
  2929. });
  2930. }
  2931. if (fieldKey === 'natstate') {
  2932. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2933. const el = document.getElementById(id);
  2934. if (el) el.checked = false;
  2935. });
  2936. }
  2937. if (fieldKey === 'days') {
  2938. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2939. const el = document.getElementById(`fw-day-${d}`);
  2940. if (el) el.checked = true;
  2941. });
  2942. }
  2943. }
  2944. }
  2945. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2946. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2947. toggleFwField(fieldKey, true);
  2948. let strVal = String(value);
  2949. if (hasInvert) {
  2950. const inv = strVal.startsWith('!');
  2951. if (inv) strVal = strVal.slice(1);
  2952. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2953. if (invEl) invEl.checked = inv;
  2954. }
  2955. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2956. if (valEl) valEl.value = strVal;
  2957. } else {
  2958. toggleFwField(fieldKey, false);
  2959. }
  2960. }
  2961. function getFwFieldVal(fieldKey, hasInvert = false) {
  2962. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2963. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2964. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2965. let v = valEl ? valEl.value.trim() : '';
  2966. if (!v) return '';
  2967. if (hasInvert) {
  2968. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2969. if (invEl && invEl.checked) {
  2970. v = '!' + v.replace(/^!/, '');
  2971. }
  2972. }
  2973. return v;
  2974. }
  2975. function toggleMaximizeFilterModal() {
  2976. const win = document.getElementById('filter-modal-window');
  2977. if (!win) return;
  2978. if (win.classList.contains('max-w-[720px]')) {
  2979. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2980. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2981. } else {
  2982. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2983. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2984. }
  2985. }
  2986. function openAddFilterModal() {
  2987. switchFwRuleTab('general');
  2988. const badge = document.getElementById('fw-modal-badge');
  2989. if (badge) badge.innerText = 'New...';
  2990. document.getElementById('filter-modal-id').value = '';
  2991. document.getElementById('filter-modal-enabled').checked = true;
  2992. document.getElementById('filter-modal-comment').value = '';
  2993. document.getElementById('filter-modal-chain').value = 'forward';
  2994. document.getElementById('filter-modal-action').value = 'accept';
  2995. document.getElementById('filter-modal-log').checked = false;
  2996. populateInterfaceSelect('fw-val-iniface');
  2997. populateInterfaceSelect('fw-val-outiface');
  2998. populateAddressListSelect('fw-val-srclist');
  2999. populateAddressListSelect('fw-val-dstlist');
  3000. populateGeoIPSelect('fw-val-srcgeo');
  3001. populateGeoIPSelect('fw-val-dstgeo');
  3002. const allFieldKeys = [
  3003. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3004. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3005. 'routingmark', 'conntype', 'cs', 'natstate',
  3006. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3007. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3008. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3009. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3010. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3011. ];
  3012. allFieldKeys.forEach(k => toggleFwField(k, false));
  3013. resetCurrentRuleCounters();
  3014. toggleFilterActionFields();
  3015. document.getElementById('filter-modal').classList.remove('hidden');
  3016. }
  3017. function openEditFilterModal(id) {
  3018. const r = (state.filterRules || []).find(rule => rule.id === id);
  3019. if (!r) return;
  3020. switchFwRuleTab('general');
  3021. const badge = document.getElementById('fw-modal-badge');
  3022. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3023. document.getElementById('filter-modal-id').value = r.id;
  3024. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3025. document.getElementById('filter-modal-comment').value = r.comment || '';
  3026. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3027. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3028. document.getElementById('filter-modal-log').checked = !!r.log;
  3029. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3030. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3031. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3032. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3033. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3034. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3035. setFwFieldVal('src', r.src_address, true);
  3036. setFwFieldVal('dst', r.dst_address, true);
  3037. setFwFieldVal('srclist', r.src_address_list, true);
  3038. setFwFieldVal('dstlist', r.dst_address_list, true);
  3039. setFwFieldVal('srcgeo', r.src_geoip, true);
  3040. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3041. if (r.protocol && r.protocol !== 'all') {
  3042. setFwFieldVal('proto', r.protocol, true);
  3043. } else {
  3044. toggleFwField('proto', false);
  3045. }
  3046. setFwFieldVal('sport', r.src_port, true);
  3047. setFwFieldVal('dport', r.dst_port, true);
  3048. setFwFieldVal('anyport', r.any_port, true);
  3049. setFwFieldVal('iniface', r.in_interface, true);
  3050. setFwFieldVal('outiface', r.out_interface, true);
  3051. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3052. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3053. setFwFieldVal('pktmark', r.packet_mark, true);
  3054. setFwFieldVal('connmark', r.connection_mark, true);
  3055. setFwFieldVal('routingmark', r.routing_mark, true);
  3056. setFwFieldVal('conntype', r.connection_type, false);
  3057. const states = r.connection_state || [];
  3058. if (states.length > 0) {
  3059. toggleFwField('cs', true);
  3060. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3061. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3062. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3063. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3064. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3065. } else {
  3066. toggleFwField('cs', false);
  3067. }
  3068. const natStates = r.connection_nat_state || [];
  3069. if (natStates.length > 0) {
  3070. toggleFwField('natstate', true);
  3071. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3072. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3073. } else {
  3074. toggleFwField('natstate', false);
  3075. }
  3076. // Advanced tab fields
  3077. setFwFieldVal('layer7', r.layer7_protocol, false);
  3078. setFwFieldVal('content', r.content, false);
  3079. setFwFieldVal('connbytes', r.connection_bytes, false);
  3080. setFwFieldVal('connrate', r.connection_rate, false);
  3081. setFwFieldVal('pcc', r.pcc, false);
  3082. setFwFieldVal('srcmac', r.src_mac_address, true);
  3083. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3084. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3085. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3086. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3087. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3088. setFwFieldVal('tlshost', r.tls_host, false);
  3089. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3090. setFwFieldVal('priority', r.priority, false);
  3091. setFwFieldVal('dscp', r.dscp, false);
  3092. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3093. if (r.tos) {
  3094. const tosEl = document.getElementById('fw-val-tos');
  3095. if (tosEl) tosEl.value = r.tos;
  3096. }
  3097. setFwFieldVal('pktsize', r.packet_size, false);
  3098. setFwFieldVal('random', r.random, false);
  3099. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3100. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3101. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3102. setFwFieldVal('ttl', r.ttl, false);
  3103. // Extra tab fields
  3104. setFwFieldVal('time', r.time, false);
  3105. if (r.days) {
  3106. toggleFwField('days', true);
  3107. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3108. const chk = document.getElementById(`fw-day-${d}`);
  3109. if (chk) chk.checked = r.days.includes(d);
  3110. });
  3111. } else {
  3112. toggleFwField('days', false);
  3113. }
  3114. setFwFieldVal('limit', r.limit, false);
  3115. setFwFieldVal('dstlimit', r.dst_limit, false);
  3116. setFwFieldVal('psd', r.psd, false);
  3117. // Action fields
  3118. if (r.reject_with) {
  3119. const rwEl = document.getElementById('filter-modal-rejectwith');
  3120. if (rwEl) rwEl.value = r.reject_with;
  3121. }
  3122. if (r.jump_target) {
  3123. const jtEl = document.getElementById('filter-modal-jumptarget');
  3124. if (jtEl) jtEl.value = r.jump_target;
  3125. }
  3126. if (r.address_list) {
  3127. const alEl = document.getElementById('filter-modal-action-addrlist');
  3128. if (alEl) alEl.value = r.address_list;
  3129. }
  3130. if (r.address_list_timeout) {
  3131. const toEl = document.getElementById('filter-modal-action-timeout');
  3132. if (toEl) toEl.value = r.address_list_timeout;
  3133. }
  3134. setFwFieldVal('logprefix', r.log_prefix, false);
  3135. // Statistics
  3136. const bEl = document.getElementById('fw-stat-bytes');
  3137. const pEl = document.getElementById('fw-stat-packets');
  3138. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3139. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3140. state.fwLastBytes = r.bytes || 0;
  3141. state.fwLastPackets = r.packets || 0;
  3142. state.fwLastTimestamp = Date.now();
  3143. state.fwStatRateHistory = new Array(30).fill(0);
  3144. state.fwStatPktHistory = new Array(30).fill(0);
  3145. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3146. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3147. toggleFilterActionFields();
  3148. document.getElementById('filter-modal').classList.remove('hidden');
  3149. }
  3150. function closeFilterModal() {
  3151. stopFwStatPolling();
  3152. document.getElementById('filter-modal').classList.add('hidden');
  3153. }
  3154. function toggleFilterActionFields() {
  3155. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3156. const rejectBox = document.getElementById('filter-action-reject-box');
  3157. const jumpBox = document.getElementById('filter-action-jump-box');
  3158. const addrBox = document.getElementById('filter-action-addrlist-box');
  3159. if (rejectBox) {
  3160. if (act === 'reject') rejectBox.classList.remove('hidden');
  3161. else rejectBox.classList.add('hidden');
  3162. }
  3163. if (jumpBox) {
  3164. if (act === 'jump') jumpBox.classList.remove('hidden');
  3165. else jumpBox.classList.add('hidden');
  3166. }
  3167. if (addrBox) {
  3168. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3169. addrBox.classList.remove('hidden');
  3170. } else {
  3171. addrBox.classList.add('hidden');
  3172. }
  3173. }
  3174. if (act === 'log') {
  3175. const logEl = document.getElementById('filter-modal-log');
  3176. if (logEl) logEl.checked = true;
  3177. toggleFwField('logprefix', true);
  3178. }
  3179. }
  3180. function toggleFwLogPrefix() {
  3181. const isLog = document.getElementById('filter-modal-log')?.checked;
  3182. toggleFwField('logprefix', !!isLog);
  3183. }
  3184. function copyFilterRule() {
  3185. document.getElementById('filter-modal-id').value = '';
  3186. const badge = document.getElementById('fw-modal-badge');
  3187. if (badge) badge.innerText = 'New...';
  3188. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3189. }
  3190. function resetCurrentRuleCounters() {
  3191. state.fwStatRateHistory = new Array(30).fill(0);
  3192. state.fwStatPktHistory = new Array(30).fill(0);
  3193. state.fwLastBytes = 0;
  3194. state.fwLastPackets = 0;
  3195. state.fwLastTimestamp = Date.now();
  3196. const bEl = document.getElementById('fw-stat-bytes');
  3197. const pEl = document.getElementById('fw-stat-packets');
  3198. const rEl = document.getElementById('fw-stat-rate');
  3199. const prEl = document.getElementById('fw-stat-pktrate');
  3200. if (bEl) bEl.value = '0 B';
  3201. if (pEl) pEl.value = '0';
  3202. if (rEl) rEl.value = '0 bps';
  3203. if (prEl) prEl.value = '0 p/s';
  3204. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3205. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3206. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3207. }
  3208. async function resetAllFwCounters() {
  3209. try {
  3210. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3211. if (res.ok) {
  3212. resetCurrentRuleCounters();
  3213. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3214. loadFirewall(false);
  3215. }
  3216. } catch (err) {
  3217. showToast('Error', err.message, 'error');
  3218. }
  3219. }
  3220. async function applyFilterRule(closeAfter = false) {
  3221. const id = document.getElementById('filter-modal-id').value;
  3222. const chain = document.getElementById('filter-modal-chain').value;
  3223. const action = document.getElementById('filter-modal-action').value;
  3224. const comment = document.getElementById('filter-modal-comment').value.trim();
  3225. const enabled = document.getElementById('filter-modal-enabled').checked;
  3226. const src = getFwFieldVal('src', true);
  3227. const dst = getFwFieldVal('dst', true);
  3228. const srclist = getFwFieldVal('srclist', true);
  3229. const dstlist = getFwFieldVal('dstlist', true);
  3230. const srcgeo = getFwFieldVal('srcgeo', true);
  3231. const dstgeo = getFwFieldVal('dstgeo', true);
  3232. const proto = getFwFieldVal('proto', true);
  3233. const sport = getFwFieldVal('sport', true);
  3234. const dport = getFwFieldVal('dport', true);
  3235. const anyport = getFwFieldVal('anyport', true);
  3236. const iniface = getFwFieldVal('iniface', true);
  3237. const outiface = getFwFieldVal('outiface', true);
  3238. const inifacelist = getFwFieldVal('inifacelist', true);
  3239. const outifacelist = getFwFieldVal('outifacelist', true);
  3240. const pktmark = getFwFieldVal('pktmark', true);
  3241. const connmark = getFwFieldVal('connmark', true);
  3242. const routingmark = getFwFieldVal('routingmark', true);
  3243. const conntype = getFwFieldVal('conntype', false);
  3244. const states = [];
  3245. const csBox = document.getElementById('fw-field-cs');
  3246. if (csBox && !csBox.classList.contains('hidden')) {
  3247. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3248. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3249. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3250. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3251. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3252. }
  3253. const natStates = [];
  3254. const natBox = document.getElementById('fw-field-natstate');
  3255. if (natBox && !natBox.classList.contains('hidden')) {
  3256. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3257. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3258. }
  3259. const payload = {
  3260. id,
  3261. chain,
  3262. action,
  3263. protocol: proto || 'all',
  3264. src_address: src,
  3265. dst_address: dst,
  3266. src_port: sport,
  3267. dst_port: dport,
  3268. any_port: anyport,
  3269. in_interface: iniface,
  3270. out_interface: outiface,
  3271. in_interface_list: inifacelist,
  3272. out_interface_list: outifacelist,
  3273. packet_mark: pktmark,
  3274. connection_mark: connmark,
  3275. routing_mark: routingmark,
  3276. connection_type: conntype,
  3277. connection_state: states,
  3278. connection_nat_state: natStates,
  3279. src_address_list: srclist,
  3280. dst_address_list: dstlist,
  3281. src_geoip: srcgeo,
  3282. dst_geoip: dstgeo,
  3283. comment,
  3284. disabled: !enabled,
  3285. // Advanced tab
  3286. layer7_protocol: getFwFieldVal('layer7', false),
  3287. content: getFwFieldVal('content', false),
  3288. connection_bytes: getFwFieldVal('connbytes', false),
  3289. connection_rate: getFwFieldVal('connrate', false),
  3290. pcc: getFwFieldVal('pcc', false),
  3291. src_mac_address: getFwFieldVal('srcmac', true),
  3292. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3293. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3294. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3295. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3296. ipsec_policy: getFwFieldVal('ipsec', false),
  3297. tls_host: getFwFieldVal('tlshost', false),
  3298. ingress_priority: getFwFieldVal('ingresspriority', false),
  3299. priority: getFwFieldVal('priority', false),
  3300. dscp: getFwFieldVal('dscp', false),
  3301. tcp_mss: getFwFieldVal('tcpmss', false),
  3302. tos: document.getElementById('fw-val-tos')?.value || '',
  3303. packet_size: getFwFieldVal('pktsize', false),
  3304. random: getFwFieldVal('random', false),
  3305. tcp_flags: getFwFieldVal('tcpflags', false),
  3306. icmp_options: getFwFieldVal('icmpoptions', false),
  3307. ipv4_options: getFwFieldVal('ipv4options', false),
  3308. ttl: getFwFieldVal('ttl', false),
  3309. // Extra tab
  3310. time: getFwFieldVal('time', false),
  3311. limit: getFwFieldVal('limit', false),
  3312. dst_limit: getFwFieldVal('dstlimit', false),
  3313. psd: getFwFieldVal('psd', false),
  3314. // Action tab
  3315. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3316. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3317. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3318. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3319. log: document.getElementById('filter-modal-log')?.checked || false,
  3320. log_prefix: getFwFieldVal('logprefix', false)
  3321. };
  3322. try {
  3323. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3324. method: 'POST',
  3325. headers: { 'Content-Type': 'application/json' },
  3326. body: JSON.stringify(payload)
  3327. });
  3328. if (res.ok) {
  3329. const data = await res.json();
  3330. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3331. loadFirewall(false);
  3332. if (closeAfter) {
  3333. closeFilterModal();
  3334. } else {
  3335. if (data.id) {
  3336. document.getElementById('filter-modal-id').value = data.id;
  3337. const badge = document.getElementById('fw-modal-badge');
  3338. if (badge) badge.innerText = `#${data.id}`;
  3339. }
  3340. }
  3341. } else {
  3342. const err = await res.json();
  3343. showToast('Error', err.message || 'Failed to save rule', 'error');
  3344. }
  3345. } catch (err) {
  3346. showToast('Error', err.message, 'error');
  3347. }
  3348. }
  3349. function submitSaveFilterRule(e) {
  3350. if (e && e.preventDefault) e.preventDefault();
  3351. return applyFilterRule(true);
  3352. }
  3353. function startFwStatPolling() {
  3354. stopFwStatPolling();
  3355. pollRuleStats();
  3356. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3357. }
  3358. function stopFwStatPolling() {
  3359. if (state.fwStatInterval) {
  3360. clearInterval(state.fwStatInterval);
  3361. state.fwStatInterval = null;
  3362. }
  3363. }
  3364. async function pollRuleStats() {
  3365. const id = document.getElementById('filter-modal-id')?.value;
  3366. if (!id) {
  3367. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3368. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3369. return;
  3370. }
  3371. try {
  3372. const res = await fetch(`${API_BASE}/firewall/filter`);
  3373. if (!res.ok) return;
  3374. const rules = await res.json();
  3375. const r = rules.find(x => x.id === id);
  3376. if (!r) return;
  3377. const now = Date.now();
  3378. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3379. state.fwLastTimestamp = now;
  3380. const curBytes = r.bytes || 0;
  3381. const curPackets = r.packets || 0;
  3382. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3383. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3384. state.fwLastBytes = curBytes;
  3385. state.fwLastPackets = curPackets;
  3386. const rateBps = Math.round((deltaBytes * 8) / dt);
  3387. const ratePkt = Math.round(deltaPkts / dt);
  3388. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3389. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3390. state.fwStatRateHistory.push(rateBps);
  3391. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3392. state.fwStatPktHistory.push(ratePkt);
  3393. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3394. const bEl = document.getElementById('fw-stat-bytes');
  3395. const pEl = document.getElementById('fw-stat-packets');
  3396. const rEl = document.getElementById('fw-stat-rate');
  3397. const prEl = document.getElementById('fw-stat-pktrate');
  3398. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3399. if (pEl) pEl.value = curPackets.toLocaleString();
  3400. if (rEl) rEl.value = formatBps(rateBps);
  3401. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3402. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3403. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3404. } catch (e) {
  3405. console.error('Error polling rule stats', e);
  3406. }
  3407. }
  3408. function formatBps(bps) {
  3409. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3410. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3411. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3412. return bps + ' bps';
  3413. }
  3414. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3415. const svg = document.getElementById(svgId);
  3416. if (!svg) return;
  3417. const w = 500;
  3418. const h = 100;
  3419. const paddingRight = 45;
  3420. const graphWidth = w - paddingRight;
  3421. const maxVal = Math.max(5, ...dataArray);
  3422. const currentVal = dataArray[dataArray.length - 1] || 0;
  3423. const leg = document.getElementById(legendId);
  3424. if (leg) {
  3425. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3426. }
  3427. let gridLines = '';
  3428. for (let i = 0; i <= 5; i++) {
  3429. const y = 8 + (i * (h - 18) / 5);
  3430. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3431. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3432. gridLines += `
  3433. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3434. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3435. `;
  3436. }
  3437. const step = graphWidth / (dataArray.length - 1);
  3438. const points = dataArray.map((val, idx) => {
  3439. const x = idx * step;
  3440. const y = (h - 10) - (val / maxVal) * (h - 20);
  3441. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3442. });
  3443. const polylineStr = points.join(' ');
  3444. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3445. svg.innerHTML = `
  3446. ${gridLines}
  3447. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3448. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3449. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3450. `;
  3451. }
  3452. async function moveFilterRule(id, dir) {
  3453. try {
  3454. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3455. method: 'POST',
  3456. headers: { 'Content-Type': 'application/json' },
  3457. body: JSON.stringify({ direction: dir })
  3458. });
  3459. if (res.ok) loadFirewall(false);
  3460. } catch (err) {
  3461. showToast('Error', err.message, 'error');
  3462. }
  3463. }
  3464. async function toggleFilterRuleState(id, disabled) {
  3465. try {
  3466. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3467. method: 'POST',
  3468. headers: { 'Content-Type': 'application/json' },
  3469. body: JSON.stringify({ disabled })
  3470. });
  3471. if (res.ok) loadFirewall(false);
  3472. } catch (err) {
  3473. showToast('Error', err.message, 'error');
  3474. }
  3475. }
  3476. async function deleteFilterRule(id) {
  3477. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3478. try {
  3479. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3480. if (res.ok) {
  3481. showToast('Deleted', 'Filter rule removed', 'success');
  3482. loadFirewall(false);
  3483. }
  3484. } catch (err) {
  3485. showToast('Error', err.message, 'error');
  3486. }
  3487. }
  3488. // ----------------- NAT Rules -----------------
  3489. function renderNATRules() {
  3490. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3491. const tbody = document.getElementById('nat-table-body');
  3492. const empty = document.getElementById('nat-empty');
  3493. if (!tbody) return;
  3494. tbody.innerHTML = '';
  3495. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3496. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3497. if (rules.length === 0) {
  3498. empty?.classList.remove('hidden');
  3499. return;
  3500. }
  3501. empty?.classList.add('hidden');
  3502. rules.forEach((r, idx) => {
  3503. const tr = document.createElement('tr');
  3504. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3505. let toTarget = '-';
  3506. if (r.action === 'jump') {
  3507. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3508. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3509. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3510. } else if (r.action === 'redirect') {
  3511. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3512. } else if (r.action === 'masquerade') {
  3513. 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>`;
  3514. } else if (r.action === 'log') {
  3515. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3516. } else {
  3517. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3518. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3519. }
  3520. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3521. tr.innerHTML = `
  3522. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3523. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3524. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3525. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3526. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3527. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3528. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3529. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3530. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3531. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3532. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3533. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3534. </td>
  3535. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3536. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3537. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3538. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3539. <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>
  3540. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3541. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3542. </td>
  3543. `;
  3544. tbody.appendChild(tr);
  3545. });
  3546. }
  3547. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3548. function switchNATRuleTab(tab) {
  3549. state.activeNATRuleTab = tab;
  3550. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3551. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3552. btn.classList.add('text-slate-400', 'border-transparent');
  3553. });
  3554. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3555. if (activeBtn) {
  3556. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3557. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3558. }
  3559. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3560. const activePane = document.getElementById(`nat-pane-${tab}`);
  3561. if (activePane) activePane.classList.remove('hidden');
  3562. if (tab === 'statistics') {
  3563. startNATStatPolling();
  3564. } else {
  3565. stopNATStatPolling();
  3566. }
  3567. }
  3568. function toggleNATField(fieldKey, expand) {
  3569. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3570. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3571. if (!plusBtn || !fieldBox) return;
  3572. if (expand) {
  3573. plusBtn.classList.add('hidden');
  3574. fieldBox.classList.remove('hidden');
  3575. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3576. if (valInput) valInput.focus();
  3577. } else {
  3578. fieldBox.classList.add('hidden');
  3579. plusBtn.classList.remove('hidden');
  3580. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3581. if (valInput) {
  3582. if (valInput.tagName === 'SELECT') {
  3583. valInput.selectedIndex = 0;
  3584. } else {
  3585. valInput.value = '';
  3586. }
  3587. }
  3588. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3589. if (invInput) invInput.checked = false;
  3590. if (fieldKey === 'days') {
  3591. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3592. const el = document.getElementById(`nat-day-${d}`);
  3593. if (el) el.checked = true;
  3594. });
  3595. }
  3596. }
  3597. }
  3598. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3599. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3600. toggleNATField(fieldKey, true);
  3601. let strVal = String(value);
  3602. if (hasInvert) {
  3603. const inv = strVal.startsWith('!');
  3604. if (inv) strVal = strVal.slice(1);
  3605. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3606. if (invEl) invEl.checked = inv;
  3607. }
  3608. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3609. if (valEl) valEl.value = strVal;
  3610. } else {
  3611. toggleNATField(fieldKey, false);
  3612. }
  3613. }
  3614. function getNATFieldVal(fieldKey, hasInvert = false) {
  3615. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3616. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3617. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3618. let v = valEl ? valEl.value.trim() : '';
  3619. if (!v) return '';
  3620. if (hasInvert) {
  3621. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3622. if (invEl && invEl.checked) {
  3623. v = '!' + v.replace(/^!/, '');
  3624. }
  3625. }
  3626. return v;
  3627. }
  3628. function toggleMaximizeNATModal() {
  3629. const win = document.getElementById('nat-modal-window');
  3630. if (!win) return;
  3631. if (win.classList.contains('max-w-[720px]')) {
  3632. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3633. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3634. } else {
  3635. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3636. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3637. }
  3638. }
  3639. function handleNATChainChange() {
  3640. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3641. const actSel = document.getElementById('nat-modal-action');
  3642. if (actSel) {
  3643. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3644. actSel.value = 'masquerade';
  3645. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3646. actSel.value = 'dst-nat';
  3647. }
  3648. }
  3649. toggleNATActionFields();
  3650. }
  3651. function toggleNATActionFields() {
  3652. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3653. const rowAddr = document.getElementById('nat-row-toaddr');
  3654. const rowPort = document.getElementById('nat-row-toport');
  3655. const jumpBox = document.getElementById('nat-action-jump-box');
  3656. const addrBox = document.getElementById('nat-action-addrlist-box');
  3657. // Hide all dynamic rows first
  3658. if (rowAddr) rowAddr.classList.add('hidden');
  3659. if (rowPort) rowPort.classList.add('hidden');
  3660. if (jumpBox) jumpBox.classList.add('hidden');
  3661. if (addrBox) addrBox.classList.add('hidden');
  3662. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3663. if (rowAddr) rowAddr.classList.remove('hidden');
  3664. if (rowPort) rowPort.classList.remove('hidden');
  3665. } else if (act === 'redirect' || act === 'masquerade') {
  3666. if (rowPort) rowPort.classList.remove('hidden');
  3667. } else if (act === 'jump') {
  3668. if (jumpBox) jumpBox.classList.remove('hidden');
  3669. } else if (act.includes('address-list') || act.includes('address list')) {
  3670. if (addrBox) addrBox.classList.remove('hidden');
  3671. }
  3672. if (act === 'log') {
  3673. const logEl = document.getElementById('nat-modal-log');
  3674. if (logEl) logEl.checked = true;
  3675. toggleNATField('logprefix', true);
  3676. }
  3677. }
  3678. function toggleNATLogPrefix() {
  3679. const isLog = document.getElementById('nat-modal-log')?.checked;
  3680. toggleNATField('logprefix', !!isLog);
  3681. }
  3682. function openAddNATModal() {
  3683. switchNATRuleTab('general');
  3684. const badge = document.getElementById('nat-modal-badge');
  3685. if (badge) badge.innerText = 'New...';
  3686. document.getElementById('nat-modal-id').value = '';
  3687. document.getElementById('nat-modal-enabled').checked = true;
  3688. document.getElementById('nat-modal-comment').value = '';
  3689. document.getElementById('nat-modal-chain').value = 'srcnat';
  3690. document.getElementById('nat-modal-action').value = 'masquerade';
  3691. document.getElementById('nat-modal-toaddr').value = '';
  3692. document.getElementById('nat-modal-toport').value = '';
  3693. document.getElementById('nat-modal-log').checked = false;
  3694. populateInterfaceSelect('nat-val-iniface');
  3695. populateInterfaceSelect('nat-val-outiface');
  3696. populateAddressListSelect('nat-val-srclist');
  3697. populateAddressListSelect('nat-val-dstlist');
  3698. populateGeoIPSelect('nat-val-srcgeo');
  3699. populateGeoIPSelect('nat-val-dstgeo');
  3700. const allFieldKeys = [
  3701. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3702. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3703. 'routingmark', 'conntype',
  3704. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3705. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3706. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3707. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3708. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3709. ];
  3710. allFieldKeys.forEach(k => toggleNATField(k, false));
  3711. resetCurrentNATRuleCounters();
  3712. toggleNATActionFields();
  3713. document.getElementById('nat-modal').classList.remove('hidden');
  3714. }
  3715. function openEditNATModal(id) {
  3716. const r = (state.natRules || []).find(rule => rule.id === id);
  3717. if (!r) return;
  3718. switchNATRuleTab('general');
  3719. const badge = document.getElementById('nat-modal-badge');
  3720. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3721. document.getElementById('nat-modal-id').value = r.id;
  3722. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3723. document.getElementById('nat-modal-comment').value = r.comment || '';
  3724. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3725. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3726. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3727. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3728. document.getElementById('nat-modal-log').checked = !!r.log;
  3729. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3730. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3731. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3732. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3733. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3734. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3735. setNATFieldVal('src', r.src_address, true);
  3736. setNATFieldVal('dst', r.dst_address, true);
  3737. setNATFieldVal('srclist', r.src_address_list, true);
  3738. setNATFieldVal('dstlist', r.dst_address_list, true);
  3739. setNATFieldVal('srcgeo', r.src_geoip, true);
  3740. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3741. if (r.protocol && r.protocol !== 'all') {
  3742. setNATFieldVal('proto', r.protocol, true);
  3743. } else {
  3744. toggleNATField('proto', false);
  3745. }
  3746. setNATFieldVal('sport', r.src_port, true);
  3747. setNATFieldVal('dport', r.dst_port, true);
  3748. setNATFieldVal('anyport', r.any_port, true);
  3749. setNATFieldVal('iniface', r.in_interface, true);
  3750. setNATFieldVal('outiface', r.out_interface, true);
  3751. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3752. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3753. setNATFieldVal('pktmark', r.packet_mark, true);
  3754. setNATFieldVal('connmark', r.connection_mark, true);
  3755. setNATFieldVal('routingmark', r.routing_mark, true);
  3756. setNATFieldVal('conntype', r.connection_type, false);
  3757. // Advanced tab fields
  3758. setNATFieldVal('layer7', r.layer7_protocol, false);
  3759. setNATFieldVal('content', r.content, false);
  3760. setNATFieldVal('connbytes', r.connection_bytes, false);
  3761. setNATFieldVal('connrate', r.connection_rate, false);
  3762. setNATFieldVal('pcc', r.pcc, false);
  3763. setNATFieldVal('srcmac', r.src_mac_address, true);
  3764. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3765. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3766. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3767. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3768. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3769. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3770. setNATFieldVal('priority', r.priority, false);
  3771. setNATFieldVal('dscp', r.dscp, false);
  3772. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3773. if (r.tos) {
  3774. const tosEl = document.getElementById('nat-val-tos');
  3775. if (tosEl) tosEl.value = r.tos;
  3776. }
  3777. setNATFieldVal('pktsize', r.packet_size, false);
  3778. setNATFieldVal('random', r.random, false);
  3779. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3780. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3781. setNATFieldVal('ttl', r.ttl, false);
  3782. // Extra tab fields
  3783. setNATFieldVal('time', r.time, false);
  3784. if (r.days) {
  3785. toggleNATField('days', true);
  3786. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3787. const chk = document.getElementById(`nat-day-${d}`);
  3788. if (chk) chk.checked = r.days.includes(d);
  3789. });
  3790. } else {
  3791. toggleNATField('days', false);
  3792. }
  3793. setNATFieldVal('limit', r.limit, false);
  3794. setNATFieldVal('dstlimit', r.dst_limit, false);
  3795. setNATFieldVal('psd', r.psd, false);
  3796. // Action fields
  3797. if (r.jump_target) {
  3798. const jtEl = document.getElementById('nat-modal-jumptarget');
  3799. if (jtEl) jtEl.value = r.jump_target;
  3800. }
  3801. if (r.address_list) {
  3802. const alEl = document.getElementById('nat-modal-action-addrlist');
  3803. if (alEl) alEl.value = r.address_list;
  3804. }
  3805. if (r.address_list_timeout) {
  3806. const toEl = document.getElementById('nat-modal-action-timeout');
  3807. if (toEl) toEl.value = r.address_list_timeout;
  3808. }
  3809. setNATFieldVal('logprefix', r.log_prefix, false);
  3810. // Statistics
  3811. const bEl = document.getElementById('nat-stat-bytes');
  3812. const pEl = document.getElementById('nat-stat-packets');
  3813. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3814. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3815. state.natLastBytes = r.bytes || 0;
  3816. state.natLastPackets = r.packets || 0;
  3817. state.natLastTimestamp = Date.now();
  3818. state.natStatRateHistory = new Array(30).fill(0);
  3819. state.natStatPktHistory = new Array(30).fill(0);
  3820. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3821. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3822. toggleNATActionFields();
  3823. document.getElementById('nat-modal').classList.remove('hidden');
  3824. }
  3825. function closeNATModal() {
  3826. stopNATStatPolling();
  3827. document.getElementById('nat-modal').classList.add('hidden');
  3828. }
  3829. function copyNATRule() {
  3830. document.getElementById('nat-modal-id').value = '';
  3831. const badge = document.getElementById('nat-modal-badge');
  3832. if (badge) badge.innerText = 'New...';
  3833. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3834. }
  3835. function resetCurrentNATRuleCounters() {
  3836. state.natStatRateHistory = new Array(30).fill(0);
  3837. state.natStatPktHistory = new Array(30).fill(0);
  3838. state.natLastBytes = 0;
  3839. state.natLastPackets = 0;
  3840. state.natLastTimestamp = Date.now();
  3841. const bEl = document.getElementById('nat-stat-bytes');
  3842. const pEl = document.getElementById('nat-stat-packets');
  3843. const rEl = document.getElementById('nat-stat-rate');
  3844. const prEl = document.getElementById('nat-stat-pktrate');
  3845. if (bEl) bEl.value = '0 B';
  3846. if (pEl) pEl.value = '0';
  3847. if (rEl) rEl.value = '0 bps';
  3848. if (prEl) prEl.value = '0 p/s';
  3849. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3850. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3851. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3852. }
  3853. async function applyNATRule(closeAfter = false) {
  3854. const id = document.getElementById('nat-modal-id').value;
  3855. const chain = document.getElementById('nat-modal-chain').value;
  3856. const action = document.getElementById('nat-modal-action').value;
  3857. const comment = document.getElementById('nat-modal-comment').value.trim();
  3858. const enabled = document.getElementById('nat-modal-enabled').checked;
  3859. const src = getNATFieldVal('src', true);
  3860. const dst = getNATFieldVal('dst', true);
  3861. const srclist = getNATFieldVal('srclist', true);
  3862. const dstlist = getNATFieldVal('dstlist', true);
  3863. const srcgeo = getNATFieldVal('srcgeo', true);
  3864. const dstgeo = getNATFieldVal('dstgeo', true);
  3865. const proto = getNATFieldVal('proto', true);
  3866. const sport = getNATFieldVal('sport', true);
  3867. const dport = getNATFieldVal('dport', true);
  3868. const anyport = getNATFieldVal('anyport', true);
  3869. const iniface = getNATFieldVal('iniface', true);
  3870. const outiface = getNATFieldVal('outiface', true);
  3871. const inifacelist = getNATFieldVal('inifacelist', true);
  3872. const outifacelist = getNATFieldVal('outifacelist', true);
  3873. const pktmark = getNATFieldVal('pktmark', true);
  3874. const connmark = getNATFieldVal('connmark', true);
  3875. const routingmark = getNATFieldVal('routingmark', true);
  3876. const conntype = getNATFieldVal('conntype', false);
  3877. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3878. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3879. const payload = {
  3880. id,
  3881. chain,
  3882. action,
  3883. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3884. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3885. protocol: proto || 'all',
  3886. src_address: src,
  3887. dst_address: dst,
  3888. src_port: sport,
  3889. dst_port: dport,
  3890. any_port: anyport,
  3891. in_interface: iniface,
  3892. out_interface: outiface,
  3893. in_interface_list: inifacelist,
  3894. out_interface_list: outifacelist,
  3895. packet_mark: pktmark,
  3896. connection_mark: connmark,
  3897. routing_mark: routingmark,
  3898. connection_type: conntype,
  3899. src_address_list: srclist,
  3900. dst_address_list: dstlist,
  3901. src_geoip: srcgeo,
  3902. dst_geoip: dstgeo,
  3903. comment,
  3904. disabled: !enabled,
  3905. // Advanced tab
  3906. layer7_protocol: getNATFieldVal('layer7', false),
  3907. content: getNATFieldVal('content', false),
  3908. connection_bytes: getNATFieldVal('connbytes', false),
  3909. connection_rate: getNATFieldVal('connrate', false),
  3910. pcc: getNATFieldVal('pcc', false),
  3911. src_mac_address: getNATFieldVal('srcmac', true),
  3912. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3913. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3914. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3915. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3916. ipsec_policy: getNATFieldVal('ipsec', false),
  3917. ingress_priority: getNATFieldVal('ingresspriority', false),
  3918. priority: getNATFieldVal('priority', false),
  3919. dscp: getNATFieldVal('dscp', false),
  3920. tcp_mss: getNATFieldVal('tcpmss', false),
  3921. tos: document.getElementById('nat-val-tos')?.value || '',
  3922. packet_size: getNATFieldVal('pktsize', false),
  3923. random: getNATFieldVal('random', false),
  3924. icmp_options: getNATFieldVal('icmpoptions', false),
  3925. ipv4_options: getNATFieldVal('ipv4options', false),
  3926. ttl: getNATFieldVal('ttl', false),
  3927. // Extra tab
  3928. time: getNATFieldVal('time', false),
  3929. limit: getNATFieldVal('limit', false),
  3930. dst_limit: getNATFieldVal('dstlimit', false),
  3931. psd: getNATFieldVal('psd', false),
  3932. // Action tab
  3933. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3934. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3935. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3936. log: document.getElementById('nat-modal-log')?.checked || false,
  3937. log_prefix: getNATFieldVal('logprefix', false)
  3938. };
  3939. try {
  3940. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3941. method: 'POST',
  3942. headers: { 'Content-Type': 'application/json' },
  3943. body: JSON.stringify(payload)
  3944. });
  3945. if (res.ok) {
  3946. const data = await res.json();
  3947. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3948. loadFirewall(false);
  3949. if (closeAfter) {
  3950. closeNATModal();
  3951. } else {
  3952. if (data.id) {
  3953. document.getElementById('nat-modal-id').value = data.id;
  3954. const badge = document.getElementById('nat-modal-badge');
  3955. if (badge) badge.innerText = `#${data.id}`;
  3956. }
  3957. }
  3958. } else {
  3959. const err = await res.json();
  3960. showToast('Error', err.message || 'Failed to save rule', 'error');
  3961. }
  3962. } catch (err) {
  3963. showToast('Error', err.message, 'error');
  3964. }
  3965. }
  3966. function submitSaveNATRule(e) {
  3967. if (e && e.preventDefault) e.preventDefault();
  3968. return applyNATRule(true);
  3969. }
  3970. function startNATStatPolling() {
  3971. stopNATStatPolling();
  3972. pollNATRuleStats();
  3973. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3974. }
  3975. function stopNATStatPolling() {
  3976. if (state.natStatInterval) {
  3977. clearInterval(state.natStatInterval);
  3978. state.natStatInterval = null;
  3979. }
  3980. }
  3981. async function pollNATRuleStats() {
  3982. const id = document.getElementById('nat-modal-id')?.value;
  3983. if (!id) {
  3984. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3985. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3986. return;
  3987. }
  3988. try {
  3989. const res = await fetch(`${API_BASE}/firewall/nat`);
  3990. if (!res.ok) return;
  3991. const rules = await res.json();
  3992. const r = rules.find(x => x.id === id);
  3993. if (!r) return;
  3994. const now = Date.now();
  3995. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3996. state.natLastTimestamp = now;
  3997. const curBytes = r.bytes || 0;
  3998. const curPackets = r.packets || 0;
  3999. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4000. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4001. state.natLastBytes = curBytes;
  4002. state.natLastPackets = curPackets;
  4003. const rateBps = Math.round((deltaBytes * 8) / dt);
  4004. const ratePkt = Math.round(deltaPkts / dt);
  4005. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4006. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4007. state.natStatRateHistory.push(rateBps);
  4008. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4009. state.natStatPktHistory.push(ratePkt);
  4010. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4011. const bEl = document.getElementById('nat-stat-bytes');
  4012. const pEl = document.getElementById('nat-stat-packets');
  4013. const rEl = document.getElementById('nat-stat-rate');
  4014. const prEl = document.getElementById('nat-stat-pktrate');
  4015. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4016. if (pEl) pEl.value = curPackets.toLocaleString();
  4017. if (rEl) rEl.value = formatBps(rateBps);
  4018. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4019. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4020. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4021. } catch (e) {
  4022. console.error('Error polling NAT rule stats', e);
  4023. }
  4024. }
  4025. async function moveNATRule(id, dir) {
  4026. try {
  4027. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4028. method: 'POST',
  4029. headers: { 'Content-Type': 'application/json' },
  4030. body: JSON.stringify({ direction: dir })
  4031. });
  4032. if (res.ok) loadFirewall(false);
  4033. } catch (err) {
  4034. showToast('Error', err.message, 'error');
  4035. }
  4036. }
  4037. async function toggleNATRuleState(id, disabled) {
  4038. try {
  4039. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4040. method: 'POST',
  4041. headers: { 'Content-Type': 'application/json' },
  4042. body: JSON.stringify({ disabled })
  4043. });
  4044. if (res.ok) loadFirewall(false);
  4045. } catch (err) {
  4046. showToast('Error', err.message, 'error');
  4047. }
  4048. }
  4049. async function deleteNATRule(id) {
  4050. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4051. try {
  4052. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4053. if (res.ok) {
  4054. showToast('Deleted', 'NAT rule removed', 'success');
  4055. loadFirewall(false);
  4056. }
  4057. } catch (err) {
  4058. showToast('Error', err.message, 'error');
  4059. }
  4060. }
  4061. // ----------------- Mangle Rules -----------------
  4062. function renderMangleRules() {
  4063. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4064. const tbody = document.getElementById('mangle-table-body');
  4065. const empty = document.getElementById('mangle-empty');
  4066. if (!tbody) return;
  4067. tbody.innerHTML = '';
  4068. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4069. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4070. if (rules.length === 0) {
  4071. empty?.classList.remove('hidden');
  4072. return;
  4073. }
  4074. empty?.classList.add('hidden');
  4075. rules.forEach((r, idx) => {
  4076. const tr = document.createElement('tr');
  4077. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4078. let markVal = '<span class="text-slate-500">-</span>';
  4079. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4080. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4081. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4082. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4083. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4084. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4085. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4086. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4087. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4088. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4089. 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>`;
  4090. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4091. tr.innerHTML = `
  4092. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4093. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4094. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4095. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4096. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4097. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4098. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4099. <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>
  4100. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4101. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4102. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4103. </td>
  4104. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4105. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4106. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4107. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4108. <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>
  4109. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4110. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4111. </td>
  4112. `;
  4113. tbody.appendChild(tr);
  4114. });
  4115. }
  4116. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4117. function switchMangleRuleTab(tab) {
  4118. state.activeMangleRuleTab = tab;
  4119. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4120. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4121. btn.classList.add('text-slate-400', 'border-transparent');
  4122. });
  4123. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4124. if (activeBtn) {
  4125. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4126. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4127. }
  4128. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4129. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4130. if (activePane) activePane.classList.remove('hidden');
  4131. if (tab === 'statistics') {
  4132. startMangleStatPolling();
  4133. } else {
  4134. stopMangleStatPolling();
  4135. }
  4136. }
  4137. function toggleMangleField(fieldKey, expand) {
  4138. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4139. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4140. if (!plusBtn || !fieldBox) return;
  4141. if (expand) {
  4142. plusBtn.classList.add('hidden');
  4143. fieldBox.classList.remove('hidden');
  4144. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4145. if (valInput) valInput.focus();
  4146. } else {
  4147. fieldBox.classList.add('hidden');
  4148. plusBtn.classList.remove('hidden');
  4149. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4150. if (valInput) {
  4151. if (valInput.tagName === 'SELECT') {
  4152. valInput.selectedIndex = 0;
  4153. } else {
  4154. valInput.value = '';
  4155. }
  4156. }
  4157. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4158. if (invInput) invInput.checked = false;
  4159. if (fieldKey === 'cs') {
  4160. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4161. const el = document.getElementById(id);
  4162. if (el) el.checked = false;
  4163. });
  4164. }
  4165. if (fieldKey === 'natstate') {
  4166. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4167. const el = document.getElementById(id);
  4168. if (el) el.checked = false;
  4169. });
  4170. }
  4171. }
  4172. }
  4173. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4174. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4175. toggleMangleField(fieldKey, true);
  4176. let strVal = String(value);
  4177. if (hasInvert) {
  4178. const inv = strVal.startsWith('!');
  4179. if (inv) strVal = strVal.slice(1);
  4180. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4181. if (invEl) invEl.checked = inv;
  4182. }
  4183. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4184. if (valEl) valEl.value = strVal;
  4185. } else {
  4186. toggleMangleField(fieldKey, false);
  4187. }
  4188. }
  4189. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4190. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4191. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4192. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4193. let v = valEl ? valEl.value.trim() : '';
  4194. if (!v) return '';
  4195. if (hasInvert) {
  4196. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4197. if (invEl && invEl.checked) {
  4198. v = '!' + v.replace(/^!/, '');
  4199. }
  4200. }
  4201. return v;
  4202. }
  4203. function toggleMaximizeMangleModal() {
  4204. const win = document.getElementById('mangle-modal-window');
  4205. if (!win) return;
  4206. if (win.classList.contains('max-w-[720px]')) {
  4207. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4208. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4209. } else {
  4210. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4211. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4212. }
  4213. }
  4214. function toggleMangleActionFields() {
  4215. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4216. // Hide all dynamic rows first
  4217. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4218. const el = document.getElementById(`mangle-row-${id}`);
  4219. if (el) el.classList.add('hidden');
  4220. });
  4221. const jumpBox = document.getElementById('mangle-action-jump-box');
  4222. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4223. if (jumpBox) jumpBox.classList.add('hidden');
  4224. if (addrBox) addrBox.classList.add('hidden');
  4225. // Activate matching rows
  4226. if (act === 'mark-connection') {
  4227. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4228. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4229. } else if (act === 'mark-routing') {
  4230. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4231. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4232. } else if (act === 'mark-packet') {
  4233. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4234. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4235. } else if (act === 'change-mss') {
  4236. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4237. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4238. } else if (act === 'change-dscp') {
  4239. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4240. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4241. } else if (act === 'change-ttl') {
  4242. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4243. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4244. } else if (act === 'set-priority') {
  4245. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4246. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4247. } else if (act === 'route') {
  4248. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4249. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4250. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4251. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4252. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4253. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4254. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4255. } else if (act === 'jump') {
  4256. if (jumpBox) jumpBox.classList.remove('hidden');
  4257. } else if (act.includes('address-list') || act.includes('address list')) {
  4258. if (addrBox) addrBox.classList.remove('hidden');
  4259. }
  4260. if (act === 'log') {
  4261. const logEl = document.getElementById('mangle-modal-log');
  4262. if (logEl) logEl.checked = true;
  4263. toggleMangleField('logprefix', true);
  4264. }
  4265. }
  4266. function toggleMangleLogPrefix() {
  4267. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4268. toggleMangleField('logprefix', !!isLog);
  4269. }
  4270. const allMangleFieldKeys = [
  4271. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4272. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4273. 'routingmark', 'conntype', 'cs', 'natstate',
  4274. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4275. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4276. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4277. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4278. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4279. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4280. ];
  4281. function openAddMangleModal() {
  4282. switchMangleRuleTab('general');
  4283. const badge = document.getElementById('mangle-modal-badge');
  4284. if (badge) badge.innerText = 'New...';
  4285. document.getElementById('mangle-modal-id').value = '';
  4286. document.getElementById('mangle-modal-enabled').checked = true;
  4287. document.getElementById('mangle-modal-comment').value = '';
  4288. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4289. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4290. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4291. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4292. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4293. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4294. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4295. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4296. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4297. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4298. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4299. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4300. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4301. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4302. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4303. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4304. populateInterfaceSelect('mangle-val-iniface');
  4305. populateInterfaceSelect('mangle-val-outiface');
  4306. populateAddressListSelect('mangle-val-srclist');
  4307. populateAddressListSelect('mangle-val-dstlist');
  4308. populateGeoIPSelect('mangle-val-srcgeo');
  4309. populateGeoIPSelect('mangle-val-dstgeo');
  4310. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4311. resetCurrentMangleRuleCounters();
  4312. toggleMangleActionFields();
  4313. document.getElementById('mangle-modal').classList.remove('hidden');
  4314. }
  4315. function openEditMangleModal(id) {
  4316. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4317. if (!r) return;
  4318. switchMangleRuleTab('general');
  4319. const badge = document.getElementById('mangle-modal-badge');
  4320. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4321. document.getElementById('mangle-modal-id').value = r.id;
  4322. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4323. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4324. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4325. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4326. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4327. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4328. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4329. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4330. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4331. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4332. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4333. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4334. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4335. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4336. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4337. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4338. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4339. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4340. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4341. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4342. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4343. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4344. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4345. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4346. setMangleFieldVal('src', r.src_address, true);
  4347. setMangleFieldVal('dst', r.dst_address, true);
  4348. setMangleFieldVal('srclist', r.src_address_list, true);
  4349. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4350. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4351. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4352. if (r.protocol && r.protocol !== 'all') {
  4353. setMangleFieldVal('proto', r.protocol, true);
  4354. } else {
  4355. toggleMangleField('proto', false);
  4356. }
  4357. setMangleFieldVal('sport', r.src_port, true);
  4358. setMangleFieldVal('dport', r.dst_port, true);
  4359. setMangleFieldVal('anyport', r.any_port, true);
  4360. setMangleFieldVal('iniface', r.in_interface, true);
  4361. setMangleFieldVal('outiface', r.out_interface, true);
  4362. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4363. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4364. setMangleFieldVal('pktmark', r.packet_mark, true);
  4365. setMangleFieldVal('connmark', r.connection_mark, true);
  4366. setMangleFieldVal('routingmark', r.routing_mark, true);
  4367. setMangleFieldVal('conntype', r.connection_type, false);
  4368. // Connection State
  4369. const states = r.connection_state || [];
  4370. if (states.length > 0) {
  4371. toggleMangleField('cs', true);
  4372. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4373. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4374. if (el) el.checked = states.includes(s);
  4375. });
  4376. } else {
  4377. toggleMangleField('cs', false);
  4378. }
  4379. // Connection NAT State
  4380. const natStates = r.connection_nat_state || [];
  4381. if (natStates.length > 0) {
  4382. toggleMangleField('natstate', true);
  4383. ['srcnat', 'dstnat'].forEach(s => {
  4384. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4385. if (el) el.checked = natStates.includes(s);
  4386. });
  4387. } else {
  4388. toggleMangleField('natstate', false);
  4389. }
  4390. // Advanced tab fields
  4391. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4392. setMangleFieldVal('content', r.content, false);
  4393. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4394. setMangleFieldVal('connrate', r.connection_rate, false);
  4395. setMangleFieldVal('pcc', r.pcc, false);
  4396. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4397. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4398. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4399. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4400. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4401. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4402. setMangleFieldVal('tlshost', r.tls_host, false);
  4403. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4404. setMangleFieldVal('priority', r.priority, false);
  4405. setMangleFieldVal('dscp', r.dscp, false);
  4406. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4407. if (r.tos) {
  4408. const tosEl = document.getElementById('mangle-val-tos');
  4409. if (tosEl) tosEl.value = r.tos;
  4410. }
  4411. setMangleFieldVal('pktsize', r.packet_size, false);
  4412. setMangleFieldVal('random', r.random, false);
  4413. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4414. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4415. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4416. setMangleFieldVal('ttl', r.ttl, false);
  4417. // Extra tab fields
  4418. setMangleFieldVal('nth', r.nth, false);
  4419. setMangleFieldVal('connlimit', r.connection_limit, false);
  4420. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4421. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4422. setMangleFieldVal('hotspot', r.hotspot, false);
  4423. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4424. setMangleFieldVal('limit', r.limit, false);
  4425. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4426. setMangleFieldVal('time', r.time, false);
  4427. setMangleFieldVal('psd', r.psd, false);
  4428. // Action fields
  4429. if (r.jump_target) {
  4430. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4431. if (jtEl) jtEl.value = r.jump_target;
  4432. }
  4433. if (r.address_list) {
  4434. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4435. if (alEl) alEl.value = r.address_list;
  4436. }
  4437. if (r.address_list_timeout) {
  4438. const toEl = document.getElementById('mangle-modal-action-timeout');
  4439. if (toEl) toEl.value = r.address_list_timeout;
  4440. }
  4441. setMangleFieldVal('logprefix', r.log_prefix, false);
  4442. // Statistics
  4443. const bEl = document.getElementById('mangle-stat-bytes');
  4444. const pEl = document.getElementById('mangle-stat-packets');
  4445. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4446. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4447. state.mangleLastBytes = r.bytes || 0;
  4448. state.mangleLastPackets = r.packets || 0;
  4449. state.mangleLastTimestamp = Date.now();
  4450. state.mangleStatRateHistory = new Array(30).fill(0);
  4451. state.mangleStatPktHistory = new Array(30).fill(0);
  4452. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4453. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4454. toggleMangleActionFields();
  4455. document.getElementById('mangle-modal').classList.remove('hidden');
  4456. }
  4457. function closeMangleModal() {
  4458. stopMangleStatPolling();
  4459. document.getElementById('mangle-modal').classList.add('hidden');
  4460. }
  4461. function copyMangleRule() {
  4462. document.getElementById('mangle-modal-id').value = '';
  4463. const badge = document.getElementById('mangle-modal-badge');
  4464. if (badge) badge.innerText = 'New...';
  4465. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4466. }
  4467. function resetCurrentMangleRuleCounters() {
  4468. state.mangleStatRateHistory = new Array(30).fill(0);
  4469. state.mangleStatPktHistory = new Array(30).fill(0);
  4470. state.mangleLastBytes = 0;
  4471. state.mangleLastPackets = 0;
  4472. state.mangleLastTimestamp = Date.now();
  4473. const bEl = document.getElementById('mangle-stat-bytes');
  4474. const pEl = document.getElementById('mangle-stat-packets');
  4475. const rEl = document.getElementById('mangle-stat-rate');
  4476. const prEl = document.getElementById('mangle-stat-pktrate');
  4477. if (bEl) bEl.value = '0 B';
  4478. if (pEl) pEl.value = '0';
  4479. if (rEl) rEl.value = '0 bps';
  4480. if (prEl) prEl.value = '0 p/s';
  4481. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4482. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4483. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4484. }
  4485. async function applyMangleRule(closeAfter = false) {
  4486. const id = document.getElementById('mangle-modal-id').value;
  4487. const chain = document.getElementById('mangle-modal-chain').value;
  4488. const action = document.getElementById('mangle-modal-action').value;
  4489. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4490. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4491. const src = getMangleFieldVal('src', true);
  4492. const dst = getMangleFieldVal('dst', true);
  4493. const srclist = getMangleFieldVal('srclist', true);
  4494. const dstlist = getMangleFieldVal('dstlist', true);
  4495. const srcgeo = getMangleFieldVal('srcgeo', true);
  4496. const dstgeo = getMangleFieldVal('dstgeo', true);
  4497. const proto = getMangleFieldVal('proto', true);
  4498. const sport = getMangleFieldVal('sport', true);
  4499. const dport = getMangleFieldVal('dport', true);
  4500. const anyport = getMangleFieldVal('anyport', true);
  4501. const iniface = getMangleFieldVal('iniface', true);
  4502. const outiface = getMangleFieldVal('outiface', true);
  4503. const inifacelist = getMangleFieldVal('inifacelist', true);
  4504. const outifacelist = getMangleFieldVal('outifacelist', true);
  4505. const pktmark = getMangleFieldVal('pktmark', true);
  4506. const connmark = getMangleFieldVal('connmark', true);
  4507. const routingmark = getMangleFieldVal('routingmark', true);
  4508. const conntype = getMangleFieldVal('conntype', false);
  4509. const states = [];
  4510. const csBox = document.getElementById('mangle-field-cs');
  4511. if (csBox && !csBox.classList.contains('hidden')) {
  4512. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4513. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4514. });
  4515. }
  4516. const natStates = [];
  4517. const natBox = document.getElementById('mangle-field-natstate');
  4518. if (natBox && !natBox.classList.contains('hidden')) {
  4519. ['srcnat', 'dstnat'].forEach(s => {
  4520. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4521. });
  4522. }
  4523. const payload = {
  4524. id,
  4525. chain,
  4526. action,
  4527. protocol: proto || 'all',
  4528. src_address: src,
  4529. dst_address: dst,
  4530. src_port: sport,
  4531. dst_port: dport,
  4532. any_port: anyport,
  4533. in_interface: iniface,
  4534. out_interface: outiface,
  4535. in_interface_list: inifacelist,
  4536. out_interface_list: outifacelist,
  4537. packet_mark: pktmark,
  4538. connection_mark: connmark,
  4539. routing_mark: routingmark,
  4540. connection_type: conntype,
  4541. connection_state: states,
  4542. connection_nat_state: natStates,
  4543. src_address_list: srclist,
  4544. dst_address_list: dstlist,
  4545. src_geoip: srcgeo,
  4546. dst_geoip: dstgeo,
  4547. comment,
  4548. disabled: !enabled,
  4549. // Advanced tab
  4550. layer7_protocol: getMangleFieldVal('layer7', false),
  4551. content: getMangleFieldVal('content', false),
  4552. connection_bytes: getMangleFieldVal('connbytes', false),
  4553. connection_rate: getMangleFieldVal('connrate', false),
  4554. pcc: getMangleFieldVal('pcc', false),
  4555. src_mac_address: getMangleFieldVal('srcmac', true),
  4556. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4557. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4558. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4559. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4560. ipsec_policy: getMangleFieldVal('ipsec', false),
  4561. tls_host: getMangleFieldVal('tlshost', false),
  4562. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4563. priority: getMangleFieldVal('priority', false),
  4564. dscp: getMangleFieldVal('dscp', false),
  4565. tcp_mss: getMangleFieldVal('tcpmss', false),
  4566. tos: document.getElementById('mangle-val-tos')?.value || '',
  4567. packet_size: getMangleFieldVal('pktsize', false),
  4568. random: getMangleFieldVal('random', false),
  4569. tcp_flags: getMangleFieldVal('tcpflags', false),
  4570. icmp_options: getMangleFieldVal('icmpoptions', false),
  4571. ipv4_options: getMangleFieldVal('ipv4options', false),
  4572. ttl: getMangleFieldVal('ttl', false),
  4573. // Extra tab
  4574. nth: getMangleFieldVal('nth', false),
  4575. connection_limit: getMangleFieldVal('connlimit', false),
  4576. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4577. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4578. hotspot: getMangleFieldVal('hotspot', false),
  4579. ip_fragment: getMangleFieldVal('ipfragment', false),
  4580. limit: getMangleFieldVal('limit', false),
  4581. dst_limit: getMangleFieldVal('dstlimit', false),
  4582. time: getMangleFieldVal('time', false),
  4583. psd: getMangleFieldVal('psd', false),
  4584. // Action tab
  4585. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4586. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4587. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4588. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4589. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4590. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4591. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4592. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4593. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4594. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4595. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4596. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4597. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4598. log: document.getElementById('mangle-modal-log')?.checked || false,
  4599. log_prefix: getMangleFieldVal('logprefix', false)
  4600. };
  4601. try {
  4602. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4603. method: 'POST',
  4604. headers: { 'Content-Type': 'application/json' },
  4605. body: JSON.stringify(payload)
  4606. });
  4607. if (res.ok) {
  4608. const data = await res.json();
  4609. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4610. loadFirewall(false);
  4611. if (closeAfter) {
  4612. closeMangleModal();
  4613. } else {
  4614. if (data.id) {
  4615. document.getElementById('mangle-modal-id').value = data.id;
  4616. const badge = document.getElementById('mangle-modal-badge');
  4617. if (badge) badge.innerText = `#${data.id}`;
  4618. }
  4619. }
  4620. } else {
  4621. const err = await res.json();
  4622. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4623. }
  4624. } catch (err) {
  4625. showToast('Error', err.message, 'error');
  4626. }
  4627. }
  4628. function submitSaveMangleRule(e) {
  4629. if (e && e.preventDefault) e.preventDefault();
  4630. return applyMangleRule(true);
  4631. }
  4632. function startMangleStatPolling() {
  4633. stopMangleStatPolling();
  4634. pollMangleRuleStats();
  4635. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4636. }
  4637. function stopMangleStatPolling() {
  4638. if (state.mangleStatInterval) {
  4639. clearInterval(state.mangleStatInterval);
  4640. state.mangleStatInterval = null;
  4641. }
  4642. }
  4643. async function pollMangleRuleStats() {
  4644. const id = document.getElementById('mangle-modal-id')?.value;
  4645. if (!id) {
  4646. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4647. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4648. return;
  4649. }
  4650. try {
  4651. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4652. if (!res.ok) return;
  4653. const rules = await res.json();
  4654. const r = rules.find(x => x.id === id);
  4655. if (!r) return;
  4656. const now = Date.now();
  4657. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4658. state.mangleLastTimestamp = now;
  4659. const curBytes = r.bytes || 0;
  4660. const curPackets = r.packets || 0;
  4661. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4662. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4663. state.mangleLastBytes = curBytes;
  4664. state.mangleLastPackets = curPackets;
  4665. const rateBps = Math.round((deltaBytes * 8) / dt);
  4666. const ratePkt = Math.round(deltaPkts / dt);
  4667. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4668. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4669. state.mangleStatRateHistory.push(rateBps);
  4670. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4671. state.mangleStatPktHistory.push(ratePkt);
  4672. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4673. const bEl = document.getElementById('mangle-stat-bytes');
  4674. const pEl = document.getElementById('mangle-stat-packets');
  4675. const rEl = document.getElementById('mangle-stat-rate');
  4676. const prEl = document.getElementById('mangle-stat-pktrate');
  4677. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4678. if (pEl) pEl.value = curPackets.toLocaleString();
  4679. if (rEl) rEl.value = formatBps(rateBps);
  4680. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4681. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4682. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4683. } catch (e) {
  4684. console.error('Error polling Mangle rule stats', e);
  4685. }
  4686. }
  4687. async function moveMangleRule(id, dir) {
  4688. try {
  4689. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4690. method: 'POST',
  4691. headers: { 'Content-Type': 'application/json' },
  4692. body: JSON.stringify({ direction: dir })
  4693. });
  4694. if (res.ok) loadFirewall(false);
  4695. } catch (err) {
  4696. showToast('Error', err.message, 'error');
  4697. }
  4698. }
  4699. async function toggleMangleRuleState(id, disabled) {
  4700. try {
  4701. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4702. method: 'POST',
  4703. headers: { 'Content-Type': 'application/json' },
  4704. body: JSON.stringify({ disabled })
  4705. });
  4706. if (res.ok) loadFirewall(false);
  4707. } catch (err) {
  4708. showToast('Error', err.message, 'error');
  4709. }
  4710. }
  4711. async function deleteMangleRule(id) {
  4712. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4713. try {
  4714. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4715. if (res.ok) {
  4716. showToast('Deleted', 'Mangle rule removed', 'success');
  4717. loadFirewall(false);
  4718. }
  4719. } catch (err) {
  4720. showToast('Error', err.message, 'error');
  4721. }
  4722. }
  4723. // ----------------- Address Lists -----------------
  4724. function renderAddressLists() {
  4725. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4726. const tbody = document.getElementById('addrlist-table-body');
  4727. const empty = document.getElementById('addrlist-empty');
  4728. if (!tbody) return;
  4729. tbody.innerHTML = '';
  4730. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4731. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4732. // Update filter select
  4733. const sel = document.getElementById('addrlist-filter-name');
  4734. if (sel) {
  4735. const cur = sel.value;
  4736. sel.innerHTML = '<option value="">All Lists</option>';
  4737. const set = new Set((state.addressLists || []).map(a => a.name));
  4738. set.forEach(n => {
  4739. const opt = document.createElement('option');
  4740. opt.value = n;
  4741. opt.innerText = n;
  4742. if (n === cur) opt.selected = true;
  4743. sel.appendChild(opt);
  4744. });
  4745. }
  4746. if (entries.length === 0) {
  4747. empty?.classList.remove('hidden');
  4748. return;
  4749. }
  4750. empty?.classList.add('hidden');
  4751. entries.forEach((e, idx) => {
  4752. const tr = document.createElement('tr');
  4753. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4754. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4755. tr.innerHTML = `
  4756. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4757. <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>
  4758. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4759. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4760. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4761. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4762. <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>
  4763. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4764. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4765. </td>
  4766. `;
  4767. tbody.appendChild(tr);
  4768. });
  4769. populateCommonAddrListDatalist();
  4770. }
  4771. function openAddAddrListModal() {
  4772. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4773. document.getElementById('addrlist-modal-id').value = '';
  4774. document.getElementById('addrlist-modal-name').value = '';
  4775. document.getElementById('addrlist-modal-addr').value = '';
  4776. document.getElementById('addrlist-modal-comment').value = '';
  4777. document.getElementById('addrlist-modal-disabled').checked = false;
  4778. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4779. if (submitBtn) submitBtn.innerText = 'Add to List';
  4780. document.getElementById('addrlist-modal').classList.remove('hidden');
  4781. }
  4782. function openEditAddrListModal(id) {
  4783. const e = (state.addressLists || []).find(item => item.id === id);
  4784. if (!e) return;
  4785. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4786. document.getElementById('addrlist-modal-id').value = e.id;
  4787. document.getElementById('addrlist-modal-name').value = e.name;
  4788. document.getElementById('addrlist-modal-addr').value = e.address;
  4789. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4790. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4791. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4792. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4793. document.getElementById('addrlist-modal').classList.remove('hidden');
  4794. }
  4795. function closeAddrListModal() {
  4796. document.getElementById('addrlist-modal').classList.add('hidden');
  4797. }
  4798. async function submitSaveAddrList(e) {
  4799. e.preventDefault();
  4800. const id = document.getElementById('addrlist-modal-id').value;
  4801. const name = document.getElementById('addrlist-modal-name').value.trim();
  4802. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4803. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4804. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4805. try {
  4806. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4807. method: 'POST',
  4808. headers: { 'Content-Type': 'application/json' },
  4809. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4810. });
  4811. if (res.ok) {
  4812. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4813. closeAddrListModal();
  4814. loadFirewall(false);
  4815. } else {
  4816. const err = await res.json();
  4817. showToast('Error', err.message || 'Failed to save address list', 'error');
  4818. }
  4819. } catch (err) {
  4820. showToast('Error', err.message, 'error');
  4821. }
  4822. }
  4823. async function toggleAddrListState(id, disabled) {
  4824. try {
  4825. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4826. method: 'POST',
  4827. headers: { 'Content-Type': 'application/json' },
  4828. body: JSON.stringify({ disabled })
  4829. });
  4830. if (res.ok) {
  4831. loadFirewall(false);
  4832. }
  4833. } catch (err) {
  4834. showToast('Error', err.message, 'error');
  4835. }
  4836. }
  4837. async function deleteAddrList(id) {
  4838. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4839. try {
  4840. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4841. if (res.ok) {
  4842. showToast('Deleted', 'Address list item removed', 'info');
  4843. loadFirewall(false);
  4844. }
  4845. } catch (err) {
  4846. showToast('Error', err.message, 'error');
  4847. }
  4848. }
  4849. // ----------------- Geo-Location IP Management -----------------
  4850. async function loadGeoIP() {
  4851. try {
  4852. const [statusRes, countriesRes] = await Promise.all([
  4853. fetch(`${API_BASE}/firewall/geoip/status`),
  4854. fetch(`${API_BASE}/firewall/geoip/countries`)
  4855. ]);
  4856. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4857. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4858. updateGeoHeader();
  4859. renderGeoCountries();
  4860. } catch (err) {
  4861. console.error('Failed to load GeoIP:', err);
  4862. }
  4863. }
  4864. function getGeoUsageMap() {
  4865. const usage = {};
  4866. const checkRule = (r, type) => {
  4867. ['src_geoip', 'dst_geoip'].forEach(field => {
  4868. let val = (r && r[field]) || '';
  4869. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4870. if (code) {
  4871. if (!usage[code]) usage[code] = [];
  4872. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4873. if (!usage[code].includes(label)) usage[code].push(label);
  4874. }
  4875. });
  4876. };
  4877. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4878. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4879. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4880. return usage;
  4881. }
  4882. function updateGeoHeader() {
  4883. const s = state.geoStatus || {};
  4884. const statusBadge = document.getElementById('geo-status-badge');
  4885. if (statusBadge) {
  4886. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4887. statusBadge.className = s.auto_update
  4888. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4889. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4890. }
  4891. const intervalLabel = document.getElementById('geo-interval-label');
  4892. if (intervalLabel) {
  4893. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4894. }
  4895. const usageMap = getGeoUsageMap();
  4896. const inUseCount = Object.keys(usageMap).length;
  4897. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4898. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4899. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4900. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4901. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4902. if (lastSyncEl) {
  4903. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4904. const d = new Date(s.last_updated);
  4905. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4906. } else {
  4907. lastSyncEl.innerText = 'Never (Sync Pending)';
  4908. }
  4909. }
  4910. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4911. if (nextSyncEl) {
  4912. if (s.next_update && !s.next_update.startsWith('0001')) {
  4913. const d = new Date(s.next_update);
  4914. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4915. } else {
  4916. nextSyncEl.innerText = '-';
  4917. }
  4918. }
  4919. const badge = document.getElementById('fw-badge-geo');
  4920. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4921. }
  4922. function renderGeoCountries() {
  4923. const tbody = document.getElementById('geo-table-body');
  4924. const empty = document.getElementById('geo-empty');
  4925. if (!tbody) return;
  4926. tbody.innerHTML = '';
  4927. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4928. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4929. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4930. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4931. const usageMap = getGeoUsageMap();
  4932. const countries = (state.geoCountries || []).filter(c => {
  4933. const isUsed = !!usageMap[c.code];
  4934. if (inUseOnly && !isUsed) return false;
  4935. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4936. if (continent && c.continent !== continent) return false;
  4937. if (q) {
  4938. const matchCode = c.code.toLowerCase().includes(q);
  4939. const matchName = c.name.toLowerCase().includes(q);
  4940. if (!matchCode && !matchName) return false;
  4941. }
  4942. return true;
  4943. });
  4944. if (countries.length === 0) {
  4945. empty?.classList.remove('hidden');
  4946. return;
  4947. }
  4948. empty?.classList.add('hidden');
  4949. countries.forEach(c => {
  4950. const tr = document.createElement('tr');
  4951. const isUsed = !!usageMap[c.code];
  4952. const rulesUsing = usageMap[c.code] || [];
  4953. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4954. let statusHtml = '';
  4955. if (isUsed) {
  4956. 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>`;
  4957. } else if (c.subnet_count > 0) {
  4958. 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>';
  4959. } else {
  4960. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4961. }
  4962. tr.innerHTML = `
  4963. <td class="py-2.5 px-3 text-center">
  4964. <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'}">
  4965. ${c.code}
  4966. </span>
  4967. </td>
  4968. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4969. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4970. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4971. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4972. </td>
  4973. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4974. <td class="py-2.5 px-3">
  4975. ${statusHtml}
  4976. </td>
  4977. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4978. <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>
  4979. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4980. </td>
  4981. `;
  4982. tbody.appendChild(tr);
  4983. });
  4984. }
  4985. function quickFilterGeo(preset) {
  4986. const searchInput = document.getElementById('geo-search-input');
  4987. const continentSel = document.getElementById('geo-continent-filter');
  4988. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4989. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4990. if (searchInput) searchInput.value = '';
  4991. if (continentSel) continentSel.value = '';
  4992. if (inUseCheck) inUseCheck.checked = false;
  4993. if (cachedCheck) cachedCheck.checked = false;
  4994. if (preset === 'GR') {
  4995. if (searchInput) searchInput.value = 'Greece';
  4996. } else if (preset === 'Europe') {
  4997. if (continentSel) continentSel.value = 'Europe';
  4998. } else if (preset === 'HIGHRISK') {
  4999. if (searchInput) searchInput.value = 'China';
  5000. }
  5001. renderGeoCountries();
  5002. }
  5003. async function toggleGeoCountry(code, enabled) {
  5004. try {
  5005. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5006. method: 'POST',
  5007. headers: { 'Content-Type': 'application/json' },
  5008. body: JSON.stringify({ enabled })
  5009. });
  5010. if (res.ok) {
  5011. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5012. loadGeoIP();
  5013. } else {
  5014. const err = await res.json();
  5015. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5016. }
  5017. } catch (err) {
  5018. showToast('Error', err.message, 'error');
  5019. }
  5020. }
  5021. async function updateGeoCountry(code) {
  5022. try {
  5023. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5024. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5025. if (res.ok) {
  5026. const data = await res.json();
  5027. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5028. loadGeoIP();
  5029. } else {
  5030. const err = await res.json();
  5031. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5032. }
  5033. } catch (err) {
  5034. showToast('Error', err.message, 'error');
  5035. }
  5036. }
  5037. async function triggerGeoUpdateNow() {
  5038. const spinner = document.getElementById('geo-update-spinner');
  5039. if (spinner) spinner.classList.remove('hidden');
  5040. try {
  5041. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5042. if (res.ok) {
  5043. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5044. setTimeout(() => {
  5045. loadGeoIP();
  5046. if (spinner) spinner.classList.add('hidden');
  5047. }, 2500);
  5048. } else {
  5049. const err = await res.json();
  5050. showToast('Notice', err.message || 'Update in progress', 'info');
  5051. if (spinner) spinner.classList.add('hidden');
  5052. }
  5053. } catch (err) {
  5054. showToast('Error', err.message, 'error');
  5055. if (spinner) spinner.classList.add('hidden');
  5056. }
  5057. }
  5058. async function applyGeoPreset(preset) {
  5059. try {
  5060. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5061. method: 'POST',
  5062. headers: { 'Content-Type': 'application/json' },
  5063. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5064. });
  5065. if (res.ok) {
  5066. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5067. loadGeoIP();
  5068. }
  5069. } catch (err) {
  5070. showToast('Error', err.message, 'error');
  5071. }
  5072. }
  5073. function openGeoIntervalModal() {
  5074. const s = state.geoStatus || {};
  5075. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5076. const sel = document.getElementById('geo-cfg-interval');
  5077. const customBox = document.getElementById('geo-cfg-custom-box');
  5078. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5079. const curHours = s.interval_hours || 24;
  5080. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5081. if (matchOption) {
  5082. sel.value = String(curHours);
  5083. customBox.classList.add('hidden');
  5084. } else {
  5085. sel.value = 'custom';
  5086. customHoursInput.value = curHours;
  5087. customBox.classList.remove('hidden');
  5088. }
  5089. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5090. }
  5091. function closeGeoIntervalModal() {
  5092. document.getElementById('geo-interval-modal').classList.add('hidden');
  5093. }
  5094. function toggleCustomGeoInterval() {
  5095. const val = document.getElementById('geo-cfg-interval').value;
  5096. const customBox = document.getElementById('geo-cfg-custom-box');
  5097. if (val === 'custom') {
  5098. customBox.classList.remove('hidden');
  5099. } else {
  5100. customBox.classList.add('hidden');
  5101. }
  5102. }
  5103. async function submitGeoIntervalSettings(e) {
  5104. e.preventDefault();
  5105. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5106. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5107. let hours = 24;
  5108. if (intervalVal === 'custom') {
  5109. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5110. } else {
  5111. hours = parseInt(intervalVal, 10) || 24;
  5112. }
  5113. try {
  5114. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5115. method: 'POST',
  5116. headers: { 'Content-Type': 'application/json' },
  5117. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5118. });
  5119. if (res.ok) {
  5120. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5121. closeGeoIntervalModal();
  5122. loadGeoIP();
  5123. } else {
  5124. const err = await res.json();
  5125. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5126. }
  5127. } catch (err) {
  5128. showToast('Error', err.message, 'error');
  5129. }
  5130. }
  5131. async function viewGeoSubnets(code, name) {
  5132. if (!name) {
  5133. const found = (state.geoCountries || []).find(x => x.code === code);
  5134. name = found ? found.name : code;
  5135. }
  5136. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5137. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5138. const listEl = document.getElementById('geo-subnets-list');
  5139. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5140. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5141. try {
  5142. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5143. if (res.ok) {
  5144. const data = await res.json();
  5145. const subnets = data.subnets || [];
  5146. if (subnets.length === 0) {
  5147. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5148. } else {
  5149. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5150. }
  5151. } else {
  5152. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5153. }
  5154. } catch (err) {
  5155. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5156. }
  5157. }
  5158. function closeGeoSubnetsModal() {
  5159. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5160. }
  5161. // ----------------- Active Connections Tracking -----------------
  5162. async function loadConnections() {
  5163. try {
  5164. const res = await fetch(`${API_BASE}/firewall/connections`);
  5165. const data = await res.json();
  5166. state.connections = Array.isArray(data) ? data : [];
  5167. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5168. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5169. renderConnections();
  5170. } catch (err) {
  5171. console.error('Failed to load connections:', err);
  5172. }
  5173. }
  5174. function renderConnections() {
  5175. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5176. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5177. const tbody = document.getElementById('conns-table-body');
  5178. const empty = document.getElementById('conns-empty');
  5179. if (!tbody) return;
  5180. tbody.innerHTML = '';
  5181. const conns = (state.connections || []).filter(c => {
  5182. if (protoFilter && c.protocol !== protoFilter) return false;
  5183. if (search) {
  5184. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5185. if (!line.includes(search)) return false;
  5186. }
  5187. return true;
  5188. });
  5189. if (conns.length === 0) {
  5190. empty?.classList.remove('hidden');
  5191. return;
  5192. }
  5193. empty?.classList.add('hidden');
  5194. conns.slice(0, 150).forEach(c => {
  5195. const tr = document.createElement('tr');
  5196. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5197. let stateColor = 'text-slate-400';
  5198. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5199. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5200. tr.innerHTML = `
  5201. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5202. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5203. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5204. <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>
  5205. <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>
  5206. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5207. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5208. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5209. <td class="py-2.5 px-3 text-right font-sans">
  5210. <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>
  5211. </td>
  5212. `;
  5213. tbody.appendChild(tr);
  5214. });
  5215. }
  5216. async function killConnection(protocol, src, sport, dst, dport) {
  5217. try {
  5218. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5219. method: 'POST',
  5220. headers: { 'Content-Type': 'application/json' },
  5221. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5222. });
  5223. if (res.ok) {
  5224. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5225. loadConnections();
  5226. }
  5227. } catch (err) {
  5228. showToast('Error', err.message, 'error');
  5229. }
  5230. }
  5231. async function resetFirewallCounters() {
  5232. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5233. try {
  5234. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5235. if (res.ok) {
  5236. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5237. loadFirewall(false);
  5238. }
  5239. } catch (err) {
  5240. showToast('Error', err.message, 'error');
  5241. }
  5242. }
  5243. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5244. function switchRoutesSubTab(tab) {
  5245. state.routesSubTab = tab;
  5246. const tabs = ['routes', 'rules', 'tables'];
  5247. tabs.forEach(t => {
  5248. const panel = document.getElementById(`routes-subtab-${t}`);
  5249. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5250. if (panel) {
  5251. if (t === tab) panel.classList.remove('hidden');
  5252. else panel.classList.add('hidden');
  5253. }
  5254. if (btn) {
  5255. if (t === tab) {
  5256. 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';
  5257. } else {
  5258. 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';
  5259. }
  5260. }
  5261. });
  5262. setTimeout(initTableSorting, 50);
  5263. }
  5264. async function loadRoutes() {
  5265. try {
  5266. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5267. fetch(`${API_BASE}/routes`),
  5268. fetch(`${API_BASE}/routing/rules`),
  5269. fetch(`${API_BASE}/routing/tables`)
  5270. ]);
  5271. if (routesRes.ok) state.routes = await routesRes.json();
  5272. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5273. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5274. const bRoutes = document.getElementById('routes-badge-routes');
  5275. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5276. const showSystem = document.getElementById('prule-show-system')?.checked;
  5277. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5278. const bRules = document.getElementById('routes-badge-rules');
  5279. if (bRules) bRules.innerText = userRules.length;
  5280. const bTables = document.getElementById('routes-badge-tables');
  5281. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5282. const bRoutesCount = document.getElementById('badge-routes-count');
  5283. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5284. renderRoutesList();
  5285. renderPolicyRules();
  5286. renderRoutingTables();
  5287. } catch (err) {
  5288. console.error('Failed to load routing:', err);
  5289. }
  5290. }
  5291. function renderRoutesList() {
  5292. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5293. const tbody = document.getElementById('routes-table-body');
  5294. const empty = document.getElementById('routes-empty');
  5295. if (!tbody) return;
  5296. tbody.innerHTML = '';
  5297. // Update table filter select
  5298. const sel = document.getElementById('routes-filter-table');
  5299. if (sel) {
  5300. const cur = sel.value;
  5301. sel.innerHTML = '<option value="">All Tables</option>';
  5302. (state.routingTables || []).forEach(t => {
  5303. const opt = document.createElement('option');
  5304. opt.value = t.name;
  5305. opt.innerText = t.name;
  5306. if (t.name === cur) opt.selected = true;
  5307. sel.appendChild(opt);
  5308. });
  5309. }
  5310. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5311. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5312. if (routes.length === 0) {
  5313. empty?.classList.remove('hidden');
  5314. return;
  5315. }
  5316. empty?.classList.add('hidden');
  5317. routes.forEach(r => {
  5318. const tr = document.createElement('tr');
  5319. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5320. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5321. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5322. let flags = '';
  5323. if (r.dynamic) flags += 'D';
  5324. if (r.active) flags += 'A';
  5325. if (r.connect) flags += 'C';
  5326. if (r.static) flags += 'S';
  5327. if (r.disabled) flags += 'X';
  5328. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5329. tr.innerHTML = `
  5330. <td class="py-2.5 px-3 text-center">
  5331. <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'}">
  5332. ${flags || '-'}
  5333. </span>
  5334. </td>
  5335. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5336. <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>
  5337. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5338. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5339. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5340. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5341. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5342. ${r.static ? `
  5343. <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>
  5344. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5345. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5346. ` : `
  5347. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5348. `}
  5349. </td>
  5350. `;
  5351. tbody.appendChild(tr);
  5352. });
  5353. }
  5354. function openAddRouteModal() {
  5355. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5356. document.getElementById('route-modal-id').value = '';
  5357. document.getElementById('route-modal-old-dst').value = '';
  5358. document.getElementById('route-modal-old-gw').value = '';
  5359. document.getElementById('route-modal-old-distance').value = '';
  5360. document.getElementById('route-modal-old-table').value = '';
  5361. document.getElementById('route-modal-old-iface').value = '';
  5362. const dstInput = document.getElementById('route-modal-dst');
  5363. const gwInput = document.getElementById('route-modal-gw');
  5364. const distInput = document.getElementById('route-modal-distance');
  5365. const ifaceSelect = document.getElementById('route-modal-iface');
  5366. const tableSelect = document.getElementById('route-modal-table');
  5367. const commentInput = document.getElementById('route-modal-comment');
  5368. const disCheck = document.getElementById('route-modal-disabled');
  5369. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5370. dstInput.disabled = false;
  5371. dstInput.value = '0.0.0.0/0';
  5372. gwInput.disabled = false;
  5373. gwInput.value = '';
  5374. distInput.disabled = false;
  5375. distInput.value = '1';
  5376. ifaceSelect.disabled = false;
  5377. tableSelect.disabled = false;
  5378. commentInput.disabled = false;
  5379. commentInput.value = '';
  5380. disCheck.disabled = false;
  5381. disCheck.checked = false;
  5382. if (saveBtn) saveBtn.classList.remove('hidden');
  5383. populateInterfaceSelect('route-modal-iface');
  5384. // Populate tables
  5385. tableSelect.innerHTML = '';
  5386. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5387. const opt = document.createElement('option');
  5388. opt.value = t.name;
  5389. opt.innerText = t.name;
  5390. if (t.name === 'main') opt.selected = true;
  5391. tableSelect.appendChild(opt);
  5392. });
  5393. document.getElementById('route-modal').classList.remove('hidden');
  5394. }
  5395. function openEditRouteModal(id) {
  5396. const r = (state.routes || []).find(route => route.id === id);
  5397. if (!r) return;
  5398. const isStatic = !!r.static;
  5399. document.getElementById('route-modal-title').innerText = isStatic
  5400. ? `Edit Route: ${r.dst_address}`
  5401. : `Route Properties (Read Only): ${r.dst_address}`;
  5402. document.getElementById('route-modal-id').value = r.id;
  5403. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5404. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5405. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5406. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5407. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5408. const dstInput = document.getElementById('route-modal-dst');
  5409. const gwInput = document.getElementById('route-modal-gw');
  5410. const distInput = document.getElementById('route-modal-distance');
  5411. const ifaceSelect = document.getElementById('route-modal-iface');
  5412. const tableSelect = document.getElementById('route-modal-table');
  5413. const commentInput = document.getElementById('route-modal-comment');
  5414. const disCheck = document.getElementById('route-modal-disabled');
  5415. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5416. dstInput.value = r.dst_address;
  5417. gwInput.value = r.gateway || '';
  5418. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5419. commentInput.value = r.comment || '';
  5420. disCheck.checked = !!r.disabled;
  5421. dstInput.disabled = !isStatic;
  5422. gwInput.disabled = !isStatic;
  5423. distInput.disabled = !isStatic;
  5424. ifaceSelect.disabled = !isStatic;
  5425. tableSelect.disabled = !isStatic;
  5426. commentInput.disabled = !isStatic;
  5427. disCheck.disabled = !isStatic;
  5428. if (saveBtn) {
  5429. if (isStatic) {
  5430. saveBtn.classList.remove('hidden');
  5431. } else {
  5432. saveBtn.classList.add('hidden');
  5433. }
  5434. }
  5435. populateInterfaceSelect('route-modal-iface', r.interface);
  5436. tableSelect.innerHTML = '';
  5437. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5438. const opt = document.createElement('option');
  5439. opt.value = t.name;
  5440. opt.innerText = t.name;
  5441. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5442. tableSelect.appendChild(opt);
  5443. });
  5444. document.getElementById('route-modal').classList.remove('hidden');
  5445. }
  5446. function closeRouteModal() {
  5447. document.getElementById('route-modal').classList.add('hidden');
  5448. }
  5449. async function submitSaveRoute(e) {
  5450. e.preventDefault();
  5451. const id = document.getElementById('route-modal-id').value;
  5452. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5453. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5454. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5455. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5456. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5457. const dst = document.getElementById('route-modal-dst').value.trim();
  5458. const gw = document.getElementById('route-modal-gw').value.trim();
  5459. const table = document.getElementById('route-modal-table').value;
  5460. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5461. const iface = document.getElementById('route-modal-iface').value;
  5462. const comment = document.getElementById('route-modal-comment').value.trim();
  5463. const disabled = document.getElementById('route-modal-disabled').checked;
  5464. if (!dst) {
  5465. showToast('Error', 'Destination address is required', 'error');
  5466. return;
  5467. }
  5468. if (!gw && !iface) {
  5469. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5470. return;
  5471. }
  5472. const payload = {
  5473. id,
  5474. old_dst_address: oldDst,
  5475. old_gateway: oldGw,
  5476. old_routing_table: oldTable,
  5477. old_interface: oldIface,
  5478. dst_address: dst,
  5479. gateway: gw || iface,
  5480. routing_table: table,
  5481. distance,
  5482. interface: iface,
  5483. comment,
  5484. disabled
  5485. };
  5486. if (oldDistStr !== undefined && oldDistStr !== '') {
  5487. payload.old_distance = parseInt(oldDistStr, 10);
  5488. }
  5489. try {
  5490. const res = await fetch(`${API_BASE}/routes`, {
  5491. method: 'POST',
  5492. headers: { 'Content-Type': 'application/json' },
  5493. body: JSON.stringify(payload)
  5494. });
  5495. if (res.ok) {
  5496. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5497. closeRouteModal();
  5498. loadRoutes();
  5499. } else {
  5500. const err = await res.json();
  5501. showToast('Error', err.message || 'Failed to save route', 'error');
  5502. }
  5503. } catch (err) {
  5504. showToast('Error', err.message, 'error');
  5505. }
  5506. }
  5507. async function toggleRouteState(id, disabled) {
  5508. try {
  5509. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5510. method: 'POST',
  5511. headers: { 'Content-Type': 'application/json' },
  5512. body: JSON.stringify({ disabled })
  5513. });
  5514. if (res.ok) loadRoutes();
  5515. } catch (err) {
  5516. showToast('Error', err.message, 'error');
  5517. }
  5518. }
  5519. async function deleteRoute(id) {
  5520. if (!confirm('Are you sure you want to delete this route?')) return;
  5521. try {
  5522. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5523. if (res.ok) {
  5524. showToast('Deleted', 'Route removed', 'success');
  5525. loadRoutes();
  5526. }
  5527. } catch (err) {
  5528. showToast('Error', err.message, 'error');
  5529. }
  5530. }
  5531. // ----------------- Policy Rules (/ip route rule) -----------------
  5532. function renderPolicyRules() {
  5533. const tbody = document.getElementById('rules-table-body');
  5534. const empty = document.getElementById('rules-empty');
  5535. if (!tbody) return;
  5536. tbody.innerHTML = '';
  5537. const showSystem = document.getElementById('prule-show-system')?.checked;
  5538. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5539. const countBadge = document.getElementById('rules-count-badge');
  5540. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5541. const bRules = document.getElementById('routes-badge-rules');
  5542. if (bRules) bRules.innerText = filtered.length;
  5543. if (filtered.length === 0) {
  5544. empty?.classList.remove('hidden');
  5545. return;
  5546. }
  5547. empty?.classList.add('hidden');
  5548. filtered.forEach(pr => {
  5549. const isSys = pr.is_default || pr.is_system;
  5550. const tr = document.createElement('tr');
  5551. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5552. tr.innerHTML = `
  5553. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5554. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5555. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5556. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5557. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5558. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5559. <td class="py-2.5 px-3 text-right font-sans">
  5560. ${!pr.is_default ? `
  5561. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5562. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5563. </td>
  5564. `;
  5565. tbody.appendChild(tr);
  5566. });
  5567. }
  5568. function openAddPolicyRuleModal() {
  5569. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5570. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5571. document.getElementById('prule-modal-mark').value = '';
  5572. document.getElementById('prule-modal-src').value = '';
  5573. document.getElementById('prule-modal-dst').value = '';
  5574. const sel = document.getElementById('prule-modal-table');
  5575. sel.innerHTML = '';
  5576. (state.routingTables || []).forEach(t => {
  5577. const opt = document.createElement('option');
  5578. opt.value = t.name;
  5579. opt.innerText = t.name;
  5580. sel.appendChild(opt);
  5581. });
  5582. document.getElementById('prule-modal').classList.remove('hidden');
  5583. }
  5584. function closePolicyRuleModal() {
  5585. document.getElementById('prule-modal').classList.add('hidden');
  5586. }
  5587. async function submitSavePolicyRule(e) {
  5588. e.preventDefault();
  5589. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5590. const mark = document.getElementById('prule-modal-mark').value.trim();
  5591. const src = document.getElementById('prule-modal-src').value.trim();
  5592. const dst = document.getElementById('prule-modal-dst').value.trim();
  5593. const table = document.getElementById('prule-modal-table').value;
  5594. const action = document.getElementById('prule-modal-action').value;
  5595. try {
  5596. const res = await fetch(`${API_BASE}/routing/rules`, {
  5597. method: 'POST',
  5598. headers: { 'Content-Type': 'application/json' },
  5599. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5600. });
  5601. if (res.ok) {
  5602. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5603. closePolicyRuleModal();
  5604. loadRoutes();
  5605. } else {
  5606. const err = await res.json();
  5607. showToast('Error', err.message, 'error');
  5608. }
  5609. } catch (err) {
  5610. showToast('Error', err.message, 'error');
  5611. }
  5612. }
  5613. async function deletePolicyRule(id) {
  5614. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5615. try {
  5616. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5617. if (res.ok) {
  5618. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5619. loadRoutes();
  5620. }
  5621. } catch (err) {
  5622. showToast('Error', err.message, 'error');
  5623. }
  5624. }
  5625. // ----------------- Routing Tables -----------------
  5626. function renderRoutingTables() {
  5627. const tbody = document.getElementById('tables-table-body');
  5628. if (!tbody) return;
  5629. tbody.innerHTML = '';
  5630. (state.routingTables || []).forEach(t => {
  5631. const tr = document.createElement('tr');
  5632. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5633. tr.innerHTML = `
  5634. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5635. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5636. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5637. `;
  5638. tbody.appendChild(tr);
  5639. });
  5640. }
  5641. function openAddTableModal() {
  5642. document.getElementById('table-modal-name').value = '';
  5643. document.getElementById('table-modal-id').value = '';
  5644. document.getElementById('table-modal-comment').value = '';
  5645. document.getElementById('table-modal').classList.remove('hidden');
  5646. }
  5647. function closeTableModal() {
  5648. document.getElementById('table-modal').classList.add('hidden');
  5649. }
  5650. async function submitSaveTable(e) {
  5651. e.preventDefault();
  5652. const name = document.getElementById('table-modal-name').value.trim();
  5653. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5654. const comment = document.getElementById('table-modal-comment').value.trim();
  5655. try {
  5656. const res = await fetch(`${API_BASE}/routing/tables`, {
  5657. method: 'POST',
  5658. headers: { 'Content-Type': 'application/json' },
  5659. body: JSON.stringify({ name, table_id: id, comment })
  5660. });
  5661. if (res.ok) {
  5662. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5663. closeTableModal();
  5664. loadRoutes();
  5665. } else {
  5666. const err = await res.json();
  5667. showToast('Error', err.message, 'error');
  5668. }
  5669. } catch (err) {
  5670. showToast('Error', err.message, 'error');
  5671. }
  5672. }
  5673. async function loadDebianConfig() {
  5674. const view = document.getElementById('debian-config-view');
  5675. view.innerText = 'Generating live configuration...';
  5676. try {
  5677. const res = await fetch(`${API_BASE}/debian/config`);
  5678. const data = await res.json();
  5679. view.innerText = data.content || '# Empty config';
  5680. } catch (err) {
  5681. view.innerText = 'Failed to generate Debian network config.';
  5682. }
  5683. }
  5684. async function saveDebianConfig() {
  5685. try {
  5686. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5687. const data = await res.json();
  5688. if (res.ok) {
  5689. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5690. loadDebianConfig();
  5691. }
  5692. } catch (err) {
  5693. showToast('Error', err.message, 'error');
  5694. }
  5695. }
  5696. function showToast(title, message, type = 'info') {
  5697. const container = document.getElementById('toast-container');
  5698. const toast = document.createElement('div');
  5699. const borderColors = {
  5700. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5701. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5702. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5703. };
  5704. 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}`;
  5705. toast.innerHTML = `
  5706. <div class="flex-1">
  5707. <div class="font-bold text-xs text-white">${title}</div>
  5708. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5709. </div>
  5710. `;
  5711. container.appendChild(toast);
  5712. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5713. setTimeout(() => {
  5714. toast.classList.add('opacity-0', 'translate-y-2');
  5715. setTimeout(() => toast.remove(), 300);
  5716. }, 4000);
  5717. }
  5718. function formatTraffic(bytesPerSec) {
  5719. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5720. const kb = bytesPerSec / 1024;
  5721. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5722. const mb = kb / 1024;
  5723. return `${mb.toFixed(2)} MB/s`;
  5724. }
  5725. function toggleSidebar() {
  5726. const sb = document.getElementById('sidebar');
  5727. sb.classList.toggle('-translate-x-full');
  5728. }
  5729. // ======================== EoIP (Ethernet over IP) ========================
  5730. async function loadEoIP(populate = true) {
  5731. try {
  5732. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5733. const data = await res.json();
  5734. state.eoipTunnels = Array.isArray(data) ? data : [];
  5735. const badge = document.getElementById('eoip-count-badge');
  5736. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5737. const sideBadge = document.getElementById('badge-eoip-count');
  5738. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5739. renderEoIPTunnels();
  5740. } catch (err) {
  5741. console.error('Failed to load EoIP:', err);
  5742. }
  5743. }
  5744. function renderEoIPTunnels() {
  5745. const tbody = document.getElementById('eoip-table-body');
  5746. const empty = document.getElementById('eoip-empty');
  5747. if (!tbody) return;
  5748. tbody.innerHTML = '';
  5749. const tunnels = state.eoipTunnels || [];
  5750. if (tunnels.length === 0) {
  5751. empty?.classList.remove('hidden');
  5752. return;
  5753. }
  5754. empty?.classList.add('hidden');
  5755. tunnels.forEach(t => {
  5756. const tr = document.createElement('tr');
  5757. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5758. tr.innerHTML = `
  5759. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5760. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5761. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5762. <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>
  5763. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5764. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5765. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5766. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5767. <td class="py-2.5 px-3 font-mono text-[11px]">
  5768. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5769. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5770. </td>
  5771. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5772. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5773. <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>
  5774. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5775. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5776. </td>
  5777. `;
  5778. tbody.appendChild(tr);
  5779. });
  5780. }
  5781. function openAddEoIPModal() {
  5782. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5783. document.getElementById('eoip-modal-id').value = '';
  5784. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5785. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5786. document.getElementById('eoip-modal-remote').value = '';
  5787. document.getElementById('eoip-modal-ip').value = '';
  5788. document.getElementById('eoip-modal-local').value = '';
  5789. document.getElementById('eoip-modal-mac').value = '';
  5790. document.getElementById('eoip-modal-mtu').value = '1500';
  5791. document.getElementById('eoip-modal-comment').value = '';
  5792. document.getElementById('eoip-modal-clampmss').checked = true;
  5793. document.getElementById('eoip-modal-disabled').checked = false;
  5794. document.getElementById('eoip-modal').classList.remove('hidden');
  5795. }
  5796. function openEditEoIPModal(id) {
  5797. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5798. if (!t) return;
  5799. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5800. document.getElementById('eoip-modal-id').value = t.id;
  5801. document.getElementById('eoip-modal-name').value = t.name;
  5802. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5803. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5804. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5805. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5806. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5807. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5808. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5809. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5810. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5811. document.getElementById('eoip-modal').classList.remove('hidden');
  5812. }
  5813. function closeEoIPModal() {
  5814. document.getElementById('eoip-modal').classList.add('hidden');
  5815. }
  5816. async function submitSaveEoIP(e) {
  5817. e.preventDefault();
  5818. const id = document.getElementById('eoip-modal-id').value;
  5819. const name = document.getElementById('eoip-modal-name').value.trim();
  5820. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5821. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5822. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5823. const local = document.getElementById('eoip-modal-local').value.trim();
  5824. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5825. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5826. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5827. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5828. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5829. try {
  5830. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5831. method: 'POST',
  5832. headers: { 'Content-Type': 'application/json' },
  5833. body: JSON.stringify({
  5834. id,
  5835. name,
  5836. tunnel_id: tunnelId,
  5837. remote_address: remote,
  5838. ip_address: ipAddress,
  5839. local_address: local,
  5840. mac_address: mac,
  5841. mtu,
  5842. clamp_mss: clampMss,
  5843. comment,
  5844. disabled
  5845. })
  5846. });
  5847. if (res.ok) {
  5848. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5849. closeEoIPModal();
  5850. loadEoIP(false);
  5851. fetchData(false);
  5852. } else {
  5853. const err = await res.json();
  5854. showToast('Error', err.message, 'error');
  5855. }
  5856. } catch (err) {
  5857. showToast('Error', err.message, 'error');
  5858. }
  5859. }
  5860. async function toggleEoIPState(id, disabled) {
  5861. try {
  5862. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5863. method: 'POST',
  5864. headers: { 'Content-Type': 'application/json' },
  5865. body: JSON.stringify({ disabled })
  5866. });
  5867. if (res.ok) {
  5868. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5869. loadEoIP(false);
  5870. fetchData(false);
  5871. }
  5872. } catch (err) {
  5873. showToast('Error', err.message, 'error');
  5874. }
  5875. }
  5876. async function deleteEoIP(id) {
  5877. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5878. try {
  5879. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5880. if (res.ok) {
  5881. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5882. loadEoIP(false);
  5883. fetchData(false);
  5884. }
  5885. } catch (err) {
  5886. showToast('Error', err.message, 'error');
  5887. }
  5888. }
  5889. // ======================== PPP Central Hub & Servers ========================
  5890. function switchPPPSubTab(tab) {
  5891. state.pppSubTab = tab;
  5892. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5893. tabs.forEach(t => {
  5894. const panel = document.getElementById(`ppp-subtab-${t}`);
  5895. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5896. if (panel) {
  5897. if (t === tab) panel.classList.remove('hidden');
  5898. else panel.classList.add('hidden');
  5899. }
  5900. if (btn) {
  5901. if (t === tab) {
  5902. 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';
  5903. } else {
  5904. 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';
  5905. }
  5906. }
  5907. });
  5908. const addBtn = document.getElementById('ppp-primary-add-btn');
  5909. if (addBtn) {
  5910. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5911. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5912. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5913. else addBtn.innerHTML = '<span>Save Config</span>';
  5914. }
  5915. if (tab === 'active') loadPPPSessions();
  5916. }
  5917. function openCurrentPPPModal() {
  5918. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5919. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5920. else if (state.pppSubTab === 'active') loadPPPSessions();
  5921. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5922. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5923. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5924. }
  5925. async function loadPPP(populateDropdowns = true) {
  5926. await Promise.all([
  5927. loadPPPSecrets(),
  5928. loadPPPProfiles(),
  5929. loadPPPServers(),
  5930. loadPPPSessions()
  5931. ]);
  5932. }
  5933. async function loadPPPSecrets() {
  5934. try {
  5935. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5936. const data = await res.json();
  5937. state.pppSecrets = Array.isArray(data) ? data : [];
  5938. const b = document.getElementById('ppp-badge-secrets');
  5939. if (b) b.innerText = state.pppSecrets.length;
  5940. const b2 = document.getElementById('secrets-count-badge');
  5941. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5942. renderPPPSecrets();
  5943. } catch (err) {
  5944. console.error('Failed to load PPP secrets:', err);
  5945. }
  5946. }
  5947. function renderPPPSecrets() {
  5948. const tbody = document.getElementById('secrets-table-body');
  5949. const empty = document.getElementById('secrets-empty');
  5950. if (!tbody) return;
  5951. tbody.innerHTML = '';
  5952. const secrets = state.pppSecrets || [];
  5953. if (secrets.length === 0) {
  5954. empty?.classList.remove('hidden');
  5955. return;
  5956. }
  5957. empty?.classList.add('hidden');
  5958. secrets.forEach(s => {
  5959. const tr = document.createElement('tr');
  5960. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5961. tr.innerHTML = `
  5962. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5963. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5964. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5965. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5966. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5967. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5968. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5969. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5970. <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>
  5971. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5972. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5973. </td>
  5974. `;
  5975. tbody.appendChild(tr);
  5976. });
  5977. }
  5978. async function loadPPPProfiles() {
  5979. try {
  5980. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5981. const data = await res.json();
  5982. state.pppProfiles = Array.isArray(data) ? data : [];
  5983. const b = document.getElementById('ppp-badge-profiles');
  5984. if (b) b.innerText = state.pppProfiles.length;
  5985. const b2 = document.getElementById('profiles-count-badge');
  5986. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5987. // Populate profile selects across modals
  5988. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5989. selects.forEach(sid => {
  5990. const el = document.getElementById(sid);
  5991. if (!el) return;
  5992. const cur = el.value;
  5993. el.innerHTML = '';
  5994. state.pppProfiles.forEach(p => {
  5995. const opt = document.createElement('option');
  5996. opt.value = p.name;
  5997. opt.innerText = `${p.name} (${p.remote_address})`;
  5998. if (p.name === cur) opt.selected = true;
  5999. el.appendChild(opt);
  6000. });
  6001. });
  6002. renderPPPProfiles();
  6003. } catch (err) {
  6004. console.error('Failed to load PPP profiles:', err);
  6005. }
  6006. }
  6007. function renderPPPProfiles() {
  6008. const tbody = document.getElementById('profiles-table-body');
  6009. if (!tbody) return;
  6010. tbody.innerHTML = '';
  6011. (state.pppProfiles || []).forEach(p => {
  6012. const isDefault = p.name.startsWith('default');
  6013. const tr = document.createElement('tr');
  6014. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6015. tr.innerHTML = `
  6016. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6017. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6018. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6019. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6020. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6021. <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>
  6022. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6023. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6024. ${!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>`}
  6025. </td>
  6026. `;
  6027. tbody.appendChild(tr);
  6028. });
  6029. }
  6030. async function loadPPPServers() {
  6031. try {
  6032. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6033. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6034. fetch(`${API_BASE}/vpn/servers/pptp`),
  6035. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6036. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6037. ]);
  6038. if (pppoeRes.ok) {
  6039. state.pppoeServer = await pppoeRes.json();
  6040. const s = state.pppoeServer;
  6041. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6042. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6043. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6044. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6045. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6046. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6047. const pill = document.getElementById('pppoe-server-status-pill');
  6048. if (pill) {
  6049. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6050. 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';
  6051. }
  6052. setDotBadge('ppp-badge-pppoe-state', s.running);
  6053. }
  6054. if (pptpRes.ok) {
  6055. state.pptpServer = await pptpRes.json();
  6056. const s = state.pptpServer;
  6057. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6058. document.getElementById('pptp-server-port').value = s.port || 1723;
  6059. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6060. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6061. const pill = document.getElementById('pptp-server-status-pill');
  6062. if (pill) {
  6063. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6064. 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';
  6065. }
  6066. setDotBadge('ppp-badge-pptp-state', s.running);
  6067. }
  6068. if (l2tpRes.ok) {
  6069. state.l2tpServer = await l2tpRes.json();
  6070. const s = state.l2tpServer;
  6071. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6072. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6073. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6074. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6075. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6076. const pill = document.getElementById('l2tp-server-status-pill');
  6077. if (pill) {
  6078. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6079. 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';
  6080. }
  6081. setDotBadge('ppp-badge-l2tp-state', s.running);
  6082. }
  6083. if (ipsecRes.ok) {
  6084. state.ipsecServer = await ipsecRes.json();
  6085. const s = state.ipsecServer;
  6086. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6087. if (modalEn) modalEn.checked = !!s.enabled;
  6088. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6089. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6090. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6091. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6092. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6093. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6094. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6095. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6096. const pill = document.getElementById('modal-ipsec-server-status');
  6097. if (pill) {
  6098. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6099. 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';
  6100. }
  6101. }
  6102. } catch (err) {
  6103. console.error('Failed to load VPN servers:', err);
  6104. }
  6105. }
  6106. async function loadPPPSessions() {
  6107. try {
  6108. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6109. const data = await res.json();
  6110. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6111. const b = document.getElementById('ppp-badge-active');
  6112. if (b) b.innerText = state.pppActiveSessions.length;
  6113. const sideB = document.getElementById('badge-ppp-sessions');
  6114. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6115. renderPPPSessions();
  6116. } catch (err) {
  6117. console.error('Failed to load active PPP sessions:', err);
  6118. }
  6119. }
  6120. function renderPPPSessions() {
  6121. const tbody = document.getElementById('active-ppp-table-body');
  6122. const empty = document.getElementById('active-ppp-empty');
  6123. if (!tbody) return;
  6124. tbody.innerHTML = '';
  6125. const list = state.pppActiveSessions || [];
  6126. if (list.length === 0) {
  6127. empty?.classList.remove('hidden');
  6128. return;
  6129. }
  6130. empty?.classList.add('hidden');
  6131. list.forEach(s => {
  6132. const tr = document.createElement('tr');
  6133. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6134. tr.innerHTML = `
  6135. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6136. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6137. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6138. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6139. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6140. <td class="py-2.5 px-3 text-[11px]">
  6141. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6142. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6143. </td>
  6144. <td class="py-2.5 px-3 text-right font-sans">
  6145. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6146. </td>
  6147. `;
  6148. tbody.appendChild(tr);
  6149. });
  6150. }
  6151. async function disconnectPPPSession(iface) {
  6152. if (!confirm(`Disconnect session ${iface}?`)) return;
  6153. try {
  6154. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6155. if (res.ok) {
  6156. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6157. loadPPPSessions();
  6158. }
  6159. } catch (err) {
  6160. showToast('Error', err.message, 'error');
  6161. }
  6162. }
  6163. // PPP Secret Modal handlers
  6164. function openAddPPPSecretModal() {
  6165. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6166. document.getElementById('secret-modal-id').value = '';
  6167. document.getElementById('secret-modal-name').value = '';
  6168. document.getElementById('secret-modal-password').value = '';
  6169. document.getElementById('secret-modal-service').value = 'any';
  6170. document.getElementById('secret-modal-profile').value = 'default';
  6171. document.getElementById('secret-modal-local').value = '';
  6172. document.getElementById('secret-modal-remote').value = '';
  6173. document.getElementById('secret-modal-comment').value = '';
  6174. document.getElementById('secret-modal-disabled').checked = false;
  6175. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6176. }
  6177. function openEditPPPSecretModal(id) {
  6178. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6179. if (!s) return;
  6180. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6181. document.getElementById('secret-modal-id').value = s.id;
  6182. document.getElementById('secret-modal-name').value = s.name;
  6183. document.getElementById('secret-modal-password').value = s.password;
  6184. document.getElementById('secret-modal-service').value = s.service || 'any';
  6185. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6186. document.getElementById('secret-modal-local').value = s.local_address || '';
  6187. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6188. document.getElementById('secret-modal-comment').value = s.comment || '';
  6189. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6190. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6191. }
  6192. function closePPPSecretModal() {
  6193. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6194. }
  6195. async function submitSavePPPSecret(e) {
  6196. e.preventDefault();
  6197. const id = document.getElementById('secret-modal-id').value;
  6198. const name = document.getElementById('secret-modal-name').value.trim();
  6199. const password = document.getElementById('secret-modal-password').value.trim();
  6200. const service = document.getElementById('secret-modal-service').value;
  6201. const profile = document.getElementById('secret-modal-profile').value;
  6202. const local = document.getElementById('secret-modal-local').value.trim();
  6203. const remote = document.getElementById('secret-modal-remote').value.trim();
  6204. const comment = document.getElementById('secret-modal-comment').value.trim();
  6205. const disabled = document.getElementById('secret-modal-disabled').checked;
  6206. try {
  6207. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6208. method: 'POST',
  6209. headers: { 'Content-Type': 'application/json' },
  6210. body: JSON.stringify({
  6211. id,
  6212. name,
  6213. password,
  6214. service,
  6215. profile,
  6216. local_address: local,
  6217. remote_address: remote,
  6218. comment,
  6219. disabled
  6220. })
  6221. });
  6222. if (res.ok) {
  6223. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6224. closePPPSecretModal();
  6225. loadPPPSecrets();
  6226. } else {
  6227. const err = await res.json();
  6228. showToast('Error', err.message, 'error');
  6229. }
  6230. } catch (err) {
  6231. showToast('Error', err.message, 'error');
  6232. }
  6233. }
  6234. async function togglePPPSecretState(id, disabled) {
  6235. try {
  6236. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6237. method: 'POST',
  6238. headers: { 'Content-Type': 'application/json' },
  6239. body: JSON.stringify({ disabled })
  6240. });
  6241. if (res.ok) {
  6242. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6243. loadPPPSecrets();
  6244. }
  6245. } catch (err) {
  6246. showToast('Error', err.message, 'error');
  6247. }
  6248. }
  6249. async function deletePPPSecret(id) {
  6250. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6251. try {
  6252. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6253. if (res.ok) {
  6254. showToast('Deleted', 'Secret account removed', 'success');
  6255. loadPPPSecrets();
  6256. }
  6257. } catch (err) {
  6258. showToast('Error', err.message, 'error');
  6259. }
  6260. }
  6261. // PPP Profile Modal handlers
  6262. function openAddPPPProfileModal() {
  6263. document.getElementById('profile-modal-name').value = '';
  6264. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6265. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6266. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6267. document.getElementById('profile-modal-encryption').value = 'required';
  6268. document.getElementById('profile-modal-onlyone').checked = true;
  6269. document.getElementById('profile-modal-comment').value = '';
  6270. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6271. }
  6272. function closePPPProfileModal() {
  6273. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6274. }
  6275. async function submitSavePPPProfile(e) {
  6276. e.preventDefault();
  6277. const name = document.getElementById('profile-modal-name').value.trim();
  6278. const local = document.getElementById('profile-modal-local').value.trim();
  6279. const remote = document.getElementById('profile-modal-remote').value.trim();
  6280. const dns = document.getElementById('profile-modal-dns').value.trim();
  6281. const enc = document.getElementById('profile-modal-encryption').value;
  6282. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6283. const comment = document.getElementById('profile-modal-comment').value.trim();
  6284. try {
  6285. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6286. method: 'POST',
  6287. headers: { 'Content-Type': 'application/json' },
  6288. body: JSON.stringify({
  6289. id: name,
  6290. name,
  6291. local_address: local,
  6292. remote_address: remote,
  6293. dns_servers: dns,
  6294. use_encryption: enc,
  6295. only_one: onlyone,
  6296. comment
  6297. })
  6298. });
  6299. if (res.ok) {
  6300. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6301. closePPPProfileModal();
  6302. loadPPPProfiles();
  6303. } else {
  6304. const err = await res.json();
  6305. showToast('Error', err.message, 'error');
  6306. }
  6307. } catch (err) {
  6308. showToast('Error', err.message, 'error');
  6309. }
  6310. }
  6311. async function deletePPPProfile(name) {
  6312. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6313. try {
  6314. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6315. if (res.ok) {
  6316. showToast('Deleted', 'Profile removed', 'success');
  6317. loadPPPProfiles();
  6318. } else {
  6319. const err = await res.json();
  6320. showToast('Error', err.message, 'error');
  6321. }
  6322. } catch (err) {
  6323. showToast('Error', err.message, 'error');
  6324. }
  6325. }
  6326. // Server Config submissions
  6327. async function savePPPoEServerConfig(e) {
  6328. e.preventDefault();
  6329. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6330. const name = document.getElementById('pppoe-server-name').value.trim();
  6331. const iface = document.getElementById('pppoe-server-iface').value;
  6332. const profile = document.getElementById('pppoe-server-profile').value;
  6333. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6334. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6335. try {
  6336. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6337. method: 'POST',
  6338. headers: { 'Content-Type': 'application/json' },
  6339. body: JSON.stringify({
  6340. enabled,
  6341. service_name: name,
  6342. interface: iface,
  6343. default_profile: profile,
  6344. max_mtu: mtu,
  6345. max_mru: mtu,
  6346. one_session_per_host: onesession
  6347. })
  6348. });
  6349. if (res.ok) {
  6350. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6351. loadPPPServers();
  6352. fetchData(false);
  6353. } else {
  6354. const err = await res.json();
  6355. showToast('Error', err.message, 'error');
  6356. }
  6357. } catch (err) {
  6358. showToast('Error', err.message, 'error');
  6359. }
  6360. }
  6361. async function savePPTPServerConfig(e) {
  6362. e.preventDefault();
  6363. const enabled = document.getElementById('pptp-server-enabled').checked;
  6364. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6365. const profile = document.getElementById('pptp-server-profile').value;
  6366. const mppe = document.getElementById('pptp-server-mppe').checked;
  6367. try {
  6368. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6369. method: 'POST',
  6370. headers: { 'Content-Type': 'application/json' },
  6371. body: JSON.stringify({
  6372. enabled,
  6373. port,
  6374. default_profile: profile,
  6375. require_mppe: mppe
  6376. })
  6377. });
  6378. if (res.ok) {
  6379. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6380. loadPPPServers();
  6381. fetchData(false);
  6382. } else {
  6383. const err = await res.json();
  6384. showToast('Error', err.message, 'error');
  6385. }
  6386. } catch (err) {
  6387. showToast('Error', err.message, 'error');
  6388. }
  6389. }
  6390. async function saveL2TPServerConfig(e) {
  6391. e.preventDefault();
  6392. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6393. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6394. const profile = document.getElementById('l2tp-server-profile').value;
  6395. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6396. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6397. try {
  6398. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6399. method: 'POST',
  6400. headers: { 'Content-Type': 'application/json' },
  6401. body: JSON.stringify({
  6402. enabled,
  6403. port,
  6404. default_profile: profile,
  6405. use_ipsec: useipsec,
  6406. ipsec_secret: psk
  6407. })
  6408. });
  6409. if (res.ok) {
  6410. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6411. loadPPPServers();
  6412. fetchData(false);
  6413. } else {
  6414. const err = await res.json();
  6415. showToast('Error', err.message, 'error');
  6416. }
  6417. } catch (err) {
  6418. showToast('Error', err.message, 'error');
  6419. }
  6420. }
  6421. // IPSec Server Modal
  6422. function openIPSecServerModal() {
  6423. loadPPPServers();
  6424. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6425. }
  6426. function closeIPSecServerModal() {
  6427. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6428. }
  6429. async function submitSaveIPSecServer(e) {
  6430. e.preventDefault();
  6431. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6432. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6433. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6434. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6435. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6436. try {
  6437. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6438. method: 'POST',
  6439. headers: { 'Content-Type': 'application/json' },
  6440. body: JSON.stringify({
  6441. enabled,
  6442. preshared_key: psk,
  6443. pool_address: pool,
  6444. dns_servers: dns,
  6445. local_subnet: subnet
  6446. })
  6447. });
  6448. if (res.ok) {
  6449. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6450. closeIPSecServerModal();
  6451. loadPPPServers();
  6452. fetchData(false);
  6453. } else {
  6454. const err = await res.json();
  6455. showToast('Error', err.message, 'error');
  6456. }
  6457. } catch (err) {
  6458. showToast('Error', err.message, 'error');
  6459. }
  6460. }
  6461. // WireGuard Client Config Viewer
  6462. let currentWGClientConf = '';
  6463. async function openWGClientConfModal(iface, clientIP) {
  6464. try {
  6465. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6466. method: 'POST',
  6467. headers: { 'Content-Type': 'application/json' },
  6468. body: JSON.stringify({
  6469. interface: iface,
  6470. address: clientIP || '10.10.0.2/32',
  6471. dns: '1.1.1.1, 8.8.8.8'
  6472. })
  6473. });
  6474. if (res.ok) {
  6475. const data = await res.json();
  6476. currentWGClientConf = data.config;
  6477. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6478. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6479. } else {
  6480. const err = await res.json();
  6481. showToast('Error', err.message, 'error');
  6482. }
  6483. } catch (err) {
  6484. showToast('Error', err.message, 'error');
  6485. }
  6486. }
  6487. function closeWGClientConfModal() {
  6488. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6489. }
  6490. function copyWGClientConf() {
  6491. if (!currentWGClientConf) return;
  6492. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6493. }
  6494. function downloadWGClientConf() {
  6495. if (!currentWGClientConf) return;
  6496. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6497. const a = document.createElement('a');
  6498. a.href = URL.createObjectURL(blob);
  6499. a.download = 'wireguard-client.conf';
  6500. document.body.appendChild(a);
  6501. a.click();
  6502. document.body.removeChild(a);
  6503. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6504. }
  6505. // =========================================================================
  6506. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6507. // =========================================================================
  6508. state.activeDynSubTab = 'bgp-peers';
  6509. state.activeBgpSubTab = 'bgp-peers';
  6510. state.activeOspfTab = 'instances';
  6511. state.bgpInstance = null;
  6512. state.bgpPeers = [];
  6513. state.bgpNets = [];
  6514. state.bgpRoutes = [];
  6515. state.ospfInstance = null;
  6516. state.ospfInstances = [];
  6517. state.ospfAreas = [];
  6518. state.ospfAreaRanges = [];
  6519. state.ospfTemplates = [];
  6520. state.ospfLiveInterfaces = [];
  6521. state.ospfStaticNbrs = [];
  6522. state.ospfNeighbors = [];
  6523. state.ospfLSA = [];
  6524. state.ospfRoutes = [];
  6525. state.selectedOspfRow = {
  6526. instances: null,
  6527. areas: null,
  6528. 'area-ranges': null,
  6529. templates: null,
  6530. interfaces: null,
  6531. 'static-nbrs': null,
  6532. neighbors: null,
  6533. lsa: null,
  6534. };
  6535. state.ospfSort = {
  6536. instances: { col: 'name', asc: true },
  6537. areas: { col: 'name', asc: true },
  6538. ranges: { col: 'area', asc: true },
  6539. templates: { col: 'interfaces', asc: true },
  6540. live_ifaces: { col: 'interface', asc: true },
  6541. snbrs: { col: 'address', asc: true },
  6542. neighbors: { col: 'address', asc: true },
  6543. lsa: { col: 'instance', asc: true },
  6544. };
  6545. function switchBgpSubTab(subTab) {
  6546. state.activeBgpSubTab = subTab;
  6547. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6548. tabs.forEach(t => {
  6549. const el = document.getElementById(`dyn-subtab-${t}`);
  6550. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6551. if (el) el.classList.toggle('hidden', t !== subTab);
  6552. if (btn) {
  6553. if (t === subTab) {
  6554. 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';
  6555. } else {
  6556. 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';
  6557. }
  6558. }
  6559. });
  6560. }
  6561. function switchOspfTab(tabName) {
  6562. state.activeOspfTab = tabName;
  6563. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6564. tabs.forEach(t => {
  6565. const pane = document.getElementById(`ospf-pane-${t}`);
  6566. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6567. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6568. if (btn) {
  6569. if (t === tabName) {
  6570. 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';
  6571. } else {
  6572. 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';
  6573. }
  6574. }
  6575. });
  6576. }
  6577. function switchOspfSubTab(tab) {
  6578. // Legacy alias
  6579. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6580. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6581. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6582. else switchOspfTab('instances');
  6583. }
  6584. function switchDynSubTab(subTab) {
  6585. if (subTab.startsWith('bgp')) {
  6586. if (state.activeTab !== 'bgp') navigate('bgp');
  6587. switchBgpSubTab(subTab);
  6588. } else if (subTab.startsWith('ospf')) {
  6589. if (state.activeTab !== 'ospf') navigate('ospf');
  6590. switchOspfTab('instances');
  6591. }
  6592. }
  6593. async function loadDynamicRouting(showToastMsg = false) {
  6594. try {
  6595. const fetchSafeJson = async (url) => {
  6596. try {
  6597. const r = await fetch(url);
  6598. return r.ok ? await r.json() : null;
  6599. } catch (e) {
  6600. return null;
  6601. }
  6602. };
  6603. const [
  6604. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6605. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6606. selectRules, commLists, asLists
  6607. ] = await Promise.all([
  6608. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6609. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6610. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6611. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6612. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6613. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6614. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6615. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6616. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6617. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6618. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6619. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6620. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6621. fetchSafeJson(`${API_BASE}/routing/filters`),
  6622. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6623. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6624. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6625. ]);
  6626. if (sum) state.dynSummary = sum;
  6627. if (bgpInst) state.bgpInstance = bgpInst;
  6628. if (bgpPeers) state.bgpPeers = bgpPeers;
  6629. if (bgpNets) state.bgpNets = bgpNets;
  6630. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6631. if (ospfInsts) state.ospfInstances = ospfInsts;
  6632. if (ospfAreas) state.ospfAreas = ospfAreas;
  6633. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6634. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6635. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6636. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6637. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6638. if (ospfLsa) state.ospfLSA = ospfLsa;
  6639. if (filters) state.routingFilters = filters;
  6640. if (selectRules) state.routingSelectRules = selectRules;
  6641. if (commLists) state.routingCommunityLists = commLists;
  6642. if (asLists) state.routingASLists = asLists;
  6643. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6644. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6645. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6646. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6647. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6648. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6649. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6650. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6651. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6652. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6653. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6654. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6655. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6656. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6657. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6658. } catch (err) {
  6659. console.error('Failed to load dynamic routing:', err);
  6660. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6661. }
  6662. }
  6663. async function loadOspfAll() {
  6664. await loadDynamicRouting(true);
  6665. }
  6666. function renderBgpStatusPill() {
  6667. const pill = document.getElementById('bgp-live-status-pill');
  6668. if (!pill) return;
  6669. const inst = state.bgpInstance;
  6670. if (!inst || !inst.enabled) {
  6671. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6672. pill.innerText = 'BGP DISABLED';
  6673. } else if (inst.running) {
  6674. 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';
  6675. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6676. } else {
  6677. 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';
  6678. pill.innerText = 'BGP STARTING...';
  6679. }
  6680. }
  6681. function renderBgpPeers() {
  6682. const tbody = document.getElementById('bgp-peers-table-body');
  6683. if (!tbody) return;
  6684. const empty = document.getElementById('bgp-peers-empty');
  6685. const countBadge = document.getElementById('bgp-peers-count-badge');
  6686. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6687. const peers = state.bgpPeers || [];
  6688. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6689. if (navBadge) navBadge.innerText = peers.length;
  6690. if (peers.length === 0) {
  6691. tbody.innerHTML = '';
  6692. if (empty) empty.classList.remove('hidden');
  6693. return;
  6694. }
  6695. if (empty) empty.classList.add('hidden');
  6696. tbody.innerHTML = peers.map(p => {
  6697. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6698. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6699. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6700. let stateBadge = '';
  6701. if (p.disabled) {
  6702. 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>';
  6703. } else if (p.state === 'Established') {
  6704. 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>';
  6705. } else if (p.state === 'Connect' || p.state === 'Active') {
  6706. 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>`;
  6707. } else {
  6708. 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>`;
  6709. }
  6710. return `
  6711. <tr class="hover:bg-slate-800/40 transition">
  6712. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6713. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6714. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6715. <td class="py-2.5 px-3">
  6716. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6717. ${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>`}
  6718. </td>
  6719. <td class="py-2.5 px-3">${stateBadge}</td>
  6720. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6721. <td class="py-2.5 px-3 text-slate-300">
  6722. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6723. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6724. </td>
  6725. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6726. ${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> ` : ''}
  6727. ${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>` : ''}
  6728. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6729. </td>
  6730. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6731. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6732. <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'}">
  6733. ${p.disabled ? 'Enable' : 'Disable'}
  6734. </button>
  6735. <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">
  6736. Edit
  6737. </button>
  6738. <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">
  6739. Delete
  6740. </button>
  6741. </td>
  6742. </tr>
  6743. `;
  6744. }).join('');
  6745. }
  6746. function renderBgpNetworks() {
  6747. const tbody = document.getElementById('bgp-nets-table-body');
  6748. if (!tbody) return;
  6749. const empty = document.getElementById('bgp-nets-empty');
  6750. const countBadge = document.getElementById('bgp-nets-count-badge');
  6751. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6752. const nets = state.bgpNets || [];
  6753. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6754. if (navBadge) navBadge.innerText = nets.length;
  6755. if (nets.length === 0) {
  6756. tbody.innerHTML = '';
  6757. if (empty) empty.classList.remove('hidden');
  6758. return;
  6759. }
  6760. if (empty) empty.classList.add('hidden');
  6761. tbody.innerHTML = nets.map(n => `
  6762. <tr class="hover:bg-slate-800/40 transition">
  6763. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6764. <td class="py-2.5 px-3">
  6765. ${n.disabled
  6766. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6767. : '<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>'}
  6768. </td>
  6769. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6770. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6771. <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">
  6772. Delete
  6773. </button>
  6774. </td>
  6775. </tr>
  6776. `).join('');
  6777. }
  6778. function renderBgpRoutes() {
  6779. const tbody = document.getElementById('bgp-routes-table-body');
  6780. if (!tbody) return;
  6781. const empty = document.getElementById('bgp-routes-empty');
  6782. const countBadge = document.getElementById('bgp-routes-count-badge');
  6783. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6784. const routes = state.bgpRoutes || [];
  6785. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6786. if (navBadge) navBadge.innerText = routes.length;
  6787. if (routes.length === 0) {
  6788. tbody.innerHTML = '';
  6789. if (empty) empty.classList.remove('hidden');
  6790. return;
  6791. }
  6792. if (empty) empty.classList.add('hidden');
  6793. tbody.innerHTML = routes.map(r => `
  6794. <tr class="hover:bg-slate-800/40 transition">
  6795. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6796. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6797. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6798. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6799. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6800. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6801. </tr>
  6802. `).join('');
  6803. }
  6804. // =========================================================================
  6805. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  6806. // =========================================================================
  6807. function sortOspfTable(tab, col) {
  6808. if (!state.ospfSort) state.ospfSort = {};
  6809. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  6810. if (state.ospfSort[tab].col === col) {
  6811. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  6812. } else {
  6813. state.ospfSort[tab].col = col;
  6814. state.ospfSort[tab].asc = true;
  6815. }
  6816. const asc = state.ospfSort[tab].asc;
  6817. let list = [];
  6818. if (tab === 'instances') list = state.ospfInstances || [];
  6819. else if (tab === 'areas') list = state.ospfAreas || [];
  6820. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  6821. else if (tab === 'templates') list = state.ospfTemplates || [];
  6822. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  6823. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  6824. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  6825. else if (tab === 'lsa') list = state.ospfLSA || [];
  6826. list.sort((a, b) => {
  6827. let valA = a[col] ?? '';
  6828. let valB = b[col] ?? '';
  6829. if (typeof valA === 'number' && typeof valB === 'number') {
  6830. return asc ? valA - valB : valB - valA;
  6831. }
  6832. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  6833. });
  6834. if (tab === 'instances') renderOspfInstances();
  6835. else if (tab === 'areas') renderOspfAreas();
  6836. else if (tab === 'ranges') renderOspfAreaRanges();
  6837. else if (tab === 'templates') renderOspfTemplates();
  6838. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  6839. else if (tab === 'snbrs') renderOspfStaticNbrs();
  6840. else if (tab === 'neighbors') renderOspfNeighbors();
  6841. else if (tab === 'lsa') renderOspfLSA();
  6842. }
  6843. function selectOspfRow(tab, id) {
  6844. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  6845. state.selectedOspfRow[tab] = id;
  6846. if (tab === 'instances') {
  6847. renderOspfInstances();
  6848. const btnEn = document.getElementById('btn-ospf-inst-enable');
  6849. const btnDis = document.getElementById('btn-ospf-inst-disable');
  6850. const btnRem = document.getElementById('btn-ospf-inst-remove');
  6851. const btnCom = document.getElementById('btn-ospf-inst-comment');
  6852. if (btnEn) btnEn.disabled = false;
  6853. if (btnDis) btnDis.disabled = false;
  6854. if (btnRem) btnRem.disabled = false;
  6855. if (btnCom) btnCom.disabled = false;
  6856. } else if (tab === 'areas') {
  6857. renderOspfAreas();
  6858. const btnEn = document.getElementById('btn-ospf-area-enable');
  6859. const btnDis = document.getElementById('btn-ospf-area-disable');
  6860. const btnRem = document.getElementById('btn-ospf-area-remove');
  6861. const btnCom = document.getElementById('btn-ospf-area-comment');
  6862. if (btnEn) btnEn.disabled = false;
  6863. if (btnDis) btnDis.disabled = false;
  6864. if (btnRem) btnRem.disabled = false;
  6865. if (btnCom) btnCom.disabled = false;
  6866. } else if (tab === 'ranges') {
  6867. renderOspfAreaRanges();
  6868. const btnEn = document.getElementById('btn-ospf-range-enable');
  6869. const btnDis = document.getElementById('btn-ospf-range-disable');
  6870. const btnRem = document.getElementById('btn-ospf-range-remove');
  6871. const btnCom = document.getElementById('btn-ospf-range-comment');
  6872. if (btnEn) btnEn.disabled = false;
  6873. if (btnDis) btnDis.disabled = false;
  6874. if (btnRem) btnRem.disabled = false;
  6875. if (btnCom) btnCom.disabled = false;
  6876. } else if (tab === 'templates') {
  6877. renderOspfTemplates();
  6878. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  6879. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  6880. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  6881. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  6882. if (btnEn) btnEn.disabled = false;
  6883. if (btnDis) btnDis.disabled = false;
  6884. if (btnRem) btnRem.disabled = false;
  6885. if (btnCom) btnCom.disabled = false;
  6886. } else if (tab === 'snbrs') {
  6887. renderOspfStaticNbrs();
  6888. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  6889. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  6890. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  6891. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  6892. if (btnEn) btnEn.disabled = false;
  6893. if (btnDis) btnDis.disabled = false;
  6894. if (btnRem) btnRem.disabled = false;
  6895. if (btnCom) btnCom.disabled = false;
  6896. }
  6897. }
  6898. // TAB 1: INSTANCES
  6899. function renderOspfInstances() {
  6900. const tbody = document.getElementById('ospf-instances-table-body');
  6901. if (!tbody) return;
  6902. const countEl = document.getElementById('ospf-instances-footer-count');
  6903. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  6904. let list = state.ospfInstances || [];
  6905. if (filter) {
  6906. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  6907. }
  6908. if (countEl) countEl.innerText = list.length;
  6909. const selId = state.selectedOspfRow?.instances;
  6910. tbody.innerHTML = list.map((inst, idx) => {
  6911. const isSel = inst.id === selId;
  6912. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6913. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6914. return `
  6915. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  6916. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6917. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6918. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  6919. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6920. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  6921. </td>
  6922. <td class="py-1.5 px-3">${inst.version || 2}</td>
  6923. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  6924. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  6925. </tr>
  6926. `;
  6927. }).join('');
  6928. }
  6929. // TAB 2: AREAS
  6930. function renderOspfAreas() {
  6931. const tbody = document.getElementById('ospf-areas-table-body');
  6932. if (!tbody) return;
  6933. const countEl = document.getElementById('ospf-areas-footer-count');
  6934. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  6935. let list = state.ospfAreas || [];
  6936. if (filter) {
  6937. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  6938. }
  6939. if (countEl) countEl.innerText = list.length;
  6940. const selId = state.selectedOspfRow?.areas;
  6941. tbody.innerHTML = list.map((a, idx) => {
  6942. const isSel = a.id === selId;
  6943. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6944. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6945. return `
  6946. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  6947. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6948. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  6949. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  6950. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6951. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  6952. </td>
  6953. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  6954. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  6955. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  6956. </tr>
  6957. `;
  6958. }).join('');
  6959. }
  6960. // TAB 3: AREA RANGES
  6961. function renderOspfAreaRanges() {
  6962. const tbody = document.getElementById('ospf-ranges-table-body');
  6963. if (!tbody) return;
  6964. const countEl = document.getElementById('ospf-ranges-footer-count');
  6965. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  6966. let list = state.ospfAreaRanges || [];
  6967. if (filter) {
  6968. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  6969. }
  6970. if (countEl) countEl.innerText = list.length;
  6971. const selId = state.selectedOspfRow?.['area-ranges'];
  6972. tbody.innerHTML = list.map((r, idx) => {
  6973. const isSel = r.id === selId;
  6974. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6975. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6976. return `
  6977. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  6978. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6979. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  6980. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  6981. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  6982. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  6983. <td class="py-1.5 px-3">${r.cost || 1}</td>
  6984. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  6985. </tr>
  6986. `;
  6987. }).join('');
  6988. }
  6989. // TAB 4: INTERFACE TEMPLATES
  6990. function renderOspfTemplates() {
  6991. const tbody = document.getElementById('ospf-templates-table-body');
  6992. if (!tbody) return;
  6993. const countEl = document.getElementById('ospf-templates-footer-count');
  6994. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  6995. let list = state.ospfTemplates || [];
  6996. if (filter) {
  6997. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  6998. }
  6999. if (countEl) countEl.innerText = list.length;
  7000. const selId = state.selectedOspfRow?.templates;
  7001. tbody.innerHTML = list.map((t, idx) => {
  7002. const isSel = t.id === selId;
  7003. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7004. const ifaces = t.interfaces || t.interface || 'all';
  7005. const nets = t.networks || t.network || '';
  7006. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7007. return `
  7008. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7009. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7010. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7011. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7012. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7013. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7014. </td>
  7015. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7016. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7017. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7018. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7019. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7020. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7021. </tr>
  7022. `;
  7023. }).join('');
  7024. }
  7025. // TAB 5: LIVE INTERFACES
  7026. function renderOspfLiveInterfaces() {
  7027. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7028. if (!tbody) return;
  7029. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7030. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7031. let list = state.ospfLiveInterfaces || [];
  7032. if (filter) {
  7033. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7034. }
  7035. if (countEl) countEl.innerText = list.length;
  7036. tbody.innerHTML = list.map(i => `
  7037. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7038. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7039. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7040. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7041. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7042. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7043. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7044. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7045. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7046. </tr>
  7047. `).join('');
  7048. }
  7049. // TAB 6: STATIC NEIGHBORS
  7050. function renderOspfStaticNbrs() {
  7051. const tbody = document.getElementById('ospf-snbrs-table-body');
  7052. if (!tbody) return;
  7053. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7054. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7055. let list = state.ospfStaticNbrs || [];
  7056. if (filter) {
  7057. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7058. }
  7059. if (countEl) countEl.innerText = list.length;
  7060. const selId = state.selectedOspfRow?.['static-nbrs'];
  7061. tbody.innerHTML = list.map((n, idx) => {
  7062. const isSel = n.id === selId;
  7063. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7064. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7065. return `
  7066. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7067. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7068. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7069. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7070. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7071. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7072. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7073. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7074. </tr>
  7075. `;
  7076. }).join('');
  7077. }
  7078. // TAB 7: LIVE NEIGHBORS
  7079. function renderOspfNeighbors() {
  7080. const tbody = document.getElementById('ospf-neighbors-table-body');
  7081. if (!tbody) return;
  7082. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7083. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7084. let list = state.ospfNeighbors || [];
  7085. if (filter) {
  7086. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7087. }
  7088. if (countEl) countEl.innerText = list.length;
  7089. tbody.innerHTML = list.map(n => `
  7090. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7091. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7092. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7093. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7094. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7095. </td>
  7096. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7097. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7098. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7099. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7100. </tr>
  7101. `).join('');
  7102. }
  7103. // TAB 8: LINK-STATE DATABASE (LSA)
  7104. function renderOspfLSA() {
  7105. const tbody = document.getElementById('ospf-lsa-table-body');
  7106. if (!tbody) return;
  7107. const countEl = document.getElementById('ospf-lsa-footer-count');
  7108. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7109. let list = state.ospfLSA || [];
  7110. if (filter) {
  7111. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7112. }
  7113. if (countEl) countEl.innerText = list.length;
  7114. tbody.innerHTML = list.map(l => `
  7115. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7116. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7117. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7118. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7119. </td>
  7120. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7121. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7122. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7123. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7124. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7125. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7126. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7127. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7128. </tr>
  7129. `).join('');
  7130. }
  7131. function renderOspfStatusPill() {
  7132. // Maintained for backward compatibility
  7133. const pill = document.getElementById('ospf-live-status-pill');
  7134. if (!pill) return;
  7135. 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';
  7136. pill.innerText = 'OSPF ACTIVE';
  7137. }
  7138. function renderOspfInterfaces() {
  7139. renderOspfTemplates();
  7140. }
  7141. function renderOspfRoutes() {
  7142. // Routes retained in background
  7143. }
  7144. // BGP Modals & Actions
  7145. function openBgpInstanceModal() {
  7146. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7147. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7148. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7149. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7150. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7151. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7152. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7153. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7154. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7155. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7156. }
  7157. function closeBgpInstanceModal() {
  7158. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7159. }
  7160. async function submitBgpInstance(e) {
  7161. e.preventDefault();
  7162. const payload = {
  7163. enabled: document.getElementById('modal-bgp-enabled').checked,
  7164. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7165. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7166. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7167. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7168. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7169. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7170. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7171. };
  7172. try {
  7173. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7174. method: 'POST',
  7175. headers: { 'Content-Type': 'application/json' },
  7176. body: JSON.stringify(payload)
  7177. });
  7178. if (res.ok) {
  7179. closeBgpInstanceModal();
  7180. showToast('Success', 'BGP instance configuration updated', 'success');
  7181. loadDynamicRouting();
  7182. } else {
  7183. const err = await res.json();
  7184. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7185. }
  7186. } catch (err) {
  7187. showToast('Error', err.message, 'error');
  7188. }
  7189. }
  7190. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7191. function switchBgpPeerModalTab(tab) {
  7192. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7193. tabs.forEach(t => {
  7194. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7195. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7196. if (t === tab) {
  7197. if (pane) pane.classList.remove('hidden');
  7198. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7199. } else {
  7200. if (pane) pane.classList.add('hidden');
  7201. 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';
  7202. }
  7203. });
  7204. }
  7205. function addOutputNetworkRow(val = '') {
  7206. const container = document.getElementById('modal-bgp-output-networks-container');
  7207. if (!container) return;
  7208. const row = document.createElement('div');
  7209. row.className = 'flex items-center gap-2 output-net-row';
  7210. row.innerHTML = `
  7211. <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">
  7212. <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>
  7213. `;
  7214. container.appendChild(row);
  7215. }
  7216. function parseBgpTime(val) {
  7217. if (!val) return 0;
  7218. val = String(val).trim();
  7219. if (val.includes(':')) {
  7220. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7221. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7222. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7223. }
  7224. return parseInt(val, 10) || 0;
  7225. }
  7226. function formatBgpTime(secs) {
  7227. if (!secs || secs <= 0) return '00:00:00';
  7228. const h = Math.floor(secs / 3600);
  7229. const m = Math.floor((secs % 3600) / 60);
  7230. const s = secs % 60;
  7231. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7232. }
  7233. function populateBgpRoutingTables() {
  7234. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7235. if (!sel) return;
  7236. const cur = sel.value || 'main';
  7237. sel.innerHTML = '<option value="main">main</option>';
  7238. (state.routingTables || []).forEach(t => {
  7239. if (t.name !== 'main') {
  7240. const opt = document.createElement('option');
  7241. opt.value = t.name;
  7242. opt.innerText = t.name;
  7243. sel.appendChild(opt);
  7244. }
  7245. });
  7246. sel.value = cur;
  7247. }
  7248. function openAddBgpPeerModal() {
  7249. document.getElementById('bgp-peer-form').reset();
  7250. document.getElementById('modal-bgp-peer-id').value = '';
  7251. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7252. // General Tab
  7253. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7254. document.getElementById('modal-bgp-peer-comment').value = '';
  7255. document.getElementById('modal-bgp-peer-name').value = '';
  7256. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7257. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7258. document.getElementById('modal-bgp-peer-local-as').value = '';
  7259. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7260. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7261. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7262. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7263. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7264. document.getElementById('modal-bgp-peer-router-id').value = '';
  7265. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7266. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7267. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7268. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7269. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7270. document.getElementById('modal-bgp-peer-local-port').value = '';
  7271. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7272. document.getElementById('modal-bgp-peer-password').value = '';
  7273. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7274. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7275. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7276. document.getElementById('modal-bgp-peer-connect').checked = true;
  7277. document.getElementById('modal-bgp-peer-listen').checked = true;
  7278. // Extra Tab
  7279. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7280. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7281. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7282. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7283. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7284. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7285. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7286. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7287. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7288. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7289. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7290. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7291. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7292. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7293. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7294. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7295. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7296. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7297. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7298. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7299. // Attributes Tab
  7300. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7301. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7302. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7303. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7304. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7305. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7306. // Filter Tab
  7307. populateFilterChainsDatalist();
  7308. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7309. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7310. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7311. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7312. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7313. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7314. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7315. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7316. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7317. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7318. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7319. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7320. populateBgpRoutingTables();
  7321. const container = document.getElementById('modal-bgp-output-networks-container');
  7322. if (container) {
  7323. container.innerHTML = '';
  7324. addOutputNetworkRow('');
  7325. }
  7326. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7327. if (removeBtn) removeBtn.classList.add('hidden');
  7328. switchBgpPeerModalTab('general');
  7329. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7330. }
  7331. function populateFilterChainsDatalist() {
  7332. const dl = document.getElementById('filter-chains-list');
  7333. if (!dl) return;
  7334. const chains = new Set();
  7335. (state.routingFilters || []).forEach(f => {
  7336. if (f.chain) chains.add(f.chain);
  7337. });
  7338. if (chains.size === 0) {
  7339. chains.add('awmn');
  7340. chains.add('bgp-in');
  7341. chains.add('bgp-out');
  7342. }
  7343. dl.innerHTML = '';
  7344. chains.forEach(c => {
  7345. const opt = document.createElement('option');
  7346. opt.value = c;
  7347. dl.appendChild(opt);
  7348. });
  7349. }
  7350. function openEditBgpPeerModal(id) {
  7351. const p = (state.bgpPeers || []).find(item => item.id === id);
  7352. if (!p) return;
  7353. populateBgpRoutingTables();
  7354. populateFilterChainsDatalist();
  7355. document.getElementById('modal-bgp-peer-id').value = p.id;
  7356. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7357. // General Tab
  7358. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7359. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7360. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7361. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7362. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7363. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7364. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7365. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7366. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7367. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7368. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7369. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7370. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7371. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7372. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7373. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7374. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7375. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7376. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7377. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7378. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7379. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7380. // Extra Tab
  7381. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7382. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7383. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7384. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7385. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7386. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7387. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7388. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7389. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7390. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7391. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7392. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7393. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7394. 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;
  7395. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7396. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7397. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7398. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7399. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7400. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7401. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7402. // Attributes Tab
  7403. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7404. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7405. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7406. 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;
  7407. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7408. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7409. // Filter Tab
  7410. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7411. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7412. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7413. 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 || '';
  7414. 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 || '';
  7415. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7416. 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 || '';
  7417. 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 || '';
  7418. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7419. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7420. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7421. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7422. // Output Networks
  7423. const container = document.getElementById('modal-bgp-output-networks-container');
  7424. if (container) {
  7425. container.innerHTML = '';
  7426. if (p.output_networks && p.output_networks.length > 0) {
  7427. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7428. } else {
  7429. addOutputNetworkRow('');
  7430. }
  7431. }
  7432. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7433. if (removeBtn) removeBtn.classList.remove('hidden');
  7434. switchBgpPeerModalTab('general');
  7435. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7436. }
  7437. function copyCurrentBgpPeer() {
  7438. document.getElementById('modal-bgp-peer-id').value = '';
  7439. const nameEl = document.getElementById('modal-bgp-peer-name');
  7440. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7441. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7442. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7443. if (removeBtn) removeBtn.classList.add('hidden');
  7444. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7445. }
  7446. function removeCurrentBgpPeer() {
  7447. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7448. if (!id) return;
  7449. deleteBgpPeer(id);
  7450. closeBgpPeerModal();
  7451. }
  7452. function closeBgpPeerModal() {
  7453. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7454. }
  7455. function getBgpPeerFormData() {
  7456. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7457. const outputNetworks = [];
  7458. netInputs.forEach(inp => {
  7459. const v = inp.value.trim();
  7460. if (v) outputNetworks.push(v);
  7461. });
  7462. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7463. return {
  7464. id: document.getElementById('modal-bgp-peer-id').value,
  7465. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7466. enabled: enabled,
  7467. disabled: !enabled,
  7468. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7469. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7470. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7471. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7472. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7473. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7474. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7475. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7476. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7477. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7478. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7479. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7480. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7481. password: document.getElementById('modal-bgp-peer-password').value,
  7482. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7483. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7484. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7485. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7486. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7487. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7488. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7489. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7490. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7491. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7492. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7493. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7494. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7495. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7496. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7497. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7498. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7499. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7500. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7501. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7502. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7503. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7504. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7505. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7506. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7507. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7508. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7509. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7510. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7511. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7512. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7513. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7514. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7515. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7516. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7517. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7518. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7519. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7520. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7521. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7522. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7523. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7524. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7525. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7526. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7527. output_networks: outputNetworks
  7528. };
  7529. }
  7530. async function submitBgpPeer(e) {
  7531. if (e) e.preventDefault();
  7532. const payload = getBgpPeerFormData();
  7533. try {
  7534. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7535. method: 'POST',
  7536. headers: { 'Content-Type': 'application/json' },
  7537. body: JSON.stringify(payload)
  7538. });
  7539. if (res.ok) {
  7540. closeBgpPeerModal();
  7541. showToast('Success', 'BGP Connection saved', 'success');
  7542. loadDynamicRouting();
  7543. } else {
  7544. const err = await res.json();
  7545. showToast('Error', err.error || 'Failed to save peer', 'error');
  7546. }
  7547. } catch (err) {
  7548. showToast('Error', err.message, 'error');
  7549. }
  7550. }
  7551. async function applyBgpPeerModal(e) {
  7552. if (e) e.preventDefault();
  7553. const payload = getBgpPeerFormData();
  7554. try {
  7555. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7556. method: 'POST',
  7557. headers: { 'Content-Type': 'application/json' },
  7558. body: JSON.stringify(payload)
  7559. });
  7560. if (res.ok) {
  7561. const data = await res.json();
  7562. if (data.peer && data.peer.id) {
  7563. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7564. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7565. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7566. }
  7567. showToast('Applied', 'BGP Connection applied', 'success');
  7568. loadDynamicRouting();
  7569. } else {
  7570. const err = await res.json();
  7571. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7572. }
  7573. } catch (err) {
  7574. showToast('Error', err.message, 'error');
  7575. }
  7576. }
  7577. async function deleteBgpPeer(id) {
  7578. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7579. try {
  7580. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7581. if (res.ok) {
  7582. showToast('Deleted', 'BGP peer removed', 'success');
  7583. loadDynamicRouting();
  7584. }
  7585. } catch (err) {
  7586. showToast('Error', err.message, 'error');
  7587. }
  7588. }
  7589. async function toggleBgpPeerState(id, disabled) {
  7590. try {
  7591. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7592. method: 'POST',
  7593. headers: { 'Content-Type': 'application/json' },
  7594. body: JSON.stringify({ disabled })
  7595. });
  7596. if (res.ok) {
  7597. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7598. loadDynamicRouting();
  7599. }
  7600. } catch (err) {
  7601. showToast('Error', err.message, 'error');
  7602. }
  7603. }
  7604. function openAddBgpNetworkModal() {
  7605. document.getElementById('bgp-network-form').reset();
  7606. document.getElementById('modal-bgp-net-id').value = '';
  7607. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7608. }
  7609. function closeBgpNetworkModal() {
  7610. document.getElementById('bgp-network-modal').classList.add('hidden');
  7611. }
  7612. async function submitBgpNetwork(e) {
  7613. e.preventDefault();
  7614. const payload = {
  7615. id: document.getElementById('modal-bgp-net-id').value,
  7616. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7617. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7618. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7619. };
  7620. try {
  7621. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7622. method: 'POST',
  7623. headers: { 'Content-Type': 'application/json' },
  7624. body: JSON.stringify(payload)
  7625. });
  7626. if (res.ok) {
  7627. closeBgpNetworkModal();
  7628. showToast('Success', 'BGP network advertisement saved', 'success');
  7629. loadDynamicRouting();
  7630. } else {
  7631. const err = await res.json();
  7632. showToast('Error', err.error || 'Failed to save network', 'error');
  7633. }
  7634. } catch (err) {
  7635. showToast('Error', err.message, 'error');
  7636. }
  7637. }
  7638. async function deleteBgpNetwork(id) {
  7639. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7640. try {
  7641. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7642. if (res.ok) {
  7643. showToast('Deleted', 'Network advertisement removed', 'success');
  7644. loadDynamicRouting();
  7645. }
  7646. } catch (err) {
  7647. showToast('Error', err.message, 'error');
  7648. }
  7649. }
  7650. // =========================================================================
  7651. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7652. // =========================================================================
  7653. // --- 1. OSPF INSTANCE ---
  7654. function openOspfInstanceModal(id = null) {
  7655. const isEdit = !!id;
  7656. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7657. id: '',
  7658. name: 'Default',
  7659. version: 2,
  7660. vrf: 'main',
  7661. router_id: '192.168.131.56',
  7662. routing_table: 'main',
  7663. enabled: true,
  7664. redistribute_connected: false,
  7665. redistribute_static: true,
  7666. redistribute_bgp: false,
  7667. comment: ''
  7668. };
  7669. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7670. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7671. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7672. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7673. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7674. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7675. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7676. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7677. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7678. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7679. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7680. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7681. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7682. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7683. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7684. }
  7685. function openEditOspfInstanceModal(id) {
  7686. openOspfInstanceModal(id);
  7687. }
  7688. function closeOspfInstanceModal() {
  7689. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7690. }
  7691. async function submitOspfInstance(e) {
  7692. if (e) e.preventDefault();
  7693. const payload = {
  7694. id: document.getElementById('modal-ospf-inst-id').value,
  7695. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  7696. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  7697. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  7698. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  7699. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  7700. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  7701. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  7702. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  7703. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  7704. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  7705. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  7706. };
  7707. try {
  7708. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  7709. method: 'POST',
  7710. headers: { 'Content-Type': 'application/json' },
  7711. body: JSON.stringify(payload)
  7712. });
  7713. if (res.ok) {
  7714. closeOspfInstanceModal();
  7715. showToast('Saved', 'OSPF instance updated', 'success');
  7716. loadDynamicRouting();
  7717. } else {
  7718. const err = await res.json();
  7719. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  7720. }
  7721. } catch (err) {
  7722. showToast('Error', err.message, 'error');
  7723. }
  7724. }
  7725. function applyOspfInstanceForm() {
  7726. submitOspfInstance(null);
  7727. }
  7728. function copyOspfInstance() {
  7729. document.getElementById('modal-ospf-inst-id').value = '';
  7730. document.getElementById('modal-ospf-inst-name').value += '-copy';
  7731. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  7732. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  7733. }
  7734. async function deleteCurrentOspfInstance() {
  7735. const id = document.getElementById('modal-ospf-inst-id').value;
  7736. if (!id) return;
  7737. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  7738. try {
  7739. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7740. if (res.ok) {
  7741. closeOspfInstanceModal();
  7742. showToast('Removed', 'OSPF instance deleted', 'success');
  7743. loadDynamicRouting();
  7744. }
  7745. } catch (err) {
  7746. showToast('Error', err.message, 'error');
  7747. }
  7748. }
  7749. async function enableSelectedOspfInstance() {
  7750. const id = state.selectedOspfRow?.instances;
  7751. if (!id) return;
  7752. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7753. method: 'POST',
  7754. headers: { 'Content-Type': 'application/json' },
  7755. body: JSON.stringify({ disabled: false })
  7756. });
  7757. loadDynamicRouting();
  7758. }
  7759. async function disableSelectedOspfInstance() {
  7760. const id = state.selectedOspfRow?.instances;
  7761. if (!id) return;
  7762. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7763. method: 'POST',
  7764. headers: { 'Content-Type': 'application/json' },
  7765. body: JSON.stringify({ disabled: true })
  7766. });
  7767. loadDynamicRouting();
  7768. }
  7769. async function removeSelectedOspfInstance() {
  7770. const id = state.selectedOspfRow?.instances;
  7771. if (!id) return;
  7772. if (!confirm('Delete selected OSPF instance?')) return;
  7773. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7774. loadDynamicRouting();
  7775. }
  7776. async function promptCommentOspfInstance() {
  7777. const id = state.selectedOspfRow?.instances;
  7778. if (!id) return;
  7779. const inst = (state.ospfInstances || []).find(i => i.id === id);
  7780. if (!inst) return;
  7781. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  7782. if (comment === null) return;
  7783. inst.comment = comment;
  7784. await fetch(`${API_BASE}/routing/ospf/instances`, {
  7785. method: 'POST',
  7786. headers: { 'Content-Type': 'application/json' },
  7787. body: JSON.stringify(inst)
  7788. });
  7789. loadDynamicRouting();
  7790. }
  7791. // --- 2. OSPF AREA ---
  7792. function populateOspfAreaDropdowns() {
  7793. const instSelect = document.getElementById('modal-ospf-area-instance');
  7794. if (instSelect) {
  7795. const cur = instSelect.value;
  7796. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  7797. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  7798. if (cur) instSelect.value = cur;
  7799. }
  7800. }
  7801. function openOspfAreaModal(id = null) {
  7802. const isEdit = !!id;
  7803. populateOspfAreaDropdowns();
  7804. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  7805. id: '',
  7806. name: 'Default',
  7807. instance: 'Default',
  7808. area_id: '0.0.0.0',
  7809. area_type: 'default',
  7810. default_cost: 1,
  7811. no_summaries: false,
  7812. disabled: false,
  7813. comment: ''
  7814. };
  7815. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  7816. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  7817. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  7818. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  7819. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  7820. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  7821. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  7822. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  7823. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  7824. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  7825. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  7826. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7827. document.getElementById('ospf-area-modal').classList.remove('hidden');
  7828. }
  7829. function openEditOspfAreaModal(id) {
  7830. openOspfAreaModal(id);
  7831. }
  7832. function closeOspfAreaModal() {
  7833. document.getElementById('ospf-area-modal').classList.add('hidden');
  7834. }
  7835. async function submitOspfArea(e) {
  7836. if (e) e.preventDefault();
  7837. const payload = {
  7838. id: document.getElementById('modal-ospf-area-id').value,
  7839. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  7840. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  7841. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  7842. area_type: document.getElementById('modal-ospf-area-type').value,
  7843. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  7844. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  7845. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  7846. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  7847. };
  7848. try {
  7849. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  7850. method: 'POST',
  7851. headers: { 'Content-Type': 'application/json' },
  7852. body: JSON.stringify(payload)
  7853. });
  7854. if (res.ok) {
  7855. closeOspfAreaModal();
  7856. showToast('Saved', 'OSPF area saved', 'success');
  7857. loadDynamicRouting();
  7858. } else {
  7859. const err = await res.json();
  7860. showToast('Error', err.error || 'Failed to save area', 'error');
  7861. }
  7862. } catch (err) {
  7863. showToast('Error', err.message, 'error');
  7864. }
  7865. }
  7866. function applyOspfAreaForm() {
  7867. submitOspfArea(null);
  7868. }
  7869. function copyOspfArea() {
  7870. document.getElementById('modal-ospf-area-id').value = '';
  7871. document.getElementById('modal-ospf-area-name').value += '-copy';
  7872. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  7873. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  7874. }
  7875. async function deleteCurrentOspfArea() {
  7876. const id = document.getElementById('modal-ospf-area-id').value;
  7877. if (!id) return;
  7878. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  7879. try {
  7880. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7881. if (res.ok) {
  7882. closeOspfAreaModal();
  7883. showToast('Removed', 'OSPF area deleted', 'success');
  7884. loadDynamicRouting();
  7885. }
  7886. } catch (err) {
  7887. showToast('Error', err.message, 'error');
  7888. }
  7889. }
  7890. async function enableSelectedOspfArea() {
  7891. const id = state.selectedOspfRow?.areas;
  7892. if (!id) return;
  7893. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7894. method: 'POST',
  7895. headers: { 'Content-Type': 'application/json' },
  7896. body: JSON.stringify({ disabled: false })
  7897. });
  7898. loadDynamicRouting();
  7899. }
  7900. async function disableSelectedOspfArea() {
  7901. const id = state.selectedOspfRow?.areas;
  7902. if (!id) return;
  7903. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7904. method: 'POST',
  7905. headers: { 'Content-Type': 'application/json' },
  7906. body: JSON.stringify({ disabled: true })
  7907. });
  7908. loadDynamicRouting();
  7909. }
  7910. async function removeSelectedOspfArea() {
  7911. const id = state.selectedOspfRow?.areas;
  7912. if (!id) return;
  7913. if (!confirm('Delete selected OSPF area?')) return;
  7914. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7915. loadDynamicRouting();
  7916. }
  7917. async function promptCommentOspfArea() {
  7918. const id = state.selectedOspfRow?.areas;
  7919. if (!id) return;
  7920. const area = (state.ospfAreas || []).find(a => a.id === id);
  7921. if (!area) return;
  7922. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  7923. if (comment === null) return;
  7924. area.comment = comment;
  7925. await fetch(`${API_BASE}/routing/ospf/areas`, {
  7926. method: 'POST',
  7927. headers: { 'Content-Type': 'application/json' },
  7928. body: JSON.stringify(area)
  7929. });
  7930. loadDynamicRouting();
  7931. }
  7932. // --- 3. OSPF AREA RANGE ---
  7933. function populateAreaRangeDropdowns() {
  7934. const select = document.getElementById('modal-ospf-range-area');
  7935. if (select) {
  7936. const cur = select.value;
  7937. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7938. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7939. if (cur) select.value = cur;
  7940. }
  7941. }
  7942. function openOspfAreaRangeModal(id = null) {
  7943. const isEdit = !!id;
  7944. populateAreaRangeDropdowns();
  7945. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  7946. id: '',
  7947. area: 'Default',
  7948. prefix: '',
  7949. cost: 1,
  7950. advertise: true,
  7951. disabled: false,
  7952. comment: ''
  7953. };
  7954. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  7955. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  7956. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  7957. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  7958. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  7959. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  7960. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  7961. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  7962. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  7963. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7964. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  7965. }
  7966. function openEditOspfAreaRangeModal(id) {
  7967. openOspfAreaRangeModal(id);
  7968. }
  7969. function closeOspfAreaRangeModal() {
  7970. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  7971. }
  7972. async function submitOspfAreaRange(e) {
  7973. if (e) e.preventDefault();
  7974. const payload = {
  7975. id: document.getElementById('modal-ospf-range-id').value,
  7976. area: document.getElementById('modal-ospf-range-area').value,
  7977. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  7978. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  7979. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  7980. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  7981. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  7982. };
  7983. try {
  7984. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  7985. method: 'POST',
  7986. headers: { 'Content-Type': 'application/json' },
  7987. body: JSON.stringify(payload)
  7988. });
  7989. if (res.ok) {
  7990. closeOspfAreaRangeModal();
  7991. showToast('Saved', 'Area range saved', 'success');
  7992. loadDynamicRouting();
  7993. } else {
  7994. const err = await res.json();
  7995. showToast('Error', err.error || 'Failed to save area range', 'error');
  7996. }
  7997. } catch (err) {
  7998. showToast('Error', err.message, 'error');
  7999. }
  8000. }
  8001. function applyOspfAreaRangeForm() {
  8002. submitOspfAreaRange(null);
  8003. }
  8004. async function deleteCurrentOspfAreaRange() {
  8005. const id = document.getElementById('modal-ospf-range-id').value;
  8006. if (!id) return;
  8007. if (!confirm('Delete this area range?')) return;
  8008. try {
  8009. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8010. closeOspfAreaRangeModal();
  8011. showToast('Removed', 'Area range removed', 'success');
  8012. loadDynamicRouting();
  8013. } catch (err) {
  8014. showToast('Error', err.message, 'error');
  8015. }
  8016. }
  8017. async function enableSelectedOspfAreaRange() {
  8018. const id = state.selectedOspfRow?.['area-ranges'];
  8019. if (!id) return;
  8020. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8021. if (!r) return;
  8022. r.disabled = false;
  8023. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8024. loadDynamicRouting();
  8025. }
  8026. async function disableSelectedOspfAreaRange() {
  8027. const id = state.selectedOspfRow?.['area-ranges'];
  8028. if (!id) return;
  8029. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8030. if (!r) return;
  8031. r.disabled = true;
  8032. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8033. loadDynamicRouting();
  8034. }
  8035. async function removeSelectedOspfAreaRange() {
  8036. const id = state.selectedOspfRow?.['area-ranges'];
  8037. if (!id) return;
  8038. if (!confirm('Delete selected area range?')) return;
  8039. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8040. loadDynamicRouting();
  8041. }
  8042. async function promptCommentOspfAreaRange() {
  8043. const id = state.selectedOspfRow?.['area-ranges'];
  8044. if (!id) return;
  8045. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8046. if (!r) return;
  8047. const comment = prompt('Enter comment for area range:', r.comment || '');
  8048. if (comment === null) return;
  8049. r.comment = comment;
  8050. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8051. loadDynamicRouting();
  8052. }
  8053. // --- 4. OSPF INTERFACE TEMPLATE ---
  8054. function switchOspfTemplateTab(tab) {
  8055. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8056. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8057. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8058. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8059. if (tab === 'general') {
  8060. if (tabGen) tabGen.classList.remove('hidden');
  8061. if (tabAuth) tabAuth.classList.add('hidden');
  8062. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8063. 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';
  8064. } else {
  8065. if (tabGen) tabGen.classList.add('hidden');
  8066. if (tabAuth) tabAuth.classList.remove('hidden');
  8067. 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';
  8068. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8069. }
  8070. }
  8071. function populateTemplateAreaDropdowns() {
  8072. const select = document.getElementById('modal-ospf-tmpl-area');
  8073. if (select) {
  8074. const cur = select.value;
  8075. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8076. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8077. if (cur) select.value = cur;
  8078. }
  8079. }
  8080. function openOspfTemplateModal(id = null) {
  8081. const isEdit = !!id;
  8082. populateTemplateAreaDropdowns();
  8083. switchOspfTemplateTab('general');
  8084. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8085. id: '',
  8086. interfaces: '',
  8087. area: 'Default',
  8088. networks: '',
  8089. network_type: 'broadcast',
  8090. cost: 1,
  8091. priority: 128,
  8092. passive: false,
  8093. hello_interval: 10,
  8094. dead_interval: 40,
  8095. auth: 'none',
  8096. auth_key: '',
  8097. disabled: false,
  8098. comment: ''
  8099. };
  8100. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8101. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8102. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8103. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8104. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8105. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8106. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8107. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8108. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8109. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8110. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8111. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8112. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8113. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8114. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8115. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8116. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8117. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8118. }
  8119. function openEditOspfTemplateModal(id) {
  8120. openOspfTemplateModal(id);
  8121. }
  8122. function closeOspfTemplateModal() {
  8123. document.getElementById('ospf-template-modal').classList.add('hidden');
  8124. }
  8125. async function submitOspfTemplate(e) {
  8126. if (e) e.preventDefault();
  8127. const payload = {
  8128. id: document.getElementById('modal-ospf-tmpl-id').value,
  8129. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8130. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8131. area: document.getElementById('modal-ospf-tmpl-area').value,
  8132. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8133. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8134. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8135. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8136. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8137. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8138. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8139. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8140. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8141. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8142. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8143. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8144. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8145. };
  8146. try {
  8147. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8148. method: 'POST',
  8149. headers: { 'Content-Type': 'application/json' },
  8150. body: JSON.stringify(payload)
  8151. });
  8152. if (res.ok) {
  8153. closeOspfTemplateModal();
  8154. showToast('Saved', 'Interface template saved', 'success');
  8155. loadDynamicRouting();
  8156. } else {
  8157. const err = await res.json();
  8158. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8159. }
  8160. } catch (err) {
  8161. showToast('Error', err.message, 'error');
  8162. }
  8163. }
  8164. function applyOspfTemplateForm() {
  8165. submitOspfTemplate(null);
  8166. }
  8167. function copyOspfTemplate() {
  8168. document.getElementById('modal-ospf-tmpl-id').value = '';
  8169. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8170. showToast('Copied', 'Duplicated as new template', 'info');
  8171. }
  8172. async function deleteCurrentOspfTemplate() {
  8173. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8174. if (!id) return;
  8175. if (!confirm('Delete this interface template?')) return;
  8176. try {
  8177. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8178. closeOspfTemplateModal();
  8179. showToast('Removed', 'Interface template deleted', 'success');
  8180. loadDynamicRouting();
  8181. } catch (err) {
  8182. showToast('Error', err.message, 'error');
  8183. }
  8184. }
  8185. async function enableSelectedOspfTemplate() {
  8186. const id = state.selectedOspfRow?.templates;
  8187. if (!id) return;
  8188. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8189. method: 'POST',
  8190. headers: { 'Content-Type': 'application/json' },
  8191. body: JSON.stringify({ disabled: false })
  8192. });
  8193. loadDynamicRouting();
  8194. }
  8195. async function disableSelectedOspfTemplate() {
  8196. const id = state.selectedOspfRow?.templates;
  8197. if (!id) return;
  8198. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8199. method: 'POST',
  8200. headers: { 'Content-Type': 'application/json' },
  8201. body: JSON.stringify({ disabled: true })
  8202. });
  8203. loadDynamicRouting();
  8204. }
  8205. async function removeSelectedOspfTemplate() {
  8206. const id = state.selectedOspfRow?.templates;
  8207. if (!id) return;
  8208. if (!confirm('Delete selected interface template?')) return;
  8209. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8210. loadDynamicRouting();
  8211. }
  8212. async function promptCommentOspfTemplate() {
  8213. const id = state.selectedOspfRow?.templates;
  8214. if (!id) return;
  8215. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8216. if (!tmpl) return;
  8217. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8218. if (comment === null) return;
  8219. tmpl.comment = comment;
  8220. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8221. method: 'POST',
  8222. headers: { 'Content-Type': 'application/json' },
  8223. body: JSON.stringify(tmpl)
  8224. });
  8225. loadDynamicRouting();
  8226. }
  8227. // --- 5. OSPF STATIC NEIGHBOR ---
  8228. function populateStaticNbrAreaDropdowns() {
  8229. const select = document.getElementById('modal-ospf-snbr-area');
  8230. if (select) {
  8231. const cur = select.value;
  8232. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8233. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8234. if (cur) select.value = cur;
  8235. }
  8236. }
  8237. function openOspfStaticNbrModal(id = null) {
  8238. const isEdit = !!id;
  8239. populateStaticNbrAreaDropdowns();
  8240. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8241. id: '',
  8242. address: '',
  8243. area: 'Default',
  8244. poll_interval: 120,
  8245. cost: 1,
  8246. disabled: false,
  8247. comment: ''
  8248. };
  8249. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8250. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8251. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8252. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8253. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8254. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8255. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8256. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8257. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8258. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8259. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8260. }
  8261. function openEditOspfStaticNbrModal(id) {
  8262. openOspfStaticNbrModal(id);
  8263. }
  8264. function closeOspfStaticNbrModal() {
  8265. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8266. }
  8267. async function submitOspfStaticNbr(e) {
  8268. if (e) e.preventDefault();
  8269. const payload = {
  8270. id: document.getElementById('modal-ospf-snbr-id').value,
  8271. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8272. area: document.getElementById('modal-ospf-snbr-area').value,
  8273. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8274. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8275. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8276. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8277. };
  8278. try {
  8279. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8280. method: 'POST',
  8281. headers: { 'Content-Type': 'application/json' },
  8282. body: JSON.stringify(payload)
  8283. });
  8284. if (res.ok) {
  8285. closeOspfStaticNbrModal();
  8286. showToast('Saved', 'Static neighbor saved', 'success');
  8287. loadDynamicRouting();
  8288. } else {
  8289. const err = await res.json();
  8290. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8291. }
  8292. } catch (err) {
  8293. showToast('Error', err.message, 'error');
  8294. }
  8295. }
  8296. function applyOspfStaticNbrForm() {
  8297. submitOspfStaticNbr(null);
  8298. }
  8299. async function deleteCurrentOspfStaticNbr() {
  8300. const id = document.getElementById('modal-ospf-snbr-id').value;
  8301. if (!id) return;
  8302. if (!confirm('Delete this static neighbor?')) return;
  8303. try {
  8304. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8305. closeOspfStaticNbrModal();
  8306. showToast('Removed', 'Static neighbor removed', 'success');
  8307. loadDynamicRouting();
  8308. } catch (err) {
  8309. showToast('Error', err.message, 'error');
  8310. }
  8311. }
  8312. async function enableSelectedOspfStaticNbr() {
  8313. const id = state.selectedOspfRow?.['static-nbrs'];
  8314. if (!id) return;
  8315. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8316. if (!n) return;
  8317. n.disabled = false;
  8318. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8319. loadDynamicRouting();
  8320. }
  8321. async function disableSelectedOspfStaticNbr() {
  8322. const id = state.selectedOspfRow?.['static-nbrs'];
  8323. if (!id) return;
  8324. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8325. if (!n) return;
  8326. n.disabled = true;
  8327. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8328. loadDynamicRouting();
  8329. }
  8330. async function removeSelectedOspfStaticNbr() {
  8331. const id = state.selectedOspfRow?.['static-nbrs'];
  8332. if (!id) return;
  8333. if (!confirm('Delete selected static neighbor?')) return;
  8334. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8335. loadDynamicRouting();
  8336. }
  8337. async function promptCommentOspfStaticNbr() {
  8338. const id = state.selectedOspfRow?.['static-nbrs'];
  8339. if (!id) return;
  8340. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8341. if (!n) return;
  8342. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8343. if (comment === null) return;
  8344. n.comment = comment;
  8345. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8346. loadDynamicRouting();
  8347. }
  8348. // Backward-compat aliases
  8349. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8350. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8351. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8352. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8353. function deleteOspfInterface(id) {
  8354. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8355. }
  8356. function toggleOspfInterfaceState(id, disabled) {
  8357. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8358. method: 'POST',
  8359. headers: { 'Content-Type': 'application/json' },
  8360. body: JSON.stringify({ disabled })
  8361. }).then(() => loadDynamicRouting());
  8362. }
  8363. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8364. function deleteOspfArea(id) {
  8365. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8366. }
  8367. // ============================================================================
  8368. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8369. // ============================================================================
  8370. function switchBridgeSubTab(tab) {
  8371. state.bridgeSubTab = tab;
  8372. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8373. tabs.forEach(t => {
  8374. const panel = document.getElementById(`bridge-subtab-${t}`);
  8375. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8376. if (panel) {
  8377. if (t === tab) panel.classList.remove('hidden');
  8378. else panel.classList.add('hidden');
  8379. }
  8380. if (btn) {
  8381. if (t === tab) {
  8382. 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';
  8383. } else {
  8384. 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';
  8385. }
  8386. }
  8387. });
  8388. const addBtn = document.getElementById('bridge-top-action-btn');
  8389. if (addBtn) {
  8390. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8391. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8392. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8393. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8394. }
  8395. if (tab === 'hosts') loadBridgeHosts();
  8396. setTimeout(initTableSorting, 50);
  8397. }
  8398. function openCurrentBridgeModal() {
  8399. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8400. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8401. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8402. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8403. }
  8404. async function loadBridge() {
  8405. try {
  8406. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8407. fetch(`${API_BASE}/bridge/bridges`),
  8408. fetch(`${API_BASE}/bridge/ports`),
  8409. fetch(`${API_BASE}/bridge/vlans`),
  8410. fetch(`${API_BASE}/bridge/summary`),
  8411. fetch(`${API_BASE}/vpn/eoip`),
  8412. fetch(`${API_BASE}/vlans`)
  8413. ]);
  8414. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8415. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8416. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8417. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8418. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8419. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8420. // Badges & Stats
  8421. const bBridges = document.getElementById('bridge-badge-bridges');
  8422. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8423. const bPorts = document.getElementById('bridge-badge-ports');
  8424. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8425. const bVlans = document.getElementById('bridge-badge-vlans');
  8426. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8427. const bHosts = document.getElementById('bridge-badge-hosts');
  8428. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8429. const sBr = document.getElementById('bridge-stat-bridges');
  8430. if (sBr) sBr.innerText = (state.bridges || []).length;
  8431. const sPorts = document.getElementById('bridge-stat-ports');
  8432. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8433. const sHosts = document.getElementById('bridge-stat-hosts');
  8434. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8435. renderBridges();
  8436. renderBridgePorts();
  8437. renderBridgeVLANs();
  8438. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8439. } catch (err) {
  8440. console.error('Failed to load bridge subsystem:', err);
  8441. }
  8442. }
  8443. // ----------------- Bridges -----------------
  8444. function renderBridges() {
  8445. const tbody = document.getElementById('bridge-table-body');
  8446. const empty = document.getElementById('bridge-empty-bridges');
  8447. const countBadge = document.getElementById('bridge-count-badge');
  8448. if (!tbody) return;
  8449. tbody.innerHTML = '';
  8450. const bridges = state.bridges || [];
  8451. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8452. if (bridges.length === 0) {
  8453. empty?.classList.remove('hidden');
  8454. return;
  8455. }
  8456. empty?.classList.add('hidden');
  8457. bridges.forEach((b, idx) => {
  8458. const tr = document.createElement('tr');
  8459. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8460. // Format IP addresses pill list
  8461. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8462. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8463. ipsHtml = b.ip_addresses.map(ip => `
  8464. <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">
  8465. <span>${ip}</span>
  8466. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8467. </span>
  8468. `).join(' ');
  8469. }
  8470. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8471. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8472. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8473. tr.innerHTML = `
  8474. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8475. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8476. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8477. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8478. </td>
  8479. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8480. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8481. <td class="py-2.5 px-3">
  8482. <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>
  8483. </td>
  8484. <td class="py-2.5 px-3 text-center">
  8485. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8486. </td>
  8487. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8488. <td class="py-2.5 px-3">
  8489. <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>
  8490. </td>
  8491. <td class="py-2.5 px-3">
  8492. <div class="flex items-center gap-1.5 flex-wrap">
  8493. ${ipsHtml}
  8494. <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>
  8495. </div>
  8496. </td>
  8497. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8498. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8499. </td>
  8500. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8501. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8502. <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>
  8503. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8504. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8505. </td>
  8506. `;
  8507. tbody.appendChild(tr);
  8508. });
  8509. }
  8510. function openAddBridgeModal() {
  8511. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8512. document.getElementById('bridge-modal-id').value = '';
  8513. document.getElementById('bridge-modal-name').value = 'bridge1';
  8514. document.getElementById('bridge-modal-name').disabled = false;
  8515. document.getElementById('bridge-modal-mtu').value = '1500';
  8516. document.getElementById('bridge-modal-mac').value = '';
  8517. document.getElementById('bridge-modal-stp').value = 'rstp';
  8518. document.getElementById('bridge-modal-priority').value = '32768';
  8519. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8520. document.getElementById('bridge-modal-pvid').value = '1';
  8521. document.getElementById('bridge-modal-fastforward').checked = true;
  8522. document.getElementById('bridge-modal-comment').value = '';
  8523. document.getElementById('bridge-modal-disabled').checked = false;
  8524. toggleBridgeModalVlanFiltering();
  8525. document.getElementById('bridge-modal').classList.remove('hidden');
  8526. }
  8527. function openEditBridgeModal(id) {
  8528. const b = (state.bridges || []).find(x => x.id === id);
  8529. if (!b) return;
  8530. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8531. document.getElementById('bridge-modal-id').value = b.id;
  8532. document.getElementById('bridge-modal-name').value = b.name;
  8533. document.getElementById('bridge-modal-name').disabled = true;
  8534. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8535. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8536. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8537. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8538. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8539. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8540. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8541. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8542. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8543. toggleBridgeModalVlanFiltering();
  8544. document.getElementById('bridge-modal').classList.remove('hidden');
  8545. }
  8546. function closeBridgeModal() {
  8547. document.getElementById('bridge-modal').classList.add('hidden');
  8548. }
  8549. function toggleBridgeModalVlanFiltering() {
  8550. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8551. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8552. if (pvidBox) {
  8553. if (chk) pvidBox.classList.remove('opacity-40');
  8554. else pvidBox.classList.add('opacity-40');
  8555. }
  8556. }
  8557. async function submitSaveBridge(e) {
  8558. e.preventDefault();
  8559. const id = document.getElementById('bridge-modal-id').value;
  8560. const name = document.getElementById('bridge-modal-name').value.trim();
  8561. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8562. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8563. const stp = document.getElementById('bridge-modal-stp').value;
  8564. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8565. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8566. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8567. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8568. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8569. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8570. try {
  8571. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8572. method: 'POST',
  8573. headers: { 'Content-Type': 'application/json' },
  8574. body: JSON.stringify({
  8575. id,
  8576. name,
  8577. mtu,
  8578. mac_address: mac,
  8579. stp,
  8580. priority,
  8581. vlan_filtering: vlanFiltering,
  8582. pvid,
  8583. fast_forward: fastForward,
  8584. comment,
  8585. disabled
  8586. })
  8587. });
  8588. if (res.ok) {
  8589. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8590. closeBridgeModal();
  8591. loadBridge();
  8592. fetchData(false);
  8593. } else {
  8594. const err = await res.json();
  8595. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8596. }
  8597. } catch (err) {
  8598. showToast('Error', err.message, 'error');
  8599. }
  8600. }
  8601. async function toggleBridgeState(id, disabled) {
  8602. try {
  8603. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8604. method: 'POST',
  8605. headers: { 'Content-Type': 'application/json' },
  8606. body: JSON.stringify({ disabled })
  8607. });
  8608. if (res.ok) {
  8609. loadBridge();
  8610. fetchData(false);
  8611. }
  8612. } catch (err) {
  8613. showToast('Error', err.message, 'error');
  8614. }
  8615. }
  8616. async function deleteBridge(id) {
  8617. const b = (state.bridges || []).find(x => x.id === id);
  8618. const name = b ? b.name : id;
  8619. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8620. try {
  8621. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8622. if (res.ok) {
  8623. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8624. loadBridge();
  8625. fetchData(false);
  8626. } else {
  8627. const err = await res.json();
  8628. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8629. }
  8630. } catch (err) {
  8631. showToast('Error', err.message, 'error');
  8632. }
  8633. }
  8634. // ----------------- Bridge IP Assignments -----------------
  8635. function openAddBridgeIPModal(id, name) {
  8636. document.getElementById('bridge-ip-modal-id').value = id;
  8637. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8638. document.getElementById('bridge-ip-modal-cidr').value = '';
  8639. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8640. }
  8641. function closeBridgeIPModal() {
  8642. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8643. }
  8644. async function submitAddBridgeIP(e) {
  8645. e.preventDefault();
  8646. const id = document.getElementById('bridge-ip-modal-id').value;
  8647. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8648. try {
  8649. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8650. method: 'POST',
  8651. headers: { 'Content-Type': 'application/json' },
  8652. body: JSON.stringify({ ip })
  8653. });
  8654. if (res.ok) {
  8655. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8656. closeBridgeIPModal();
  8657. loadBridge();
  8658. fetchData(false);
  8659. } else {
  8660. const err = await res.json();
  8661. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8662. }
  8663. } catch (err) {
  8664. showToast('Error', err.message, 'error');
  8665. }
  8666. }
  8667. async function deleteBridgeIP(id, ip) {
  8668. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8669. try {
  8670. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8671. method: 'DELETE',
  8672. headers: { 'Content-Type': 'application/json' },
  8673. body: JSON.stringify({ ip })
  8674. });
  8675. if (res.ok) {
  8676. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8677. loadBridge();
  8678. fetchData(false);
  8679. }
  8680. } catch (err) {
  8681. showToast('Error', err.message, 'error');
  8682. }
  8683. }
  8684. // ----------------- Bridge Ports -----------------
  8685. function renderBridgePorts() {
  8686. const tbody = document.getElementById('bridge-ports-table-body');
  8687. const empty = document.getElementById('bridge-empty-ports');
  8688. const countBadge = document.getElementById('bridge-ports-count-badge');
  8689. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8690. if (!tbody) return;
  8691. tbody.innerHTML = '';
  8692. // Update filter select
  8693. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  8694. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  8695. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  8696. if (ports.length === 0) {
  8697. empty?.classList.remove('hidden');
  8698. return;
  8699. }
  8700. empty?.classList.add('hidden');
  8701. ports.forEach((p, idx) => {
  8702. const tr = document.createElement('tr');
  8703. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  8704. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8705. tr.innerHTML = `
  8706. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8707. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8708. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8709. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  8710. </td>
  8711. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  8712. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  8713. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  8714. <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>
  8715. <td class="py-2.5 px-3">
  8716. ${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>'}
  8717. </td>
  8718. <td class="py-2.5 px-3">
  8719. <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>
  8720. </td>
  8721. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  8722. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8723. <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>
  8724. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8725. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8726. </td>
  8727. `;
  8728. tbody.appendChild(tr);
  8729. });
  8730. }
  8731. function openAddBridgePortModal() {
  8732. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  8733. document.getElementById('bridge-port-modal-id').value = '';
  8734. populateBridgeSelect('bridge-port-modal-bridge');
  8735. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  8736. document.getElementById('bridge-port-modal-pvid').value = '1';
  8737. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  8738. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  8739. document.getElementById('bridge-port-modal-horizon').value = '0';
  8740. document.getElementById('bridge-port-modal-pathcost').value = '10';
  8741. document.getElementById('bridge-port-modal-priority').value = '128';
  8742. document.getElementById('bridge-port-modal-learn').checked = true;
  8743. document.getElementById('bridge-port-modal-comment').value = '';
  8744. document.getElementById('bridge-port-modal-disabled').checked = false;
  8745. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8746. }
  8747. function openEditBridgePortModal(id) {
  8748. const p = (state.bridgePorts || []).find(x => x.id === id);
  8749. if (!p) return;
  8750. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  8751. document.getElementById('bridge-port-modal-id').value = p.id;
  8752. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  8753. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  8754. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  8755. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  8756. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  8757. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  8758. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  8759. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  8760. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  8761. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  8762. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  8763. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8764. }
  8765. function closeBridgePortModal() {
  8766. document.getElementById('bridge-port-modal').classList.add('hidden');
  8767. }
  8768. async function submitSaveBridgePort(e) {
  8769. e.preventDefault();
  8770. const id = document.getElementById('bridge-port-modal-id').value;
  8771. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  8772. const iface = document.getElementById('bridge-port-modal-interface').value;
  8773. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  8774. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  8775. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  8776. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  8777. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  8778. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  8779. const learn = document.getElementById('bridge-port-modal-learn').checked;
  8780. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  8781. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  8782. try {
  8783. const res = await fetch(`${API_BASE}/bridge/ports`, {
  8784. method: 'POST',
  8785. headers: { 'Content-Type': 'application/json' },
  8786. body: JSON.stringify({
  8787. id,
  8788. bridge,
  8789. interface: iface,
  8790. pvid,
  8791. frame_types: frameTypes,
  8792. ingress_filtering: ingressFiltering,
  8793. horizon,
  8794. path_cost: pathCost,
  8795. priority,
  8796. learn,
  8797. comment,
  8798. disabled
  8799. })
  8800. });
  8801. if (res.ok) {
  8802. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  8803. closeBridgePortModal();
  8804. loadBridge();
  8805. fetchData(false);
  8806. } else {
  8807. const err = await res.json();
  8808. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  8809. }
  8810. } catch (err) {
  8811. showToast('Error', err.message, 'error');
  8812. }
  8813. }
  8814. async function toggleBridgePortState(id, disabled) {
  8815. try {
  8816. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  8817. method: 'POST',
  8818. headers: { 'Content-Type': 'application/json' },
  8819. body: JSON.stringify({ disabled })
  8820. });
  8821. if (res.ok) {
  8822. loadBridge();
  8823. fetchData(false);
  8824. }
  8825. } catch (err) {
  8826. showToast('Error', err.message, 'error');
  8827. }
  8828. }
  8829. async function deleteBridgePort(id) {
  8830. const p = (state.bridgePorts || []).find(x => x.id === id);
  8831. const iface = p ? p.interface : id;
  8832. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  8833. try {
  8834. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8835. if (res.ok) {
  8836. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  8837. loadBridge();
  8838. fetchData(false);
  8839. }
  8840. } catch (err) {
  8841. showToast('Error', err.message, 'error');
  8842. }
  8843. }
  8844. // ----------------- Bridge VLANs -----------------
  8845. function renderBridgeVLANs() {
  8846. const tbody = document.getElementById('bridge-vlans-table-body');
  8847. const empty = document.getElementById('bridge-empty-vlans');
  8848. const countBadge = document.getElementById('bridge-vlans-count-badge');
  8849. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  8850. if (!tbody) return;
  8851. tbody.innerHTML = '';
  8852. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  8853. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  8854. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  8855. if (vlans.length === 0) {
  8856. empty?.classList.remove('hidden');
  8857. return;
  8858. }
  8859. empty?.classList.add('hidden');
  8860. vlans.forEach((v, idx) => {
  8861. const tr = document.createElement('tr');
  8862. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  8863. const taggedHtml = (v.tagged && v.tagged.length > 0)
  8864. ? 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(' ')
  8865. : '<span class="text-slate-600">none</span>';
  8866. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  8867. ? 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(' ')
  8868. : '<span class="text-slate-600">none</span>';
  8869. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8870. tr.innerHTML = `
  8871. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8872. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8873. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  8874. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  8875. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  8876. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  8877. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  8878. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8879. <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>
  8880. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8881. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8882. </td>
  8883. `;
  8884. tbody.appendChild(tr);
  8885. });
  8886. }
  8887. function openAddBridgeVLANModal() {
  8888. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  8889. document.getElementById('bridge-vlan-modal-id').value = '';
  8890. populateBridgeSelect('bridge-vlan-modal-bridge');
  8891. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  8892. document.getElementById('bridge-vlan-modal-comment').value = '';
  8893. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  8894. updateBridgeVlanPortCheckboxes();
  8895. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8896. }
  8897. function openEditBridgeVLANModal(id) {
  8898. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  8899. if (!v) return;
  8900. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  8901. document.getElementById('bridge-vlan-modal-id').value = v.id;
  8902. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  8903. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  8904. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  8905. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  8906. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  8907. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8908. }
  8909. function closeBridgeVlanModal() {
  8910. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  8911. }
  8912. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  8913. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  8914. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  8915. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  8916. if (!taggedBox || !untaggedBox) return;
  8917. // Ports belonging to the selected bridge
  8918. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  8919. if (memberPorts.length === 0) {
  8920. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8921. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8922. return;
  8923. }
  8924. taggedBox.innerHTML = memberPorts.map(p => `
  8925. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8926. <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">
  8927. <span>${p.interface}</span>
  8928. </label>
  8929. `).join('');
  8930. untaggedBox.innerHTML = memberPorts.map(p => `
  8931. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8932. <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">
  8933. <span>${p.interface}</span>
  8934. </label>
  8935. `).join('');
  8936. }
  8937. async function submitSaveBridgeVLAN(e) {
  8938. e.preventDefault();
  8939. const id = document.getElementById('bridge-vlan-modal-id').value;
  8940. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  8941. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  8942. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  8943. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  8944. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  8945. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  8946. try {
  8947. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  8948. method: 'POST',
  8949. headers: { 'Content-Type': 'application/json' },
  8950. body: JSON.stringify({
  8951. id,
  8952. bridge,
  8953. vlan_ids: vlanIDs,
  8954. tagged,
  8955. untagged,
  8956. comment,
  8957. disabled
  8958. })
  8959. });
  8960. if (res.ok) {
  8961. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  8962. closeBridgeVlanModal();
  8963. loadBridge();
  8964. } else {
  8965. const err = await res.json();
  8966. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  8967. }
  8968. } catch (err) {
  8969. showToast('Error', err.message, 'error');
  8970. }
  8971. }
  8972. async function toggleBridgeVLANState(id, disabled) {
  8973. try {
  8974. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  8975. method: 'POST',
  8976. headers: { 'Content-Type': 'application/json' },
  8977. body: JSON.stringify({ disabled })
  8978. });
  8979. if (res.ok) loadBridge();
  8980. } catch (err) {
  8981. showToast('Error', err.message, 'error');
  8982. }
  8983. }
  8984. async function deleteBridgeVLAN(id) {
  8985. if (!confirm('Delete this bridge VLAN entry?')) return;
  8986. try {
  8987. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8988. if (res.ok) {
  8989. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  8990. loadBridge();
  8991. }
  8992. } catch (err) {
  8993. showToast('Error', err.message, 'error');
  8994. }
  8995. }
  8996. // ----------------- Hosts / MAC Table -----------------
  8997. async function loadBridgeHosts() {
  8998. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  8999. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9000. try {
  9001. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9002. const res = await fetch(url);
  9003. if (res.ok) {
  9004. state.bridgeHosts = await res.json();
  9005. renderBridgeHosts();
  9006. }
  9007. } catch (err) {
  9008. console.error('Failed to load bridge hosts:', err);
  9009. }
  9010. }
  9011. function renderBridgeHosts() {
  9012. const tbody = document.getElementById('bridge-hosts-table-body');
  9013. const empty = document.getElementById('bridge-empty-hosts');
  9014. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9015. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9016. if (!tbody) return;
  9017. tbody.innerHTML = '';
  9018. const hosts = (state.bridgeHosts || []).filter(h => {
  9019. if (!search) return true;
  9020. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9021. });
  9022. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9023. if (hosts.length === 0) {
  9024. empty?.classList.remove('hidden');
  9025. return;
  9026. }
  9027. empty?.classList.add('hidden');
  9028. hosts.forEach(h => {
  9029. const tr = document.createElement('tr');
  9030. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9031. let flagBadges = '';
  9032. 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>';
  9033. 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>';
  9034. 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>';
  9035. tr.innerHTML = `
  9036. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9037. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9038. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9039. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9040. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9041. <td class="py-2.5 px-3">${flagBadges}</td>
  9042. `;
  9043. tbody.appendChild(tr);
  9044. });
  9045. }
  9046. async function flushBridgeHosts() {
  9047. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9048. if (!selBridge) {
  9049. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9050. return;
  9051. }
  9052. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9053. try {
  9054. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9055. method: 'POST',
  9056. headers: { 'Content-Type': 'application/json' },
  9057. body: JSON.stringify({ bridge: selBridge })
  9058. });
  9059. if (res.ok) {
  9060. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9061. loadBridgeHosts();
  9062. }
  9063. } catch (err) {
  9064. showToast('Error', err.message, 'error');
  9065. }
  9066. }
  9067. // ----------------- Helpers -----------------
  9068. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9069. const sel = document.getElementById(selectId);
  9070. if (!sel) return;
  9071. const prevVal = currentVal || sel.value;
  9072. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9073. (state.bridges || []).forEach(b => {
  9074. const opt = document.createElement('option');
  9075. opt.value = b.name;
  9076. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9077. if (b.name === prevVal) opt.selected = true;
  9078. sel.appendChild(opt);
  9079. });
  9080. }
  9081. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9082. const sel = document.getElementById(selectId);
  9083. if (!sel) return;
  9084. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9085. // 1. Physical Interfaces
  9086. const grpPhys = document.createElement('optgroup');
  9087. grpPhys.label = 'Physical Interfaces';
  9088. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9089. const opt = document.createElement('option');
  9090. opt.value = i.name;
  9091. opt.innerText = `${i.name} (${i.role || i.type})`;
  9092. if (i.name === currentVal) opt.selected = true;
  9093. grpPhys.appendChild(opt);
  9094. });
  9095. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9096. // 2. VLAN Sub-interfaces
  9097. const grpVlans = document.createElement('optgroup');
  9098. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9099. (state.vlans || []).forEach(v => {
  9100. const opt = document.createElement('option');
  9101. opt.value = v.name;
  9102. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9103. if (v.name === currentVal) opt.selected = true;
  9104. grpVlans.appendChild(opt);
  9105. });
  9106. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9107. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9108. const grpEoip = document.createElement('optgroup');
  9109. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9110. (state.eoipTunnels || []).forEach(t => {
  9111. const opt = document.createElement('option');
  9112. opt.value = t.name;
  9113. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9114. if (t.name === currentVal) opt.selected = true;
  9115. grpEoip.appendChild(opt);
  9116. });
  9117. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9118. }
  9119. // -------------------------------------------------------------
  9120. // RouterOS v7 Routing Filters Management (/routing filter)
  9121. // -------------------------------------------------------------
  9122. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9123. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9124. if (!state.rfSort) state.rfSort = {};
  9125. function switchRoutingFilterTab(tab) {
  9126. state.activeRoutingFilterTab = tab;
  9127. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9128. tabs.forEach(t => {
  9129. const btn = document.getElementById(`tab-rf-${t}`);
  9130. const content = document.getElementById(`tab-content-rf-${t}`);
  9131. if (btn) {
  9132. if (t === tab) {
  9133. 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';
  9134. } else {
  9135. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9136. }
  9137. }
  9138. if (content) {
  9139. if (t === tab) content.classList.remove('hidden');
  9140. else content.classList.add('hidden');
  9141. }
  9142. });
  9143. const chainContainer = document.getElementById('rf-chain-filter-container');
  9144. if (chainContainer) {
  9145. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9146. else chainContainer.classList.add('hidden');
  9147. }
  9148. renderRoutingFilters();
  9149. }
  9150. function selectFilterRow(tab, id) {
  9151. if (state.selectedFilterRow[tab] === id) {
  9152. delete state.selectedFilterRow[tab];
  9153. } else {
  9154. state.selectedFilterRow[tab] = id;
  9155. }
  9156. if (tab === 'rules') renderRoutingFilterRules();
  9157. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9158. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9159. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9160. }
  9161. function openRoutingFilterNewModal() {
  9162. const tab = state.activeRoutingFilterTab || 'rules';
  9163. if (tab === 'rules') openAddRoutingFilterModal();
  9164. else if (tab === 'select-rules') openAddSelectRuleModal();
  9165. else if (tab === 'community-lists') openAddCommunityListModal();
  9166. else if (tab === 'as-lists') openAddASListModal();
  9167. }
  9168. function toggleSelectedRoutingFilter(disabled) {
  9169. const tab = state.activeRoutingFilterTab || 'rules';
  9170. const id = state.selectedFilterRow[tab];
  9171. if (!id) {
  9172. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9173. return;
  9174. }
  9175. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9176. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9177. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9178. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9179. }
  9180. function removeSelectedRoutingFilter() {
  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') deleteRoutingFilter(id);
  9188. else if (tab === 'select-rules') deleteSelectRule(id);
  9189. else if (tab === 'community-lists') deleteCommunityList(id);
  9190. else if (tab === 'as-lists') deleteASList(id);
  9191. }
  9192. function searchRoutingFilters(q) {
  9193. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9194. renderRoutingFilters();
  9195. }
  9196. function sortFilterTable(tab, col) {
  9197. if (!state.rfSort) state.rfSort = {};
  9198. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9199. if (state.rfSort[tab].col === col) {
  9200. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9201. } else {
  9202. state.rfSort[tab].col = col;
  9203. state.rfSort[tab].asc = true;
  9204. }
  9205. const asc = state.rfSort[tab].asc;
  9206. let list = [];
  9207. if (tab === 'rules') list = state.routingFilters || [];
  9208. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9209. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9210. else if (tab === 'as-lists') list = state.routingASLists || [];
  9211. list.sort((a, b) => {
  9212. let valA = a[col] ?? '';
  9213. let valB = b[col] ?? '';
  9214. if (col === 'flags') {
  9215. valA = a.disabled ? 'X' : 'A';
  9216. valB = b.disabled ? 'X' : 'A';
  9217. }
  9218. if (typeof valA === 'number' && typeof valB === 'number') {
  9219. return asc ? valA - valB : valB - valA;
  9220. }
  9221. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9222. });
  9223. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9224. allCols.forEach(c => {
  9225. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9226. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9227. });
  9228. if (tab === 'rules') renderRoutingFilterRules();
  9229. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9230. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9231. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9232. }
  9233. function renderRoutingFilters() {
  9234. const navBadge = document.getElementById('badge-filters-count');
  9235. const allRules = state.routingFilters || [];
  9236. if (navBadge) navBadge.innerText = allRules.length;
  9237. // Populate chain filter select options and datalist
  9238. const chainSelect = document.getElementById('routing-filter-chain-select');
  9239. const chainDatalist = document.getElementById('dl-routing-chains');
  9240. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9241. if (chainSelect) {
  9242. const currentVal = state.filterChainSelected || 'all';
  9243. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9244. uniqueChains.map(ch => {
  9245. const count = allRules.filter(r => r.chain === ch).length;
  9246. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9247. }).join('');
  9248. chainSelect.value = currentVal;
  9249. }
  9250. if (chainDatalist) {
  9251. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9252. }
  9253. renderRoutingFilterRules();
  9254. renderRoutingFilterSelectRules();
  9255. renderRoutingFilterCommunityLists();
  9256. renderRoutingFilterASLists();
  9257. }
  9258. function filterRoutingFiltersByChain(chain) {
  9259. state.filterChainSelected = chain;
  9260. renderRoutingFilters();
  9261. }
  9262. // -------------------------------------------------------------
  9263. // TAB 1: RULES (/routing filter rule)
  9264. // -------------------------------------------------------------
  9265. function renderRoutingFilterRules() {
  9266. const tbody = document.getElementById('routing-filter-rules-tbody');
  9267. if (!tbody) return;
  9268. const empty = document.getElementById('rf-rules-empty');
  9269. const statusCount = document.getElementById('rf-status-count');
  9270. let list = (state.routingFilters || []).slice();
  9271. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9272. list = list.filter(r => r.chain === state.filterChainSelected);
  9273. }
  9274. const q = state.rfSearchQuery;
  9275. if (q) {
  9276. list = list.filter(r =>
  9277. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9278. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9279. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9280. (r.comment && r.comment.toLowerCase().includes(q))
  9281. );
  9282. }
  9283. if (!state.rfSort?.['rules']) {
  9284. list.sort((a, b) => {
  9285. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9286. return (a.rule_order || 0) - (b.rule_order || 0);
  9287. });
  9288. }
  9289. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9290. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9291. }
  9292. if (list.length === 0) {
  9293. tbody.innerHTML = '';
  9294. if (empty) empty.classList.remove('hidden');
  9295. return;
  9296. }
  9297. if (empty) empty.classList.add('hidden');
  9298. tbody.innerHTML = list.map(r => {
  9299. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9300. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9301. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9302. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9303. let ruleDisplay = '';
  9304. if (r.rule && r.rule.trim() !== '') {
  9305. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9306. } else {
  9307. let conds = [];
  9308. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9309. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9310. let act = r.action || 'accept';
  9311. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9312. }
  9313. return `
  9314. <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'}">
  9315. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9316. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9317. <td class="py-2 px-3">
  9318. <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>
  9319. </td>
  9320. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9321. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9322. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9323. <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>
  9324. <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>
  9325. <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'}">
  9326. ${r.disabled ? 'Enable' : 'Disable'}
  9327. </button>
  9328. <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">
  9329. Edit
  9330. </button>
  9331. <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">
  9332. ✕
  9333. </button>
  9334. </td>
  9335. </tr>
  9336. `;
  9337. }).join('');
  9338. }
  9339. // -------------------------------------------------------------
  9340. // TAB 2: SELECT RULES (/routing filter select-rule)
  9341. // -------------------------------------------------------------
  9342. function renderRoutingFilterSelectRules() {
  9343. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9344. if (!tbody) return;
  9345. const empty = document.getElementById('rf-select-rules-empty');
  9346. const statusCount = document.getElementById('rf-status-count');
  9347. let list = (state.routingSelectRules || []).slice();
  9348. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9349. list = list.filter(r => r.chain === state.filterChainSelected);
  9350. }
  9351. const q = state.rfSearchQuery;
  9352. if (q) {
  9353. list = list.filter(r =>
  9354. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9355. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9356. (r.comment && r.comment.toLowerCase().includes(q))
  9357. );
  9358. }
  9359. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9360. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9361. }
  9362. if (list.length === 0) {
  9363. tbody.innerHTML = '';
  9364. if (empty) empty.classList.remove('hidden');
  9365. return;
  9366. }
  9367. if (empty) empty.classList.add('hidden');
  9368. tbody.innerHTML = list.map(r => {
  9369. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9370. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9371. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9372. return `
  9373. <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'}">
  9374. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9375. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9376. <td class="py-2 px-3">
  9377. <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>
  9378. </td>
  9379. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9380. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9381. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9382. <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'}">
  9383. ${r.disabled ? 'Enable' : 'Disable'}
  9384. </button>
  9385. <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">
  9386. Edit
  9387. </button>
  9388. <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">
  9389. ✕
  9390. </button>
  9391. </td>
  9392. </tr>
  9393. `;
  9394. }).join('');
  9395. }
  9396. // -------------------------------------------------------------
  9397. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9398. // -------------------------------------------------------------
  9399. function renderRoutingFilterCommunityLists() {
  9400. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9401. if (!tbody) return;
  9402. const empty = document.getElementById('rf-comm-lists-empty');
  9403. const statusCount = document.getElementById('rf-status-count');
  9404. let list = (state.routingCommunityLists || []).slice();
  9405. const q = state.rfSearchQuery;
  9406. if (q) {
  9407. list = list.filter(cl =>
  9408. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9409. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9410. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9411. );
  9412. }
  9413. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9414. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9415. }
  9416. if (list.length === 0) {
  9417. tbody.innerHTML = '';
  9418. if (empty) empty.classList.remove('hidden');
  9419. return;
  9420. }
  9421. if (empty) empty.classList.add('hidden');
  9422. tbody.innerHTML = list.map(cl => {
  9423. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9424. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9425. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9426. const commBadges = (cl.communities || []).map(c =>
  9427. `<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>`
  9428. ).join(' ');
  9429. return `
  9430. <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'}">
  9431. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9432. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9433. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9434. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9435. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9436. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9437. <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'}">
  9438. ${cl.disabled ? 'Enable' : 'Disable'}
  9439. </button>
  9440. <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">
  9441. Edit
  9442. </button>
  9443. <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">
  9444. ✕
  9445. </button>
  9446. </td>
  9447. </tr>
  9448. `;
  9449. }).join('');
  9450. }
  9451. // -------------------------------------------------------------
  9452. // TAB 4: AS LISTS (/routing filter num-list)
  9453. // -------------------------------------------------------------
  9454. function renderRoutingFilterASLists() {
  9455. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9456. if (!tbody) return;
  9457. const empty = document.getElementById('rf-as-lists-empty');
  9458. const statusCount = document.getElementById('rf-status-count');
  9459. let list = (state.routingASLists || []).slice();
  9460. const q = state.rfSearchQuery;
  9461. if (q) {
  9462. list = list.filter(al =>
  9463. (al.name && al.name.toLowerCase().includes(q)) ||
  9464. (al.range && al.range.toLowerCase().includes(q)) ||
  9465. (al.comment && al.comment.toLowerCase().includes(q))
  9466. );
  9467. }
  9468. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9469. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9470. }
  9471. if (list.length === 0) {
  9472. tbody.innerHTML = '';
  9473. if (empty) empty.classList.remove('hidden');
  9474. return;
  9475. }
  9476. if (empty) empty.classList.add('hidden');
  9477. tbody.innerHTML = list.map(al => {
  9478. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9479. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9480. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9481. return `
  9482. <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'}">
  9483. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9484. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9485. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9486. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9487. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9488. <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'}">
  9489. ${al.disabled ? 'Enable' : 'Disable'}
  9490. </button>
  9491. <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">
  9492. Edit
  9493. </button>
  9494. <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">
  9495. ✕
  9496. </button>
  9497. </td>
  9498. </tr>
  9499. `;
  9500. }).join('');
  9501. }
  9502. // -------------------------------------------------------------
  9503. // SNIPPETS & WIZARD HELPERS
  9504. // -------------------------------------------------------------
  9505. function insertRuleSnippet(type) {
  9506. const textarea = document.getElementById('modal-rf-rule');
  9507. if (!textarea) return;
  9508. let snippet = '';
  9509. switch (type) {
  9510. case 'accept-default':
  9511. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9512. break;
  9513. case 'drop-rfc1918':
  9514. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9515. break;
  9516. case 'len-24':
  9517. snippet = 'if (dst-len > 24) { reject; }';
  9518. break;
  9519. case 'local-pref-150':
  9520. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9521. break;
  9522. case 'as-prepend-2':
  9523. snippet = 'set bgp-path-prepend 2; accept;';
  9524. break;
  9525. case 'set-comm':
  9526. snippet = 'set bgp-communities.add 65000:100; accept;';
  9527. break;
  9528. case 'match-comm':
  9529. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9530. break;
  9531. case 'reject-all':
  9532. snippet = 'reject;';
  9533. break;
  9534. }
  9535. if (!snippet) return;
  9536. if (!textarea.value.trim()) {
  9537. textarea.value = snippet;
  9538. } else {
  9539. textarea.value = textarea.value.trim() + '\n' + snippet;
  9540. }
  9541. }
  9542. function generateScriptFromWizard() {
  9543. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9544. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9545. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9546. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9547. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9548. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9549. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9550. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9551. const conds = [];
  9552. if (pfx) {
  9553. if (pfxLen) {
  9554. if (pfxLen.includes('-')) {
  9555. const parts = pfxLen.split('-');
  9556. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9557. } else {
  9558. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9559. }
  9560. } else {
  9561. conds.push(`dst in ${pfx}`);
  9562. }
  9563. }
  9564. if (proto && proto !== 'any') {
  9565. conds.push(`protocol ${proto}`);
  9566. }
  9567. if (asp) {
  9568. conds.push(`bgp-as-path "${asp}"`);
  9569. }
  9570. if (comm) {
  9571. conds.push(`bgp-communities includes ${comm}`);
  9572. }
  9573. const actions = [];
  9574. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9575. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9576. actions.push(`${act};`);
  9577. let code = '';
  9578. if (conds.length > 0) {
  9579. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9580. } else {
  9581. code = actions.join(' ');
  9582. }
  9583. const textarea = document.getElementById('modal-rf-rule');
  9584. if (textarea) textarea.value = code;
  9585. }
  9586. // -------------------------------------------------------------
  9587. // MODAL CRUD: RULES (/routing filter rule)
  9588. // -------------------------------------------------------------
  9589. function openAddRoutingFilterModal(defaultChain = '') {
  9590. const form = document.getElementById('routing-filter-form');
  9591. if (form) form.reset();
  9592. const idEl = document.getElementById('modal-rf-id');
  9593. if (idEl) idEl.value = '';
  9594. const titleEl = document.getElementById('modal-rf-title');
  9595. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9596. const chainEl = document.getElementById('modal-rf-chain');
  9597. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9598. const orderEl = document.getElementById('modal-rf-order');
  9599. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9600. const ruleEl = document.getElementById('modal-rf-rule');
  9601. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9602. const disEl = document.getElementById('modal-rf-disabled');
  9603. if (disEl) disEl.checked = false;
  9604. const modal = document.getElementById('modal-routing-filter');
  9605. if (modal) modal.classList.remove('hidden');
  9606. }
  9607. function openEditRoutingFilterModal(id) {
  9608. const r = (state.routingFilters || []).find(item => item.id === id);
  9609. if (!r) return;
  9610. const idEl = document.getElementById('modal-rf-id');
  9611. if (idEl) idEl.value = r.id;
  9612. const titleEl = document.getElementById('modal-rf-title');
  9613. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9614. const chainEl = document.getElementById('modal-rf-chain');
  9615. if (chainEl) chainEl.value = r.chain || '';
  9616. const orderEl = document.getElementById('modal-rf-order');
  9617. if (orderEl) orderEl.value = r.rule_order || 10;
  9618. const ruleEl = document.getElementById('modal-rf-rule');
  9619. if (ruleEl) {
  9620. if (r.rule) {
  9621. ruleEl.value = r.rule;
  9622. } else {
  9623. let conds = [];
  9624. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9625. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9626. let act = r.action || 'accept';
  9627. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9628. }
  9629. }
  9630. const comEl = document.getElementById('modal-rf-comment');
  9631. if (comEl) comEl.value = r.comment || '';
  9632. const disEl = document.getElementById('modal-rf-disabled');
  9633. if (disEl) disEl.checked = !!r.disabled;
  9634. const modal = document.getElementById('modal-routing-filter');
  9635. if (modal) modal.classList.remove('hidden');
  9636. }
  9637. function closeRoutingFilterModal() {
  9638. const modal = document.getElementById('modal-routing-filter');
  9639. if (modal) modal.classList.add('hidden');
  9640. }
  9641. async function submitRoutingFilter(e) {
  9642. if (e) e.preventDefault();
  9643. const payload = {
  9644. id: document.getElementById('modal-rf-id').value,
  9645. chain: document.getElementById('modal-rf-chain').value.trim(),
  9646. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9647. rule: document.getElementById('modal-rf-rule').value.trim(),
  9648. comment: document.getElementById('modal-rf-comment').value.trim(),
  9649. disabled: document.getElementById('modal-rf-disabled').checked
  9650. };
  9651. try {
  9652. const res = await fetch(`${API_BASE}/routing/filters`, {
  9653. method: 'POST',
  9654. headers: { 'Content-Type': 'application/json' },
  9655. body: JSON.stringify(payload)
  9656. });
  9657. if (res.ok) {
  9658. closeRoutingFilterModal();
  9659. showToast('Success', 'Routing filter rule saved', 'success');
  9660. loadDynamicRouting();
  9661. } else {
  9662. const err = await res.json();
  9663. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9664. }
  9665. } catch (err) {
  9666. showToast('Error', err.message, 'error');
  9667. }
  9668. }
  9669. async function applyRoutingFilterForm() {
  9670. const payload = {
  9671. id: document.getElementById('modal-rf-id').value,
  9672. chain: document.getElementById('modal-rf-chain').value.trim(),
  9673. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9674. rule: document.getElementById('modal-rf-rule').value.trim(),
  9675. comment: document.getElementById('modal-rf-comment').value.trim(),
  9676. disabled: document.getElementById('modal-rf-disabled').checked
  9677. };
  9678. try {
  9679. const res = await fetch(`${API_BASE}/routing/filters`, {
  9680. method: 'POST',
  9681. headers: { 'Content-Type': 'application/json' },
  9682. body: JSON.stringify(payload)
  9683. });
  9684. if (res.ok) {
  9685. const data = await res.json();
  9686. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  9687. showToast('Applied', 'Routing filter configuration applied', 'success');
  9688. loadDynamicRouting();
  9689. } else {
  9690. const err = await res.json();
  9691. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  9692. }
  9693. } catch (err) {
  9694. showToast('Error', err.message, 'error');
  9695. }
  9696. }
  9697. async function moveRoutingFilterOrder(id, delta) {
  9698. const list = state.routingFilters || [];
  9699. const idx = list.findIndex(r => r.id === id);
  9700. if (idx < 0) return;
  9701. const targetIdx = idx + delta;
  9702. if (targetIdx < 0 || targetIdx >= list.length) return;
  9703. const currentOrder = list[idx].rule_order || 10;
  9704. const targetOrder = list[targetIdx].rule_order || 20;
  9705. list[idx].rule_order = targetOrder;
  9706. list[targetIdx].rule_order = currentOrder;
  9707. try {
  9708. await fetch(`${API_BASE}/routing/filters`, {
  9709. method: 'POST',
  9710. headers: { 'Content-Type': 'application/json' },
  9711. body: JSON.stringify(list[idx])
  9712. });
  9713. await fetch(`${API_BASE}/routing/filters`, {
  9714. method: 'POST',
  9715. headers: { 'Content-Type': 'application/json' },
  9716. body: JSON.stringify(list[targetIdx])
  9717. });
  9718. loadDynamicRouting();
  9719. } catch (e) {
  9720. console.error('Reorder error:', e);
  9721. }
  9722. }
  9723. async function deleteRoutingFilter(id) {
  9724. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  9725. try {
  9726. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9727. if (res.ok) {
  9728. showToast('Deleted', 'Routing filter rule removed', 'info');
  9729. loadDynamicRouting();
  9730. } else {
  9731. const err = await res.json();
  9732. showToast('Error', err.error || 'Failed to delete rule', 'error');
  9733. }
  9734. } catch (err) {
  9735. showToast('Error', err.message, 'error');
  9736. }
  9737. }
  9738. async function toggleRoutingFilterState(id, disabled) {
  9739. try {
  9740. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  9741. method: 'POST',
  9742. headers: { 'Content-Type': 'application/json' },
  9743. body: JSON.stringify({ disabled })
  9744. });
  9745. if (res.ok) {
  9746. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9747. loadDynamicRouting();
  9748. } else {
  9749. const err = await res.json();
  9750. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  9751. }
  9752. } catch (err) {
  9753. showToast('Error', err.message, 'error');
  9754. }
  9755. }
  9756. // -------------------------------------------------------------
  9757. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  9758. // -------------------------------------------------------------
  9759. function openAddSelectRuleModal() {
  9760. document.getElementById('modal-rf-sr-id').value = '';
  9761. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  9762. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  9763. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  9764. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  9765. document.getElementById('modal-rf-sr-comment').value = '';
  9766. document.getElementById('modal-rf-sr-disabled').checked = false;
  9767. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9768. }
  9769. function openEditSelectRuleModal(id) {
  9770. const r = (state.routingSelectRules || []).find(item => item.id === id);
  9771. if (!r) return;
  9772. document.getElementById('modal-rf-sr-id').value = r.id;
  9773. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  9774. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  9775. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  9776. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  9777. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  9778. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  9779. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9780. }
  9781. function closeSelectRuleModal() {
  9782. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  9783. }
  9784. async function submitSelectRule(e) {
  9785. e.preventDefault();
  9786. const payload = {
  9787. id: document.getElementById('modal-rf-sr-id').value,
  9788. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  9789. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  9790. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  9791. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  9792. disabled: document.getElementById('modal-rf-sr-disabled').checked
  9793. };
  9794. try {
  9795. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  9796. method: 'POST',
  9797. headers: { 'Content-Type': 'application/json' },
  9798. body: JSON.stringify(payload)
  9799. });
  9800. if (res.ok) {
  9801. closeSelectRuleModal();
  9802. showToast('Success', 'Select rule saved', 'success');
  9803. loadDynamicRouting();
  9804. } else {
  9805. const err = await res.json();
  9806. showToast('Error', err.error || 'Failed to save select rule', 'error');
  9807. }
  9808. } catch (err) {
  9809. showToast('Error', err.message, 'error');
  9810. }
  9811. }
  9812. async function deleteSelectRule(id) {
  9813. if (!confirm('Are you sure you want to delete this select rule?')) return;
  9814. try {
  9815. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9816. if (res.ok) {
  9817. showToast('Deleted', 'Select rule removed', 'info');
  9818. loadDynamicRouting();
  9819. } else {
  9820. const err = await res.json();
  9821. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  9822. }
  9823. } catch (err) {
  9824. showToast('Error', err.message, 'error');
  9825. }
  9826. }
  9827. async function toggleSelectRuleState(id, disabled) {
  9828. try {
  9829. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  9830. method: 'POST',
  9831. headers: { 'Content-Type': 'application/json' },
  9832. body: JSON.stringify({ disabled })
  9833. });
  9834. if (res.ok) {
  9835. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9836. loadDynamicRouting();
  9837. } else {
  9838. const err = await res.json();
  9839. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  9840. }
  9841. } catch (err) {
  9842. showToast('Error', err.message, 'error');
  9843. }
  9844. }
  9845. // -------------------------------------------------------------
  9846. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  9847. // -------------------------------------------------------------
  9848. function openAddCommunityListModal() {
  9849. document.getElementById('modal-rf-cl-id').value = '';
  9850. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  9851. document.getElementById('modal-rf-cl-name').value = '';
  9852. document.getElementById('modal-rf-cl-communities').value = '';
  9853. document.getElementById('modal-rf-cl-regexp').value = '';
  9854. document.getElementById('modal-rf-cl-comment').value = '';
  9855. document.getElementById('modal-rf-cl-disabled').checked = false;
  9856. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9857. }
  9858. function openEditCommunityListModal(id) {
  9859. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  9860. if (!cl) return;
  9861. document.getElementById('modal-rf-cl-id').value = cl.id;
  9862. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  9863. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  9864. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  9865. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  9866. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  9867. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  9868. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9869. }
  9870. function closeCommunityListModal() {
  9871. document.getElementById('modal-rf-community-list').classList.add('hidden');
  9872. }
  9873. async function submitCommunityList(e) {
  9874. e.preventDefault();
  9875. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  9876. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  9877. const payload = {
  9878. id: document.getElementById('modal-rf-cl-id').value,
  9879. name: document.getElementById('modal-rf-cl-name').value.trim(),
  9880. communities: comms,
  9881. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  9882. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  9883. disabled: document.getElementById('modal-rf-cl-disabled').checked
  9884. };
  9885. try {
  9886. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  9887. method: 'POST',
  9888. headers: { 'Content-Type': 'application/json' },
  9889. body: JSON.stringify(payload)
  9890. });
  9891. if (res.ok) {
  9892. closeCommunityListModal();
  9893. showToast('Success', 'Community list saved', 'success');
  9894. loadDynamicRouting();
  9895. } else {
  9896. const err = await res.json();
  9897. showToast('Error', err.error || 'Failed to save community list', 'error');
  9898. }
  9899. } catch (err) {
  9900. showToast('Error', err.message, 'error');
  9901. }
  9902. }
  9903. async function deleteCommunityList(id) {
  9904. if (!confirm('Are you sure you want to delete this community list?')) return;
  9905. try {
  9906. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9907. if (res.ok) {
  9908. showToast('Deleted', 'Community list removed', 'info');
  9909. loadDynamicRouting();
  9910. } else {
  9911. const err = await res.json();
  9912. showToast('Error', err.error || 'Failed to delete community list', 'error');
  9913. }
  9914. } catch (err) {
  9915. showToast('Error', err.message, 'error');
  9916. }
  9917. }
  9918. async function toggleCommunityListState(id, disabled) {
  9919. try {
  9920. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  9921. method: 'POST',
  9922. headers: { 'Content-Type': 'application/json' },
  9923. body: JSON.stringify({ disabled })
  9924. });
  9925. if (res.ok) {
  9926. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9927. loadDynamicRouting();
  9928. } else {
  9929. const err = await res.json();
  9930. showToast('Error', err.error || 'Failed to update community list state', 'error');
  9931. }
  9932. } catch (err) {
  9933. showToast('Error', err.message, 'error');
  9934. }
  9935. }
  9936. // -------------------------------------------------------------
  9937. // MODAL CRUD: AS LISTS (/routing filter num-list)
  9938. // -------------------------------------------------------------
  9939. function openAddASListModal() {
  9940. document.getElementById('modal-rf-al-id').value = '';
  9941. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  9942. document.getElementById('modal-rf-al-name').value = '';
  9943. document.getElementById('modal-rf-al-range').value = '';
  9944. document.getElementById('modal-rf-al-comment').value = '';
  9945. document.getElementById('modal-rf-al-disabled').checked = false;
  9946. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9947. }
  9948. function openEditASListModal(id) {
  9949. const al = (state.routingASLists || []).find(item => item.id === id);
  9950. if (!al) return;
  9951. document.getElementById('modal-rf-al-id').value = al.id;
  9952. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  9953. document.getElementById('modal-rf-al-name').value = al.name || '';
  9954. document.getElementById('modal-rf-al-range').value = al.range || '';
  9955. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  9956. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  9957. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9958. }
  9959. function closeASListModal() {
  9960. document.getElementById('modal-rf-as-list').classList.add('hidden');
  9961. }
  9962. async function submitASList(e) {
  9963. e.preventDefault();
  9964. const payload = {
  9965. id: document.getElementById('modal-rf-al-id').value,
  9966. name: document.getElementById('modal-rf-al-name').value.trim(),
  9967. range: document.getElementById('modal-rf-al-range').value.trim(),
  9968. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  9969. disabled: document.getElementById('modal-rf-al-disabled').checked
  9970. };
  9971. try {
  9972. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  9973. method: 'POST',
  9974. headers: { 'Content-Type': 'application/json' },
  9975. body: JSON.stringify(payload)
  9976. });
  9977. if (res.ok) {
  9978. closeASListModal();
  9979. showToast('Success', 'AS number list saved', 'success');
  9980. loadDynamicRouting();
  9981. } else {
  9982. const err = await res.json();
  9983. showToast('Error', err.error || 'Failed to save AS list', 'error');
  9984. }
  9985. } catch (err) {
  9986. showToast('Error', err.message, 'error');
  9987. }
  9988. }
  9989. async function deleteASList(id) {
  9990. if (!confirm('Are you sure you want to delete this AS list?')) return;
  9991. try {
  9992. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9993. if (res.ok) {
  9994. showToast('Deleted', 'AS list removed', 'info');
  9995. loadDynamicRouting();
  9996. } else {
  9997. const err = await res.json();
  9998. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  9999. }
  10000. } catch (err) {
  10001. showToast('Error', err.message, 'error');
  10002. }
  10003. }
  10004. async function toggleASListState(id, disabled) {
  10005. try {
  10006. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10007. method: 'POST',
  10008. headers: { 'Content-Type': 'application/json' },
  10009. body: JSON.stringify({ disabled })
  10010. });
  10011. if (res.ok) {
  10012. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10013. loadDynamicRouting();
  10014. } else {
  10015. const err = await res.json();
  10016. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10017. }
  10018. } catch (err) {
  10019. showToast('Error', err.message, 'error');
  10020. }
  10021. }
  10022. // ==========================================
  10023. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10024. // ==========================================
  10025. function loadToolsView() {
  10026. populateToolsInterfaces();
  10027. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10028. }
  10029. function populateToolsInterfaces() {
  10030. const pingSel = document.getElementById('tools-ping-iface');
  10031. const traceSel = document.getElementById('tools-tr-iface');
  10032. let opts = '<option value="">Auto (Default Route)</option>';
  10033. if (Array.isArray(state.interfaces)) {
  10034. state.interfaces.forEach(iface => {
  10035. if (iface.name) {
  10036. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10037. }
  10038. });
  10039. }
  10040. if (pingSel) {
  10041. const cur = pingSel.value;
  10042. pingSel.innerHTML = opts;
  10043. if (cur) pingSel.value = cur;
  10044. }
  10045. if (traceSel) {
  10046. const cur = traceSel.value;
  10047. traceSel.innerHTML = opts;
  10048. if (cur) traceSel.value = cur;
  10049. }
  10050. }
  10051. function switchToolsSubTab(subTab) {
  10052. state.activeToolsSubTab = subTab;
  10053. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10054. tabs.forEach(t => {
  10055. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10056. const view = document.getElementById(`tools-view-${t}`);
  10057. if (btn) {
  10058. if (t === subTab) {
  10059. 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';
  10060. } else {
  10061. 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';
  10062. }
  10063. }
  10064. if (view) {
  10065. if (t === subTab) {
  10066. view.classList.remove('hidden');
  10067. } else {
  10068. view.classList.add('hidden');
  10069. }
  10070. }
  10071. });
  10072. }
  10073. function setPortPreset(port) {
  10074. const input = document.getElementById('tools-port-num');
  10075. if (input) input.value = port;
  10076. }
  10077. let pingAbortController = null;
  10078. let tracerouteAbortController = null;
  10079. function clearPingTable() {
  10080. const tbody = document.getElementById('tools-ping-tbody');
  10081. if (tbody) tbody.innerHTML = '';
  10082. const rawEl = document.getElementById('tools-ping-raw');
  10083. if (rawEl) rawEl.innerText = '';
  10084. const sentEl = document.getElementById('tools-ping-stat-sent');
  10085. if (sentEl) sentEl.innerText = '0';
  10086. const recvEl = document.getElementById('tools-ping-stat-recv');
  10087. if (recvEl) recvEl.innerText = '0';
  10088. const lossEl = document.getElementById('tools-ping-stat-loss');
  10089. if (lossEl) lossEl.innerText = '0%';
  10090. const avgEl = document.getElementById('tools-ping-stat-avg');
  10091. if (avgEl) avgEl.innerText = '0 ms';
  10092. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10093. if (minMaxEl) minMaxEl.innerText = '-';
  10094. const badge = document.getElementById('tools-ping-status-badge');
  10095. if (badge) {
  10096. badge.className = '';
  10097. badge.innerText = '';
  10098. }
  10099. }
  10100. function clearTracerouteTable() {
  10101. const tbody = document.getElementById('tools-tr-tbody');
  10102. if (tbody) tbody.innerHTML = '';
  10103. const rawEl = document.getElementById('tools-tr-raw');
  10104. if (rawEl) rawEl.innerText = '';
  10105. const statHops = document.getElementById('tools-tr-hops-count');
  10106. if (statHops) statHops.innerText = '0 Hops';
  10107. }
  10108. function resetPingButton() {
  10109. const btn = document.getElementById('tools-ping-btn');
  10110. const btnText = document.getElementById('tools-ping-btn-text');
  10111. const spinner = document.getElementById('tools-ping-spinner');
  10112. if (btn) {
  10113. btn.disabled = false;
  10114. 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';
  10115. }
  10116. if (btnText) btnText.innerText = 'Start Ping';
  10117. if (spinner) spinner.classList.add('hidden');
  10118. }
  10119. function setPingRunningButton() {
  10120. const btn = document.getElementById('tools-ping-btn');
  10121. const btnText = document.getElementById('tools-ping-btn-text');
  10122. const spinner = document.getElementById('tools-ping-spinner');
  10123. if (btn) {
  10124. btn.disabled = false;
  10125. 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';
  10126. }
  10127. if (btnText) btnText.innerText = 'Stop Ping';
  10128. if (spinner) spinner.classList.remove('hidden');
  10129. }
  10130. function resetTracerouteButton() {
  10131. const btn = document.getElementById('tools-tr-btn');
  10132. const btnText = document.getElementById('tools-tr-btn-text');
  10133. const spinner = document.getElementById('tools-tr-spinner');
  10134. if (btn) {
  10135. btn.disabled = false;
  10136. 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';
  10137. }
  10138. if (btnText) btnText.innerText = 'Start Traceroute';
  10139. if (spinner) spinner.classList.add('hidden');
  10140. }
  10141. function setTracerouteRunningButton() {
  10142. const btn = document.getElementById('tools-tr-btn');
  10143. const btnText = document.getElementById('tools-tr-btn-text');
  10144. const spinner = document.getElementById('tools-tr-spinner');
  10145. if (btn) {
  10146. btn.disabled = false;
  10147. 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';
  10148. }
  10149. if (btnText) btnText.innerText = 'Stop Traceroute';
  10150. if (spinner) spinner.classList.remove('hidden');
  10151. }
  10152. async function executePing(e) {
  10153. if (e) e.preventDefault();
  10154. // If already running, clicking the button stops the stream!
  10155. if (pingAbortController) {
  10156. pingAbortController.abort();
  10157. pingAbortController = null;
  10158. resetPingButton();
  10159. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10160. return;
  10161. }
  10162. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10163. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10164. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10165. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10166. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10167. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10168. if (!target) {
  10169. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10170. return;
  10171. }
  10172. clearPingTable();
  10173. const resCard = document.getElementById('tools-ping-results');
  10174. if (resCard) resCard.classList.remove('hidden');
  10175. pingAbortController = new AbortController();
  10176. setPingRunningButton();
  10177. try {
  10178. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10179. method: 'POST',
  10180. headers: { 'Content-Type': 'application/json' },
  10181. body: JSON.stringify({
  10182. target,
  10183. count,
  10184. size,
  10185. timeout,
  10186. interface: iface,
  10187. dont_frag: dontFrag
  10188. }),
  10189. signal: pingAbortController.signal
  10190. });
  10191. if (!res.ok) {
  10192. const errText = await res.text();
  10193. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10194. resetPingButton();
  10195. pingAbortController = null;
  10196. return;
  10197. }
  10198. const reader = res.body.getReader();
  10199. const decoder = new TextDecoder('utf-8');
  10200. let buffer = '';
  10201. while (true) {
  10202. const { done, value } = await reader.read();
  10203. if (done) break;
  10204. buffer += decoder.decode(value, { stream: true });
  10205. const blocks = buffer.split('\n\n');
  10206. buffer = blocks.pop() || '';
  10207. for (const block of blocks) {
  10208. const trimmed = block.trim();
  10209. if (!trimmed) continue;
  10210. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10211. try {
  10212. const evt = JSON.parse(line);
  10213. handleLivePingEvent(evt);
  10214. } catch (parseErr) {
  10215. console.warn('Ping SSE parse error:', parseErr, line);
  10216. }
  10217. }
  10218. }
  10219. } catch (err) {
  10220. if (err.name === 'AbortError') {
  10221. // User aborted normally
  10222. } else {
  10223. showToast('Ping Error', err.message, 'error');
  10224. }
  10225. } finally {
  10226. pingAbortController = null;
  10227. resetPingButton();
  10228. }
  10229. }
  10230. function handleLivePingEvent(evt) {
  10231. const sentEl = document.getElementById('tools-ping-stat-sent');
  10232. const recvEl = document.getElementById('tools-ping-stat-recv');
  10233. const lossEl = document.getElementById('tools-ping-stat-loss');
  10234. const avgEl = document.getElementById('tools-ping-stat-avg');
  10235. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10236. const badge = document.getElementById('tools-ping-status-badge');
  10237. const tbody = document.getElementById('tools-ping-tbody');
  10238. const rawEl = document.getElementById('tools-ping-raw');
  10239. if (evt.raw && rawEl) {
  10240. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10241. rawEl.scrollTop = rawEl.scrollHeight;
  10242. }
  10243. if (evt.type === 'reply') {
  10244. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10245. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10246. if (lossEl && evt.packet_loss_pct !== undefined) {
  10247. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10248. lossEl.className = evt.packet_loss_pct === 0
  10249. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10250. : (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');
  10251. }
  10252. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10253. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10254. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10255. }
  10256. if (badge) {
  10257. if (evt.packet_loss_pct === 0) {
  10258. 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';
  10259. badge.innerText = '100% OK';
  10260. } else {
  10261. 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';
  10262. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10263. }
  10264. }
  10265. if (tbody) {
  10266. const tr = document.createElement('tr');
  10267. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10268. tr.innerHTML = `
  10269. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10270. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10271. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10272. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10273. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10274. <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>
  10275. `;
  10276. tbody.appendChild(tr);
  10277. }
  10278. } else if (evt.type === 'timeout') {
  10279. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10280. if (lossEl && evt.packet_loss_pct !== undefined) {
  10281. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10282. 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';
  10283. }
  10284. if (badge) {
  10285. 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';
  10286. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10287. }
  10288. if (tbody) {
  10289. const tr = document.createElement('tr');
  10290. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10291. tr.innerHTML = `
  10292. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10293. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10294. <td class="py-2 px-3 text-slate-600">--</td>
  10295. <td class="py-2 px-3 text-slate-600">--</td>
  10296. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10297. <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>
  10298. `;
  10299. tbody.appendChild(tr);
  10300. }
  10301. } else if (evt.type === 'unreach') {
  10302. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10303. if (lossEl && evt.packet_loss_pct !== undefined) {
  10304. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10305. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10306. }
  10307. if (badge) {
  10308. 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';
  10309. badge.innerText = 'UNREACHABLE';
  10310. }
  10311. if (tbody) {
  10312. const tr = document.createElement('tr');
  10313. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10314. tr.innerHTML = `
  10315. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10316. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10317. <td class="py-2 px-3 text-slate-600">--</td>
  10318. <td class="py-2 px-3 text-slate-600">--</td>
  10319. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10320. <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>
  10321. `;
  10322. tbody.appendChild(tr);
  10323. }
  10324. } else if (evt.type === 'stats') {
  10325. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10326. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10327. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10328. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10329. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10330. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10331. }
  10332. } else if (evt.type === 'done') {
  10333. 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');
  10334. }
  10335. }
  10336. async function executeTraceroute(e) {
  10337. if (e) e.preventDefault();
  10338. if (tracerouteAbortController) {
  10339. tracerouteAbortController.abort();
  10340. tracerouteAbortController = null;
  10341. resetTracerouteButton();
  10342. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10343. return;
  10344. }
  10345. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10346. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10347. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10348. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10349. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10350. if (!target) {
  10351. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10352. return;
  10353. }
  10354. clearTracerouteTable();
  10355. const resCard = document.getElementById('tools-tr-results');
  10356. if (resCard) resCard.classList.remove('hidden');
  10357. tracerouteAbortController = new AbortController();
  10358. setTracerouteRunningButton();
  10359. try {
  10360. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10361. method: 'POST',
  10362. headers: { 'Content-Type': 'application/json' },
  10363. body: JSON.stringify({
  10364. target,
  10365. max_hops: maxHops,
  10366. protocol,
  10367. interface: iface,
  10368. resolve
  10369. }),
  10370. signal: tracerouteAbortController.signal
  10371. });
  10372. if (!res.ok) {
  10373. const errText = await res.text();
  10374. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10375. resetTracerouteButton();
  10376. tracerouteAbortController = null;
  10377. return;
  10378. }
  10379. const reader = res.body.getReader();
  10380. const decoder = new TextDecoder('utf-8');
  10381. let buffer = '';
  10382. while (true) {
  10383. const { done, value } = await reader.read();
  10384. if (done) break;
  10385. buffer += decoder.decode(value, { stream: true });
  10386. const blocks = buffer.split('\n\n');
  10387. buffer = blocks.pop() || '';
  10388. for (const block of blocks) {
  10389. const trimmed = block.trim();
  10390. if (!trimmed) continue;
  10391. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10392. try {
  10393. const evt = JSON.parse(line);
  10394. handleLiveTracerouteEvent(evt);
  10395. } catch (parseErr) {
  10396. console.warn('Traceroute SSE parse error:', parseErr, line);
  10397. }
  10398. }
  10399. }
  10400. } catch (err) {
  10401. if (err.name === 'AbortError') {
  10402. // User aborted normally
  10403. } else {
  10404. showToast('Traceroute Error', err.message, 'error');
  10405. }
  10406. } finally {
  10407. tracerouteAbortController = null;
  10408. resetTracerouteButton();
  10409. }
  10410. }
  10411. function handleLiveTracerouteEvent(evt) {
  10412. const statHops = document.getElementById('tools-tr-hops-count');
  10413. const tbody = document.getElementById('tools-tr-tbody');
  10414. const rawEl = document.getElementById('tools-tr-raw');
  10415. if (evt.raw && rawEl) {
  10416. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10417. rawEl.scrollTop = rawEl.scrollHeight;
  10418. }
  10419. if (evt.hops_count !== undefined && statHops) {
  10420. statHops.innerText = `${evt.hops_count} Hops`;
  10421. }
  10422. if (evt.type === 'hop' && evt.hop && tbody) {
  10423. const h = evt.hop;
  10424. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10425. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10426. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10427. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10428. const tr = document.createElement('tr');
  10429. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10430. tr.innerHTML = `
  10431. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10432. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10433. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10434. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10435. <td class="py-2.5 px-3 text-right">
  10436. ${isTimeout
  10437. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10438. : '<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>'}
  10439. </td>
  10440. `;
  10441. tbody.appendChild(tr);
  10442. } else if (evt.type === 'done') {
  10443. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10444. }
  10445. }
  10446. async function executeMTR(e) {
  10447. if (e) e.preventDefault();
  10448. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10449. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10450. if (!target) {
  10451. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10452. return;
  10453. }
  10454. const btn = document.getElementById('tools-mtr-btn');
  10455. const spinner = document.getElementById('tools-mtr-spinner');
  10456. if (btn) btn.disabled = true;
  10457. if (spinner) spinner.classList.remove('hidden');
  10458. try {
  10459. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10460. method: 'POST',
  10461. headers: { 'Content-Type': 'application/json' },
  10462. body: JSON.stringify({ target, count: cycles })
  10463. });
  10464. const data = await res.json();
  10465. if (!res.ok) {
  10466. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10467. return;
  10468. }
  10469. const resCard = document.getElementById('tools-mtr-results');
  10470. if (resCard) resCard.classList.remove('hidden');
  10471. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10472. const statHops = document.getElementById('tools-mtr-hops-count');
  10473. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10474. const tbody = document.getElementById('tools-mtr-tbody');
  10475. if (tbody) {
  10476. if (hopsCount > 0) {
  10477. tbody.innerHTML = data.hops.map(h => {
  10478. 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');
  10479. return `
  10480. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10481. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10482. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10483. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10484. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10485. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10486. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10487. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10488. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10489. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10490. </tr>
  10491. `;
  10492. }).join('');
  10493. } else {
  10494. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10495. }
  10496. }
  10497. const rawEl = document.getElementById('tools-mtr-raw');
  10498. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10499. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10500. } catch (err) {
  10501. showToast('MTR Error', err.message, 'error');
  10502. } finally {
  10503. if (btn) btn.disabled = false;
  10504. if (spinner) spinner.classList.add('hidden');
  10505. }
  10506. }
  10507. async function executeDNS(e) {
  10508. if (e) e.preventDefault();
  10509. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10510. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10511. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10512. if (!domain) {
  10513. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10514. return;
  10515. }
  10516. const btn = document.getElementById('tools-dns-btn');
  10517. const spinner = document.getElementById('tools-dns-spinner');
  10518. if (btn) btn.disabled = true;
  10519. if (spinner) spinner.classList.remove('hidden');
  10520. try {
  10521. const res = await fetch(`${API_BASE}/tools/dns`, {
  10522. method: 'POST',
  10523. headers: { 'Content-Type': 'application/json' },
  10524. body: JSON.stringify({ domain, type, server })
  10525. });
  10526. const data = await res.json();
  10527. if (!res.ok) {
  10528. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10529. return;
  10530. }
  10531. const resCard = document.getElementById('tools-dns-results');
  10532. if (resCard) resCard.classList.remove('hidden');
  10533. const metaEl = document.getElementById('tools-dns-meta');
  10534. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10535. const tbody = document.getElementById('tools-dns-tbody');
  10536. if (tbody) {
  10537. if (Array.isArray(data.records) && data.records.length > 0) {
  10538. tbody.innerHTML = data.records.map(r => `
  10539. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10540. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10541. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10542. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10543. <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>
  10544. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10545. </tr>
  10546. `).join('');
  10547. } else {
  10548. 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>`;
  10549. }
  10550. }
  10551. const rawEl = document.getElementById('tools-dns-raw');
  10552. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10553. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10554. } catch (err) {
  10555. showToast('DNS Error', err.message, 'error');
  10556. } finally {
  10557. if (btn) btn.disabled = false;
  10558. if (spinner) spinner.classList.add('hidden');
  10559. }
  10560. }
  10561. async function executePortProbe(e) {
  10562. if (e) e.preventDefault();
  10563. const target = document.getElementById('tools-port-target')?.value?.trim();
  10564. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10565. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10566. if (!target || !port) {
  10567. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10568. return;
  10569. }
  10570. const btn = document.getElementById('tools-port-btn');
  10571. const spinner = document.getElementById('tools-port-spinner');
  10572. if (btn) btn.disabled = true;
  10573. if (spinner) spinner.classList.remove('hidden');
  10574. try {
  10575. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10576. method: 'POST',
  10577. headers: { 'Content-Type': 'application/json' },
  10578. body: JSON.stringify({ target, port, timeout })
  10579. });
  10580. const data = await res.json();
  10581. if (!res.ok) {
  10582. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10583. return;
  10584. }
  10585. const resCard = document.getElementById('tools-port-results');
  10586. if (resCard) resCard.classList.remove('hidden');
  10587. const banner = document.getElementById('tools-port-banner');
  10588. const icon = document.getElementById('tools-port-icon');
  10589. const title = document.getElementById('tools-port-title');
  10590. const sub = document.getElementById('tools-port-sub');
  10591. const latency = document.getElementById('tools-port-latency');
  10592. if (data.open) {
  10593. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10594. if (icon) {
  10595. 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';
  10596. icon.innerText = '✓';
  10597. }
  10598. if (title) {
  10599. title.className = 'text-sm font-bold text-emerald-300';
  10600. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10601. }
  10602. if (sub) {
  10603. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10604. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10605. }
  10606. if (latency) {
  10607. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10608. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10609. }
  10610. } else {
  10611. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10612. if (icon) {
  10613. 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';
  10614. icon.innerText = '✕';
  10615. }
  10616. if (title) {
  10617. title.className = 'text-sm font-bold text-rose-300';
  10618. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10619. }
  10620. if (sub) {
  10621. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10622. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10623. }
  10624. if (latency) {
  10625. latency.className = 'text-base font-bold font-mono text-slate-500';
  10626. latency.innerText = '--';
  10627. }
  10628. }
  10629. const rawEl = document.getElementById('tools-port-raw');
  10630. 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'}`);
  10631. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10632. } catch (err) {
  10633. showToast('Probe Error', err.message, 'error');
  10634. } finally {
  10635. if (btn) btn.disabled = false;
  10636. if (spinner) spinner.classList.add('hidden');
  10637. }
  10638. }
  10639. // ==========================================
  10640. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10641. // ==========================================
  10642. async function loadDHCPClients(showToastMsg = false) {
  10643. try {
  10644. const [clientsRes, sumRes] = await Promise.all([
  10645. fetch(`${API_BASE}/dhcp/clients`),
  10646. fetch(`${API_BASE}/dhcp/clients/summary`)
  10647. ]);
  10648. if (clientsRes.ok) {
  10649. state.dhcpClients = await clientsRes.json();
  10650. }
  10651. if (sumRes.ok) {
  10652. state.dhcpSummary = await sumRes.json();
  10653. }
  10654. renderDHCPClients();
  10655. updateDHCPSummaryCards();
  10656. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10657. if (bDhcp && state.dhcpSummary) {
  10658. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10659. }
  10660. if (showToastMsg) {
  10661. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10662. }
  10663. } catch (err) {
  10664. console.error('Failed to load DHCP clients:', err);
  10665. if (showToastMsg) {
  10666. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10667. }
  10668. }
  10669. }
  10670. function updateDHCPSummaryCards() {
  10671. const sum = state.dhcpSummary || {
  10672. total_clients: (state.dhcpClients || []).length,
  10673. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10674. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10675. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10676. };
  10677. const totalEl = document.getElementById('dhcp-stat-total');
  10678. const boundEl = document.getElementById('dhcp-stat-bound');
  10679. const searchEl = document.getElementById('dhcp-stat-searching');
  10680. const disEl = document.getElementById('dhcp-stat-disabled');
  10681. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10682. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10683. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10684. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  10685. }
  10686. function renderDHCPClients() {
  10687. const tbody = document.getElementById('dhcp-clients-tbody');
  10688. const emptyState = document.getElementById('dhcp-clients-empty');
  10689. if (!tbody) return;
  10690. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  10691. if (clients.length === 0) {
  10692. tbody.innerHTML = '';
  10693. if (emptyState) emptyState.classList.remove('hidden');
  10694. return;
  10695. }
  10696. if (emptyState) emptyState.classList.add('hidden');
  10697. tbody.innerHTML = clients.map(c => {
  10698. let statusBadge = '';
  10699. if (!c.enabled) {
  10700. 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>';
  10701. } else if (c.status === 'bound') {
  10702. 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>';
  10703. } else if (c.status === 'searching') {
  10704. 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>';
  10705. } else if (c.status === 'stopped') {
  10706. 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>';
  10707. } else {
  10708. 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>`;
  10709. }
  10710. 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>';
  10711. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  10712. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  10713. 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>';
  10714. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  10715. // Option flags
  10716. const flags = [];
  10717. 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>');
  10718. 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>');
  10719. 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>');
  10720. 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>`);
  10721. return `
  10722. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  10723. <td class="py-3 px-4">
  10724. <div class="flex items-center gap-2">
  10725. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  10726. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  10727. </div>
  10728. </td>
  10729. <td class="py-3 px-4">${statusBadge}</td>
  10730. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  10731. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  10732. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  10733. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  10734. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  10735. <td class="py-3 px-4">
  10736. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  10737. </td>
  10738. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  10739. ${c.enabled ? `
  10740. <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>
  10741. <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>
  10742. <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>
  10743. ` : `
  10744. <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>
  10745. `}
  10746. <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>
  10747. <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>
  10748. </td>
  10749. </tr>
  10750. `;
  10751. }).join('');
  10752. }
  10753. function openDHCPClientModal(clientId = null) {
  10754. const modal = document.getElementById('modal-dhcp-client');
  10755. if (!modal) return;
  10756. const title = document.getElementById('modal-dhcp-title');
  10757. const idInput = document.getElementById('modal-dhcp-id');
  10758. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10759. const distInput = document.getElementById('modal-dhcp-distance');
  10760. const commentInput = document.getElementById('modal-dhcp-comment');
  10761. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  10762. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  10763. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  10764. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  10765. // Populate interfaces
  10766. if (ifaceSelect) {
  10767. let opts = '<option value="">Select interface...</option>';
  10768. const allIfaces = state.interfaces || [];
  10769. const allVlans = state.vlans || [];
  10770. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  10771. // Group 1: Physical & Bridge Interfaces
  10772. opts += '<optgroup label="Physical & Bridge Interfaces">';
  10773. allIfaces.forEach(i => {
  10774. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  10775. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  10776. });
  10777. opts += '</optgroup>';
  10778. // Group 2: VLAN Interfaces
  10779. if (allVlans.length > 0) {
  10780. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  10781. allVlans.forEach(v => {
  10782. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  10783. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  10784. });
  10785. opts += '</optgroup>';
  10786. }
  10787. ifaceSelect.innerHTML = opts;
  10788. }
  10789. if (clientId) {
  10790. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  10791. if (client) {
  10792. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  10793. if (idInput) idInput.value = client.id;
  10794. if (ifaceSelect) {
  10795. ifaceSelect.value = client.interface;
  10796. ifaceSelect.disabled = true; // interface cannot be changed on edit
  10797. }
  10798. if (distInput) distInput.value = client.default_route_distance || 1;
  10799. if (commentInput) commentInput.value = client.comment || '';
  10800. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  10801. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  10802. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  10803. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  10804. }
  10805. } else {
  10806. if (title) title.innerText = 'Add DHCP Client';
  10807. if (idInput) idInput.value = '';
  10808. if (ifaceSelect) {
  10809. ifaceSelect.value = '';
  10810. ifaceSelect.disabled = false;
  10811. }
  10812. if (distInput) distInput.value = 1;
  10813. if (commentInput) commentInput.value = '';
  10814. if (defRouteCheck) defRouteCheck.checked = true;
  10815. if (peerDnsCheck) peerDnsCheck.checked = true;
  10816. if (peerNtpCheck) peerNtpCheck.checked = true;
  10817. if (enabledCheck) enabledCheck.checked = true;
  10818. }
  10819. modal.classList.remove('hidden');
  10820. }
  10821. function openDHCPClientModalForIface(ifaceName) {
  10822. openDHCPClientModal();
  10823. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10824. if (ifaceSelect && ifaceName) {
  10825. ifaceSelect.value = ifaceName;
  10826. }
  10827. }
  10828. function closeDHCPClientModal() {
  10829. const modal = document.getElementById('modal-dhcp-client');
  10830. if (modal) modal.classList.add('hidden');
  10831. }
  10832. async function submitSaveDHCPClient(e) {
  10833. if (e) e.preventDefault();
  10834. const id = document.getElementById('modal-dhcp-id')?.value;
  10835. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  10836. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  10837. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  10838. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  10839. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  10840. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  10841. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  10842. if (!id && !iface) {
  10843. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  10844. return;
  10845. }
  10846. try {
  10847. let res;
  10848. if (id) {
  10849. // PUT update
  10850. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10851. method: 'PUT',
  10852. headers: { 'Content-Type': 'application/json' },
  10853. body: JSON.stringify({
  10854. enabled,
  10855. add_default_route: defRoute,
  10856. default_route_distance: distance,
  10857. use_peer_dns: peerDns,
  10858. use_peer_ntp: peerNtp,
  10859. comment
  10860. })
  10861. });
  10862. } else {
  10863. // POST create
  10864. res = await fetch(`${API_BASE}/dhcp/clients`, {
  10865. method: 'POST',
  10866. headers: { 'Content-Type': 'application/json' },
  10867. body: JSON.stringify({
  10868. interface: iface,
  10869. enabled,
  10870. add_default_route: defRoute,
  10871. default_route_distance: distance,
  10872. use_peer_dns: peerDns,
  10873. use_peer_ntp: peerNtp,
  10874. comment
  10875. })
  10876. });
  10877. }
  10878. const data = await res.json();
  10879. if (!res.ok) {
  10880. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  10881. return;
  10882. }
  10883. closeDHCPClientModal();
  10884. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  10885. await loadDHCPClients();
  10886. fetchData(); // refresh interfaces list with new lease/status
  10887. } catch (err) {
  10888. showToast('Error', err.message, 'error');
  10889. }
  10890. }
  10891. async function toggleDHCPClientState(id, enabled) {
  10892. try {
  10893. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  10894. method: 'POST',
  10895. headers: { 'Content-Type': 'application/json' },
  10896. body: JSON.stringify({ enabled })
  10897. });
  10898. const data = await res.json();
  10899. if (!res.ok) {
  10900. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  10901. return;
  10902. }
  10903. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  10904. await loadDHCPClients();
  10905. fetchData();
  10906. } catch (err) {
  10907. showToast('Error', err.message, 'error');
  10908. }
  10909. }
  10910. async function renewDHCPClient(id) {
  10911. try {
  10912. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  10913. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  10914. method: 'POST'
  10915. });
  10916. const data = await res.json();
  10917. if (!res.ok) {
  10918. showToast('Error', data.error || 'Failed to renew lease', 'error');
  10919. return;
  10920. }
  10921. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  10922. setTimeout(() => {
  10923. loadDHCPClients();
  10924. fetchData();
  10925. }, 1500);
  10926. } catch (err) {
  10927. showToast('Error', err.message, 'error');
  10928. }
  10929. }
  10930. async function releaseDHCPClient(id) {
  10931. try {
  10932. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  10933. method: 'POST'
  10934. });
  10935. const data = await res.json();
  10936. if (!res.ok) {
  10937. showToast('Error', data.error || 'Failed to release lease', 'error');
  10938. return;
  10939. }
  10940. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  10941. await loadDHCPClients();
  10942. fetchData();
  10943. } catch (err) {
  10944. showToast('Error', err.message, 'error');
  10945. }
  10946. }
  10947. async function deleteDHCPClient(id, ifaceName) {
  10948. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  10949. return;
  10950. }
  10951. try {
  10952. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10953. method: 'DELETE'
  10954. });
  10955. const data = await res.json();
  10956. if (!res.ok) {
  10957. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  10958. return;
  10959. }
  10960. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  10961. await loadDHCPClients();
  10962. fetchData();
  10963. } catch (err) {
  10964. showToast('Error', err.message, 'error');
  10965. }
  10966. }
  10967. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  10968. function initTableSorting() {
  10969. document.querySelectorAll('table').forEach(setupSortableTable);
  10970. }
  10971. function setupSortableTable(table) {
  10972. const thead = table.querySelector('thead');
  10973. const tbody = table.querySelector('tbody');
  10974. if (!thead || !tbody) return;
  10975. const headerRows = thead.querySelectorAll('tr');
  10976. if (headerRows.length === 0) return;
  10977. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  10978. ths.forEach((th, colIdx) => {
  10979. if (th._sortBound) return;
  10980. th._sortBound = true;
  10981. const rawText = th.innerText.trim().toLowerCase();
  10982. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  10983. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  10984. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  10985. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  10986. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  10987. return;
  10988. }
  10989. th.classList.add('table-sortable', 'group');
  10990. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  10991. let icon = th.querySelector('.table-sort-icon');
  10992. if (!icon) {
  10993. icon = document.createElement('span');
  10994. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10995. icon.innerHTML = '⇅';
  10996. th.appendChild(icon);
  10997. }
  10998. th.addEventListener('click', (e) => {
  10999. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  11000. handleHeaderClick(table, th, colIdx);
  11001. });
  11002. });
  11003. if (!tbody._sortObserved) {
  11004. tbody._sortObserved = true;
  11005. let sortDebounceTimer = null;
  11006. const observer = new MutationObserver((mutations) => {
  11007. if (tbody._isSorting) return;
  11008. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  11009. if (!hasChildChanges) return;
  11010. clearTimeout(sortDebounceTimer);
  11011. sortDebounceTimer = setTimeout(() => {
  11012. if (tbody._isSorting) return;
  11013. if (table._activeSort && table._activeSort.dir !== 'none') {
  11014. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  11015. } else {
  11016. tagOriginalRowOrder(tbody);
  11017. }
  11018. }, 10);
  11019. });
  11020. observer.observe(tbody, { childList: true });
  11021. }
  11022. tagOriginalRowOrder(tbody);
  11023. }
  11024. function tagOriginalRowOrder(tbody) {
  11025. let idx = 0;
  11026. Array.from(tbody.children).forEach(tr => {
  11027. if (!tr.querySelector('td[colspan]')) {
  11028. if (!tr.hasAttribute('data-orig-idx')) {
  11029. tr.setAttribute('data-orig-idx', idx++);
  11030. }
  11031. }
  11032. });
  11033. }
  11034. function handleHeaderClick(table, th, colIdx) {
  11035. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  11036. let newDir = 'asc';
  11037. if (currentSort.colIdx === colIdx) {
  11038. if (currentSort.dir === 'asc') newDir = 'desc';
  11039. else if (currentSort.dir === 'desc') newDir = 'none';
  11040. else newDir = 'asc';
  11041. } else {
  11042. newDir = 'asc';
  11043. }
  11044. table._activeSort = { colIdx, dir: newDir };
  11045. updateHeaderIcons(table, colIdx, newDir);
  11046. applyTableSort(table, colIdx, newDir, true);
  11047. }
  11048. function updateHeaderIcons(table, activeColIdx, dir) {
  11049. const thead = table.querySelector('thead');
  11050. if (!thead) return;
  11051. const ths = thead.querySelectorAll('th');
  11052. ths.forEach((th, idx) => {
  11053. const icon = th.querySelector('.table-sort-icon');
  11054. if (!icon) return;
  11055. if (idx === activeColIdx && dir !== 'none') {
  11056. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  11057. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  11058. th.classList.add('table-sorted-active');
  11059. } else {
  11060. icon.innerHTML = '⇅';
  11061. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  11062. th.classList.remove('table-sorted-active');
  11063. }
  11064. });
  11065. }
  11066. function applyTableSort(table, colIdx, dir, userInitiated) {
  11067. const tbody = table.querySelector('tbody');
  11068. if (!tbody || tbody.children.length <= 1) return;
  11069. tbody._isSorting = true;
  11070. tagOriginalRowOrder(tbody);
  11071. // Group parent rows and any attached drawer/sub-rows
  11072. const groups = [];
  11073. let currentGroup = null;
  11074. Array.from(tbody.children).forEach(tr => {
  11075. if (tr.querySelector('td[colspan]')) {
  11076. if (currentGroup) {
  11077. currentGroup.subRows.push(tr);
  11078. } else {
  11079. groups.push({ mainRow: tr, subRows: [] });
  11080. }
  11081. } else {
  11082. currentGroup = { mainRow: tr, subRows: [] };
  11083. groups.push(currentGroup);
  11084. }
  11085. });
  11086. if (dir === 'none') {
  11087. groups.sort((a, b) => {
  11088. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11089. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11090. return idxA - idxB;
  11091. });
  11092. } else {
  11093. groups.sort((a, b) => {
  11094. const cellA = a.mainRow.children[colIdx];
  11095. const cellB = b.mainRow.children[colIdx];
  11096. const res = compareTableCells(cellA, cellB);
  11097. return dir === 'asc' ? res : -res;
  11098. });
  11099. }
  11100. // Re-append rows in sorted order
  11101. groups.forEach(g => {
  11102. tbody.appendChild(g.mainRow);
  11103. g.subRows.forEach(sub => tbody.appendChild(sub));
  11104. });
  11105. tbody._isSorting = false;
  11106. }
  11107. function getCellRawText(cell) {
  11108. if (!cell) return '';
  11109. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  11110. const input = cell.querySelector('input, select');
  11111. if (input) {
  11112. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  11113. return input.value;
  11114. }
  11115. return cell.innerText.trim();
  11116. }
  11117. function parseTrafficToNumber(str) {
  11118. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  11119. if (!m) return null;
  11120. const num = parseFloat(m[1].replace(/,/g, ''));
  11121. if (isNaN(num)) return null;
  11122. const unit = m[2].toUpperCase();
  11123. let mult = 1;
  11124. if (unit.startsWith('K')) mult = 1024;
  11125. else if (unit.startsWith('M')) mult = 1024 * 1024;
  11126. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  11127. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  11128. return num * mult;
  11129. }
  11130. function parseIpToNumber(str) {
  11131. const clean = str.replace(/^[!~]/, '').trim();
  11132. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  11133. if (!m) return null;
  11134. const o1 = parseInt(m[1], 10);
  11135. const o2 = parseInt(m[2], 10);
  11136. const o3 = parseInt(m[3], 10);
  11137. const o4 = parseInt(m[4], 10);
  11138. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  11139. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  11140. }
  11141. function parseCompoundPackets(str) {
  11142. const m = str.match(/^([\d,]+)p/);
  11143. if (!m) return null;
  11144. return parseInt(m[1].replace(/,/g, ''), 10);
  11145. }
  11146. function compareTableCells(cellA, cellB) {
  11147. const a = getCellRawText(cellA);
  11148. const b = getCellRawText(cellB);
  11149. if (a === '' && b !== '') return 1;
  11150. if (b === '' && a !== '') return -1;
  11151. if (a === b) return 0;
  11152. // 1. IP Addresses / CIDR
  11153. const ipA = parseIpToNumber(a);
  11154. const ipB = parseIpToNumber(b);
  11155. if (ipA !== null && ipB !== null) return ipA - ipB;
  11156. // 2. Packet counts (e.g. "1,250p / 45 KB")
  11157. const pktA = parseCompoundPackets(a);
  11158. const pktB = parseCompoundPackets(b);
  11159. if (pktA !== null && pktB !== null) return pktA - pktB;
  11160. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  11161. const trafA = parseTrafficToNumber(a);
  11162. const trafB = parseTrafficToNumber(b);
  11163. if (trafA !== null && trafB !== null) return trafA - trafB;
  11164. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  11165. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11166. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11167. const numA = Number(cleanNumA);
  11168. const numB = Number(cleanNumB);
  11169. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  11170. return numA - numB;
  11171. }
  11172. // 5. Natural case-insensitive string compare
  11173. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  11174. }
  11175. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  11176. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  11177. const docTableObserver = new MutationObserver((mutations) => {
  11178. let needsInit = false;
  11179. for (const m of mutations) {
  11180. for (const node of m.addedNodes) {
  11181. if (node.nodeType === 1) {
  11182. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  11183. needsInit = true;
  11184. break;
  11185. }
  11186. }
  11187. }
  11188. if (needsInit) break;
  11189. }
  11190. if (needsInit) {
  11191. initTableSorting();
  11192. }
  11193. });
  11194. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  11195. }