app.js 514 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null
  48. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. initTableSorting();
  64. fetchData();
  65. // Live polling every 2.5 seconds
  66. setInterval(() => {
  67. if (state.isPolling) {
  68. fetchData(false);
  69. }
  70. }, 2500);
  71. });
  72. // Navigation Handler
  73. function navigate(tabName) {
  74. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  75. navigate('bgp');
  76. return;
  77. }
  78. if (tabName === 'vlans') {
  79. navigate('interfaces');
  80. return;
  81. }
  82. state.activeTab = tabName;
  83. window.location.hash = tabName;
  84. // Update nav links styling
  85. document.querySelectorAll('.nav-link').forEach(link => {
  86. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  87. });
  88. const activeNav = document.getElementById(`nav-${tabName}`);
  89. if (activeNav) {
  90. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  91. }
  92. // Update page headers
  93. const titles = {
  94. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  95. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  96. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  97. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  98. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  99. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  100. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  101. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  103. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  104. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 dynamic routing engine' },
  105. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  106. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  107. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  108. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  109. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  110. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  111. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  112. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  113. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  114. };
  115. const header = titles[tabName] || titles.dashboard;
  116. const pTitle = document.getElementById('page-title');
  117. if (pTitle) pTitle.innerText = header.title;
  118. const pSub = document.getElementById('page-subtitle');
  119. if (pSub) pSub.innerText = header.sub;
  120. // Toggle sections dynamically for all section elements
  121. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  122. if (el.id === `section-${tabName}`) {
  123. el.classList.remove('hidden');
  124. } else {
  125. el.classList.add('hidden');
  126. }
  127. });
  128. if (tabName === 'bridge') loadBridge();
  129. if (tabName === 'firewall') loadFirewall();
  130. if (tabName === 'routes') loadRoutes();
  131. if (tabName === 'bgp') {
  132. loadDynamicRouting();
  133. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  134. }
  135. if (tabName === 'ospf') {
  136. loadDynamicRouting();
  137. switchOspfTab(state.activeOspfTab || 'instances');
  138. }
  139. if (tabName === 'routing-filters') loadDynamicRouting();
  140. if (tabName === 'dynamic-routing') loadDynamicRouting();
  141. if (tabName === 'ppp') loadPPP();
  142. if (tabName === 'eoip') loadEoIP();
  143. if (tabName === 'persistence') loadDebianConfig();
  144. if (tabName === 'pppoe') loadPPPoE();
  145. if (tabName === 'wireguard') loadWireGuard();
  146. if (tabName === 'ipsec') loadIPSec();
  147. if (tabName === 'l2tp') loadL2TP();
  148. if (tabName === 'pptp') loadPPTP();
  149. if (tabName === 'tools') loadToolsView();
  150. if (tabName === 'dhcp-client') loadDHCPClients();
  151. setTimeout(initTableSorting, 50);
  152. }
  153. // Fetch all core system, network and VPN telemetry
  154. async function fetchData(isManual = false) {
  155. const spinner = document.getElementById('refresh-spinner');
  156. if (isManual && spinner) spinner.classList.add('animate-spin');
  157. try {
  158. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  159. fetch(`${API_BASE}/system/status`),
  160. fetch(`${API_BASE}/interfaces`),
  161. fetch(`${API_BASE}/vlans`),
  162. fetch(`${API_BASE}/vpn/status`),
  163. fetch(`${API_BASE}/firewall/summary`),
  164. fetch(`${API_BASE}/routing/dynamic/summary`),
  165. fetch(`${API_BASE}/bridge/summary`),
  166. fetch(`${API_BASE}/dhcp/clients/summary`),
  167. fetch(`${API_BASE}/dhcp/clients`)
  168. ]);
  169. if (dhcpSumRes && dhcpSumRes.ok) {
  170. state.dhcpSummary = await dhcpSumRes.json();
  171. const bDhcp = document.getElementById('badge-dhcp-client-count');
  172. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  173. }
  174. if (dhcpClientsRes && dhcpClientsRes.ok) {
  175. state.dhcpClients = await dhcpClientsRes.json();
  176. }
  177. if (brSummaryRes.ok) {
  178. state.bridgeSummary = await brSummaryRes.json();
  179. const bBridge = document.getElementById('badge-bridge-count');
  180. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  181. const sBr = document.getElementById('bridge-stat-bridges');
  182. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  183. const sPorts = document.getElementById('bridge-stat-ports');
  184. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  185. const sHosts = document.getElementById('bridge-stat-hosts');
  186. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  187. }
  188. if (statusRes.ok) state.systemStatus = await statusRes.json();
  189. if (ifacesRes.ok) {
  190. const ifacesData = await ifacesRes.json();
  191. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  192. state.interfaces = rawIfaces.filter(i => {
  193. if (!i.name) return false;
  194. if (i.name.startsWith('ep_')) return false;
  195. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  196. });
  197. try { populateToolsInterfaces(); } catch (e) {}
  198. }
  199. if (vlansRes.ok) {
  200. const vlansData = await vlansRes.json();
  201. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  202. }
  203. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  204. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  205. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  206. updateSystemMetrics();
  207. updateBadges();
  208. if (state.activeTab === 'dashboard') renderDashboard();
  209. if (state.activeTab === 'interfaces') renderInterfacesList();
  210. if (state.activeTab === 'vlans') renderVlansList();
  211. if (state.activeTab === 'firewall') loadFirewall(false);
  212. if (state.activeTab === 'routes') loadRoutes(false);
  213. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  214. if (state.activeTab === 'ppp') loadPPP(false);
  215. if (state.activeTab === 'eoip') loadEoIP(false);
  216. if (state.activeTab === 'pppoe') loadPPPoE(false);
  217. if (state.activeTab === 'wireguard') loadWireGuard(false);
  218. if (state.activeTab === 'ipsec') loadIPSec(false);
  219. if (state.activeTab === 'l2tp') loadL2TP(false);
  220. if (state.activeTab === 'pptp') loadPPTP(false);
  221. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  222. } catch (err) {
  223. console.error('Failed to fetch router state:', err);
  224. } finally {
  225. if (isManual && spinner) {
  226. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  227. }
  228. }
  229. }
  230. // Update Top KPI and Sidebar Telemetry
  231. function updateSystemMetrics() {
  232. const s = state.systemStatus;
  233. const v = state.vpnStatus;
  234. if (!s) return;
  235. // Sidebar Host & Uptime
  236. const sideHost = document.getElementById('side-hostname');
  237. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  238. const sideUp = document.getElementById('side-uptime');
  239. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  240. const sideGw = document.getElementById('side-gateway-ip');
  241. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  242. // Compute CPU Metrics
  243. let cpuPct = 0;
  244. if (s.cpu_pct !== undefined) {
  245. cpuPct = s.cpu_pct;
  246. } else if (s.cpu_load && s.cpu_load.length > 0) {
  247. const cores = s.cpu_cores || 1;
  248. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  249. }
  250. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  251. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  252. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  253. // Sidebar CPU
  254. const sideCpuVal = document.getElementById('side-cpu-val');
  255. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  256. const sideCpuBar = document.getElementById('side-cpu-bar');
  257. if (sideCpuBar) {
  258. sideCpuBar.style.width = cpuWidth;
  259. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  260. }
  261. // Dashboard CPU Card
  262. const dashCpuVal = document.getElementById('dash-cpu-val');
  263. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  264. const dashCpuBar = document.getElementById('dash-cpu-bar');
  265. if (dashCpuBar) {
  266. dashCpuBar.style.width = cpuWidth;
  267. if (cpuPct > 85) {
  268. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  269. } else if (cpuPct > 65) {
  270. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  271. } else {
  272. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  273. }
  274. }
  275. const dashCpuCores = document.getElementById('dash-cpu-cores');
  276. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  277. const dashCpuLoad = document.getElementById('dash-cpu-load');
  278. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  279. const dashCpuStatus = document.getElementById('dash-cpu-status');
  280. if (dashCpuStatus) {
  281. if (cpuPct > 85) {
  282. dashCpuStatus.innerText = 'High';
  283. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  284. } else if (cpuPct > 65) {
  285. dashCpuStatus.innerText = 'Heavy';
  286. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  287. } else {
  288. dashCpuStatus.innerText = 'Normal';
  289. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  290. }
  291. }
  292. // Compute RAM Metrics
  293. const memPct = Math.round(s.mem_usage_pct || 0);
  294. const memPctStr = `${memPct}%`;
  295. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  296. const usedMB = s.mem_used_mb || 0;
  297. const totalMB = s.mem_total_mb || 0;
  298. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  299. function fmtMemMB(mb) {
  300. if (mb >= 1024) {
  301. return `${(mb / 1024).toFixed(1)} GB`;
  302. }
  303. return `${mb} MB`;
  304. }
  305. // Sidebar RAM
  306. const sideRamVal = document.getElementById('side-ram-val');
  307. if (sideRamVal) sideRamVal.innerText = memPctStr;
  308. const sideRamBar = document.getElementById('side-ram-bar');
  309. if (sideRamBar) sideRamBar.style.width = memWidth;
  310. // Dashboard RAM Card
  311. const dashRamVal = document.getElementById('dash-ram-val');
  312. if (dashRamVal) dashRamVal.innerText = memPctStr;
  313. const dashRamBar = document.getElementById('dash-ram-bar');
  314. if (dashRamBar) {
  315. dashRamBar.style.width = memWidth;
  316. if (memPct > 85) {
  317. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  318. } else if (memPct > 70) {
  319. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  320. } else {
  321. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  322. }
  323. }
  324. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  325. if (dashRamUsedTotal) {
  326. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  327. }
  328. const dashRamFree = document.getElementById('dash-ram-free');
  329. if (dashRamFree) {
  330. dashRamFree.innerText = fmtMemMB(freeMB);
  331. }
  332. const dashRamStatus = document.getElementById('dash-ram-status');
  333. if (dashRamStatus) {
  334. if (memPct > 85) {
  335. dashRamStatus.innerText = 'High';
  336. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  337. } else {
  338. dashRamStatus.innerText = 'Active';
  339. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  340. }
  341. }
  342. // Legacy Dashboard Stats (Safe checks)
  343. const elIfacesUp = document.getElementById('stat-ifaces-up');
  344. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  345. const elIfacesTot = document.getElementById('stat-ifaces-total');
  346. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  347. const elIfacesDown = document.getElementById('stat-ifaces-down');
  348. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  349. const elVlans = document.getElementById('stat-vlans-count');
  350. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  351. // VPN Status Indicators
  352. if (v) {
  353. const totalActive = v.total_active_tunnels || 0;
  354. const statVpnActive = document.getElementById('stat-vpn-active');
  355. if (statVpnActive) statVpnActive.innerText = totalActive;
  356. const tunnelsDot = document.getElementById('tunnels-dot');
  357. const tunnelsLabel = document.getElementById('tunnels-label');
  358. if (tunnelsDot && tunnelsLabel) {
  359. if (totalActive > 0) {
  360. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  361. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  362. } else {
  363. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  364. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  365. }
  366. }
  367. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  368. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  369. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  370. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  371. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  372. }
  373. // Total Live Bandwidth Rate
  374. let totalRx = 0;
  375. let totalTx = 0;
  376. (state.interfaces || []).forEach(i => {
  377. if (i.rate) {
  378. totalRx += i.rate.rx_bytes_sec || 0;
  379. totalTx += i.rate.tx_bytes_sec || 0;
  380. }
  381. });
  382. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  383. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  384. }
  385. function setDotBadge(id, active) {
  386. const el = document.getElementById(id);
  387. if (!el) return;
  388. if (active) {
  389. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  390. } else {
  391. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  392. }
  393. }
  394. function updateBadges() {
  395. const bIfaces = document.getElementById('badge-ifaces-count');
  396. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  397. const bVlans = document.getElementById('badge-vlans-count');
  398. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  399. if (state.fwSummary) {
  400. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  401. const badgeFw = document.getElementById('badge-firewall-count');
  402. if (badgeFw) badgeFw.innerText = totalFwRules;
  403. }
  404. if (state.vpnStatus) {
  405. const v = state.vpnStatus;
  406. const bEoIP = document.getElementById('badge-eoip-count');
  407. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  408. const bPPPSess = document.getElementById('badge-ppp-sessions');
  409. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  410. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  411. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  412. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  413. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  414. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  415. }
  416. if (state.dynSummary) {
  417. const d = state.dynSummary;
  418. setDotBadge('badge-bgp-dot', d.bgp_running);
  419. setDotBadge('badge-ospf-dot', d.ospf_running);
  420. const bBgp = document.getElementById('badge-bgp-count');
  421. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  422. const bOspf = document.getElementById('badge-ospf-count');
  423. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  424. const bFilters = document.getElementById('badge-filters-count');
  425. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  426. }
  427. }
  428. // Render Dashboard View
  429. function renderDashboard() {
  430. const matrix = document.getElementById('port-matrix');
  431. matrix.innerHTML = '';
  432. (state.interfaces || []).forEach(iface => {
  433. const isUp = iface.state === 'UP';
  434. const isVlan = iface.is_vlan;
  435. const portCard = document.createElement('div');
  436. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  437. isUp
  438. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  439. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  440. }`;
  441. portCard.onclick = () => openIfaceModal(iface.name);
  442. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  443. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  444. portCard.innerHTML = `
  445. <div class="flex items-center justify-between mb-2">
  446. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  447. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  448. </div>
  449. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  450. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  451. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  452. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  453. </div>
  454. `;
  455. matrix.appendChild(portCard);
  456. });
  457. const ifaceTbody = document.getElementById('quick-interfaces-table');
  458. if (ifaceTbody) {
  459. ifaceTbody.innerHTML = '';
  460. (state.interfaces || []).forEach(i => {
  461. const isUp = i.state === 'UP';
  462. const tr = document.createElement('tr');
  463. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  464. tr.onclick = () => openIfaceModal(i.name);
  465. const rxStr = i.rate?.rx_human || '0 B/s';
  466. const txStr = i.rate?.tx_human || '0 B/s';
  467. tr.innerHTML = `
  468. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  469. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  470. <span>${i.name}</span>
  471. </td>
  472. <td class="py-2.5 text-slate-300 font-sans">
  473. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  474. </td>
  475. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  476. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  477. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  478. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  479. </td>
  480. <td class="py-2.5 text-right font-sans font-semibold">
  481. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  482. </td>
  483. `;
  484. ifaceTbody.appendChild(tr);
  485. });
  486. }
  487. const vlanTbody = document.getElementById('quick-vlans-table');
  488. if (vlanTbody) {
  489. vlanTbody.innerHTML = '';
  490. }
  491. }
  492. // Expand / Collapse Handlers
  493. function toggleExpand(parentName) {
  494. if (state.expandedParents.has(parentName)) {
  495. state.expandedParents.delete(parentName);
  496. } else {
  497. state.expandedParents.add(parentName);
  498. }
  499. renderInterfacesList();
  500. }
  501. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  502. function supportsVLAN(iface) {
  503. if (!iface) return false;
  504. if (iface.is_vlan) return false;
  505. const name = (iface.name || '').toLowerCase();
  506. const type = (iface.type || '').toLowerCase();
  507. const role = (iface.role || '').toLowerCase();
  508. // Exclude loopback
  509. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  510. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  511. if (type === 'wireguard' || name.startsWith('wg')) return false;
  512. // Exclude PPP / PPPoE
  513. if (type === 'ppp' || name.startsWith('ppp')) return false;
  514. // Exclude other Layer 3 tunnels and dummy devices
  515. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  516. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  517. return false;
  518. }
  519. // If name already contains a dot, it's already a sub-interface
  520. if (name.includes('.')) return false;
  521. return true;
  522. }
  523. // Expand / Collapse Handlers
  524. function toggleExpand(parentName) {
  525. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  526. if (childVlans.length === 0) {
  527. // Cannot expand an interface with no VLANs
  528. state.expandedParents.delete(parentName);
  529. return;
  530. }
  531. if (state.expandedParents.has(parentName)) {
  532. state.expandedParents.delete(parentName);
  533. } else {
  534. state.expandedParents.add(parentName);
  535. }
  536. renderInterfacesList();
  537. }
  538. function expandAllIfaces(expand) {
  539. if (expand) {
  540. (state.interfaces || []).forEach(i => {
  541. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  542. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  543. });
  544. } else {
  545. state.expandedParents.clear();
  546. }
  547. renderInterfacesList();
  548. }
  549. // Filter and Render Hierarchical Interfaces List
  550. function filterIfaces(filter) {
  551. state.ifaceFilter = filter || 'all';
  552. renderInterfacesList();
  553. }
  554. function renderInterfacesList() {
  555. const tbody = document.getElementById('interfaces-tree-tbody');
  556. const emptyState = document.getElementById('interfaces-empty-state');
  557. const summary = document.getElementById('ifaces-list-summary');
  558. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  559. tbody.innerHTML = '';
  560. const allIfaces = state.interfaces || [];
  561. const allVlans = state.vlans || [];
  562. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  563. const filteredParents = parentIfaces.filter(parent => {
  564. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  565. if (query) {
  566. const matchName = parent.name.toLowerCase().includes(query);
  567. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  568. const matchRole = (parent.role || '').toLowerCase().includes(query);
  569. const matchType = (parent.type || '').toLowerCase().includes(query);
  570. const matchVlan = childVlans.some(v =>
  571. v.name.toLowerCase().includes(query) ||
  572. String(v.vlan_id).includes(query) ||
  573. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  574. (v.description || '').toLowerCase().includes(query)
  575. );
  576. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  577. }
  578. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  579. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  580. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  581. return true;
  582. });
  583. if (summary) {
  584. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  585. }
  586. if (filteredParents.length === 0) {
  587. emptyState?.classList.remove('hidden');
  588. return;
  589. }
  590. emptyState?.classList.add('hidden');
  591. filteredParents.forEach(parent => {
  592. const isUp = parent.state === 'UP';
  593. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  594. const hasVlans = childVlans.length > 0;
  595. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  596. const canHaveVlan = supportsVLAN(parent);
  597. const parentRow = document.createElement('tr');
  598. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  599. parentRow.innerHTML = `
  600. <td class="py-3 px-3 text-center">
  601. ${hasVlans ? `
  602. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  603. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  604. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  605. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  606. </svg>
  607. </button>
  608. ` : `
  609. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  610. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  611. </div>
  612. `}
  613. </td>
  614. <td class="py-3 px-4">
  615. <div class="flex items-center space-x-2.5">
  616. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  617. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  618. </div>
  619. <div>
  620. <div class="flex items-center gap-2">
  621. ${hasVlans ? `
  622. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  623. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  624. ` : `
  625. <span class="font-bold text-white text-sm">${parent.name}</span>
  626. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  627. `}
  628. </div>
  629. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  630. </div>
  631. </div>
  632. </td>
  633. <td class="py-3 px-4 font-sans">
  634. <div class="flex items-center gap-1.5">
  635. <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
  636. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  637. </div>
  638. </td>
  639. <td class="py-3 px-4">
  640. ${parent.ipv4 && parent.ipv4.length > 0
  641. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  642. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  643. }
  644. ${(() => {
  645. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  646. if (!c) return '';
  647. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  648. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  649. })()}
  650. </td>
  651. <td class="py-3 px-4 text-slate-400 text-[11px]">
  652. <div>${parent.mac || 'N/A'}</div>
  653. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  654. </td>
  655. <td class="py-3 px-4 text-[11px]">
  656. <div class="flex items-center space-x-2">
  657. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  658. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  659. </div>
  660. </td>
  661. <td class="py-3 px-4 font-sans">
  662. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  663. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  664. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  665. }" title="Click to toggle link status">
  666. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  667. <span>${parent.state}</span>
  668. </button>
  669. </td>
  670. <td class="py-3 px-4 text-right space-x-2 font-sans">
  671. ${(() => {
  672. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  673. if (c) {
  674. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  675. }
  676. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  677. })()}
  678. ${canHaveVlan ? `
  679. <button onclick="openVlanModal('${parent.name}')"
  680. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  681. + Add VLAN
  682. </button>
  683. ` : ''}
  684. <button onclick="openIfaceModal('${parent.name}')"
  685. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  686. Configure
  687. </button>
  688. </td>
  689. `;
  690. tbody.appendChild(parentRow);
  691. if (isExpanded) {
  692. const drawerRow = document.createElement('tr');
  693. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  694. const drawerCell = document.createElement('td');
  695. drawerCell.colSpan = 8;
  696. drawerCell.className = 'p-0';
  697. drawerCell.innerHTML = `
  698. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  699. <div class="flex items-center justify-between mb-3">
  700. <div class="flex items-center space-x-3">
  701. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  702. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  703. </span>
  704. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  705. ${childVlans.length} Attached
  706. </span>
  707. </div>
  708. <button onclick="openVlanModal('${parent.name}')"
  709. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  710. <span>+ Create VLAN on ${parent.name}</span>
  711. </button>
  712. </div>
  713. ${childVlans.length === 0 ? `
  714. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  715. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  716. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  717. <span>+ Create Your First VLAN on ${parent.name}</span>
  718. </button>
  719. </div>
  720. ` : `
  721. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  722. <table class="w-full text-left text-xs font-mono">
  723. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  724. <tr>
  725. <th class="py-2.5 px-4">VLAN ID</th>
  726. <th class="py-2.5 px-4">Interface Device</th>
  727. <th class="py-2.5 px-4">Subnet Gateway</th>
  728. <th class="py-2.5 px-4">Role / Alias</th>
  729. <th class="py-2.5 px-4">MTU</th>
  730. <th class="py-2.5 px-4">Throughput</th>
  731. <th class="py-2.5 px-4">Status</th>
  732. <th class="py-2.5 px-4 text-right">Actions</th>
  733. </tr>
  734. </thead>
  735. <tbody class="divide-y divide-slate-800/70">
  736. ${childVlans.map(v => {
  737. const isVlanUp = v.state === 'UP';
  738. return `
  739. <tr class="hover:bg-slate-800/40 transition">
  740. <td class="py-2.5 px-4">
  741. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  742. VLAN ${v.vlan_id}
  743. </span>
  744. </td>
  745. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  746. <span class="text-cyan-500">└─</span>
  747. <span>${v.name}</span>
  748. </td>
  749. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  750. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  751. ${(() => {
  752. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  753. if (!c) return '';
  754. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  755. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  756. })()}
  757. </td>
  758. <td class="py-2.5 px-4 font-sans text-slate-300">
  759. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  760. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  761. </td>
  762. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  763. <td class="py-2.5 px-4 text-[11px]">
  764. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  765. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  766. </td>
  767. <td class="py-2.5 px-4 font-sans">
  768. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  769. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  770. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  771. }">
  772. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  773. <span>${v.state}</span>
  774. </button>
  775. </td>
  776. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (c) {
  780. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  781. }
  782. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  783. })()}
  784. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  785. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  786. </td>
  787. </tr>
  788. `;
  789. }).join('')}
  790. </tbody>
  791. </table>
  792. </div>
  793. `}
  794. </div>
  795. `;
  796. drawerRow.appendChild(drawerCell);
  797. tbody.appendChild(drawerRow);
  798. }
  799. });
  800. }
  801. // Render VLANs Dedicated View
  802. function renderVlansList() {
  803. const tbody = document.getElementById('vlans-table-body');
  804. if (!tbody) return;
  805. const emptyState = document.getElementById('vlans-empty-state');
  806. const countBadge = document.getElementById('vlans-table-count');
  807. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  808. tbody.innerHTML = '';
  809. const allVlans = state.vlans || [];
  810. if (countBadge) countBadge.innerText = allVlans.length;
  811. const filtered = allVlans.filter(v => {
  812. if (!query) return true;
  813. return v.name.toLowerCase().includes(query) ||
  814. String(v.vlan_id).includes(query) ||
  815. (v.description || '').toLowerCase().includes(query) ||
  816. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  817. });
  818. if (allVlans.length === 0) {
  819. emptyState.classList.remove('hidden');
  820. return;
  821. }
  822. emptyState.classList.add('hidden');
  823. filtered.forEach(v => {
  824. const isUp = v.state === 'UP';
  825. const tr = document.createElement('tr');
  826. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  827. tr.innerHTML = `
  828. <td class="py-3 px-4">
  829. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  830. VLAN ${v.vlan_id}
  831. </span>
  832. </td>
  833. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  834. <td class="py-3 px-4 text-slate-300">
  835. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  836. </td>
  837. <td class="py-3 px-4 text-emerald-400 font-medium">
  838. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  839. </td>
  840. <td class="py-3 px-4 text-slate-300 font-sans">
  841. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  842. </td>
  843. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  844. <td class="py-3 px-4 font-sans">
  845. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  846. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  847. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  848. }">
  849. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  850. <span>${v.state}</span>
  851. </button>
  852. </td>
  853. <td class="py-3 px-4 text-right space-x-2 font-sans">
  854. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  855. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  856. </td>
  857. `;
  858. tbody.appendChild(tr);
  859. });
  860. }
  861. // Toggle interface UP / DOWN
  862. async function toggleInterfaceState(name, newState) {
  863. try {
  864. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  865. method: 'POST',
  866. headers: { 'Content-Type': 'application/json' },
  867. body: JSON.stringify({ state: newState })
  868. });
  869. const data = await res.json();
  870. if (res.ok) {
  871. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  872. fetchData(false);
  873. } else {
  874. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  875. }
  876. } catch (err) {
  877. showToast('Error', err.message, 'error');
  878. }
  879. }
  880. // ---------------- MikroTik Flag & Utilities ----------------
  881. function renderMikroTikFlag(running, disabled) {
  882. if (running) {
  883. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  884. }
  885. if (disabled) {
  886. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  887. }
  888. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  889. }
  890. function copyToClipboard(text, label = 'Text') {
  891. navigator.clipboard.writeText(text).then(() => {
  892. showToast('Copied', `${label} copied to clipboard`, 'success');
  893. }).catch(() => {
  894. prompt('Copy value:', text);
  895. });
  896. }
  897. // ======================== PPPoE Multi-Instance ========================
  898. async function loadPPPoE(populateInputs = true) {
  899. try {
  900. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  901. const list = await res.json();
  902. state.pppoeList = Array.isArray(list) ? list : [];
  903. const badge = document.getElementById('pppoe-count-badge');
  904. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  905. const tbody = document.getElementById('pppoe-table-body');
  906. const empty = document.getElementById('pppoe-empty');
  907. if (!tbody) return;
  908. tbody.innerHTML = '';
  909. if (state.pppoeList.length === 0) {
  910. if (empty) empty.classList.remove('hidden');
  911. } else {
  912. if (empty) empty.classList.add('hidden');
  913. state.pppoeList.forEach(inst => {
  914. const tr = document.createElement('tr');
  915. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  916. tr.innerHTML = `
  917. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  918. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  919. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
  920. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  921. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  922. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  923. <td class="py-2.5 px-3 text-center">
  924. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  925. ${inst.default_route ? 'Yes' : 'No'}
  926. </span>
  927. </td>
  928. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  929. ${inst.running ? `
  930. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  931. ` : `
  932. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  933. `}
  934. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  935. ${inst.disabled ? 'Enable' : 'Disable'}
  936. </button>
  937. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  938. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  939. </td>
  940. `;
  941. tbody.appendChild(tr);
  942. });
  943. }
  944. } catch (err) {
  945. console.error('Failed to load PPPoE:', err);
  946. }
  947. }
  948. function openAddPPPoEModal() {
  949. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  950. document.getElementById('pppoe-modal-edit-orig').value = '';
  951. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  952. document.getElementById('pppoe-modal-name').readOnly = false;
  953. document.getElementById('pppoe-modal-user').value = '';
  954. document.getElementById('pppoe-modal-pass').value = '';
  955. document.getElementById('pppoe-modal-service').value = '';
  956. document.getElementById('pppoe-modal-mtu').value = '1492';
  957. document.getElementById('pppoe-modal-defroute').checked = true;
  958. document.getElementById('pppoe-modal-reconnect').checked = true;
  959. document.getElementById('pppoe-modal-disabled').checked = false;
  960. // Populate interfaces
  961. const sel = document.getElementById('pppoe-modal-iface');
  962. sel.innerHTML = '';
  963. (state.interfaces || []).forEach(i => {
  964. if (i.name === 'lo') return;
  965. const opt = document.createElement('option');
  966. opt.value = i.name;
  967. opt.innerText = `${i.name} (${i.role || i.type})`;
  968. sel.appendChild(opt);
  969. });
  970. document.getElementById('pppoe-modal').classList.remove('hidden');
  971. }
  972. function openEditPPPoEModal(name) {
  973. const inst = (state.pppoeList || []).find(i => i.name === name);
  974. if (!inst) return;
  975. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  976. document.getElementById('pppoe-modal-edit-orig').value = name;
  977. document.getElementById('pppoe-modal-name').value = inst.name;
  978. document.getElementById('pppoe-modal-name').readOnly = true;
  979. document.getElementById('pppoe-modal-user').value = inst.username || '';
  980. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  981. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  982. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  983. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  984. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  985. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  986. const sel = document.getElementById('pppoe-modal-iface');
  987. sel.innerHTML = '';
  988. (state.interfaces || []).forEach(i => {
  989. if (i.name === 'lo') return;
  990. const opt = document.createElement('option');
  991. opt.value = i.name;
  992. opt.innerText = `${i.name} (${i.role || i.type})`;
  993. if (i.name === inst.interface) opt.selected = true;
  994. sel.appendChild(opt);
  995. });
  996. document.getElementById('pppoe-modal').classList.remove('hidden');
  997. }
  998. function closePPPoEModal() {
  999. document.getElementById('pppoe-modal').classList.add('hidden');
  1000. }
  1001. async function submitSavePPPoE(e) {
  1002. e.preventDefault();
  1003. const name = document.getElementById('pppoe-modal-name').value.trim();
  1004. const iface = document.getElementById('pppoe-modal-iface').value;
  1005. const user = document.getElementById('pppoe-modal-user').value.trim();
  1006. const pass = document.getElementById('pppoe-modal-pass').value;
  1007. const service = document.getElementById('pppoe-modal-service').value.trim();
  1008. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1009. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1010. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1011. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1012. try {
  1013. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1014. method: 'POST',
  1015. headers: { 'Content-Type': 'application/json' },
  1016. body: JSON.stringify({
  1017. name,
  1018. interface: iface,
  1019. username: user,
  1020. password: pass,
  1021. service_name: service,
  1022. mtu,
  1023. default_route: defRoute,
  1024. auto_reconnect: reconnect,
  1025. disabled
  1026. })
  1027. });
  1028. if (res.ok) {
  1029. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1030. closePPPoEModal();
  1031. loadPPPoE(false);
  1032. fetchData(false);
  1033. } else {
  1034. const err = await res.json();
  1035. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1036. }
  1037. } catch (err) {
  1038. showToast('Error', err.message, 'error');
  1039. }
  1040. }
  1041. async function connectPPPoEInstance(name) {
  1042. try {
  1043. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1044. if (res.ok) {
  1045. showToast('Connecting', `Dialing ${name}...`, 'info');
  1046. setTimeout(() => loadPPPoE(false), 2000);
  1047. }
  1048. } catch (err) {
  1049. showToast('Error', err.message, 'error');
  1050. }
  1051. }
  1052. async function disconnectPPPoEInstance(name) {
  1053. try {
  1054. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1055. if (res.ok) {
  1056. showToast('Disconnected', `${name} session terminated`, 'info');
  1057. setTimeout(() => loadPPPoE(false), 1000);
  1058. }
  1059. } catch (err) {
  1060. showToast('Error', err.message, 'error');
  1061. }
  1062. }
  1063. async function togglePPPoEState(name, enable) {
  1064. try {
  1065. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1066. method: 'POST',
  1067. headers: { 'Content-Type': 'application/json' },
  1068. body: JSON.stringify({ enabled: enable })
  1069. });
  1070. if (res.ok) {
  1071. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1072. loadPPPoE(false);
  1073. }
  1074. } catch (err) {
  1075. showToast('Error', err.message, 'error');
  1076. }
  1077. }
  1078. async function deletePPPoEInstance(name) {
  1079. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1080. try {
  1081. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1082. if (res.ok) {
  1083. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1084. loadPPPoE(false);
  1085. fetchData(false);
  1086. }
  1087. } catch (err) {
  1088. showToast('Error', err.message, 'error');
  1089. }
  1090. }
  1091. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1092. state.wgSubTab = 'ifaces';
  1093. function switchWGSubTab(tab) {
  1094. state.wgSubTab = tab;
  1095. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1096. const peersPanel = document.getElementById('wg-subtab-peers');
  1097. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1098. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1099. if (tab === 'ifaces') {
  1100. ifacesPanel?.classList.remove('hidden');
  1101. peersPanel?.classList.add('hidden');
  1102. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1103. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1104. } else {
  1105. ifacesPanel?.classList.add('hidden');
  1106. peersPanel?.classList.remove('hidden');
  1107. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1108. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1109. renderWGPeers();
  1110. }
  1111. }
  1112. async function loadWireGuard(populateInputs = true) {
  1113. try {
  1114. const [ifacesRes, peersRes] = await Promise.all([
  1115. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1116. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1117. ]);
  1118. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1119. const peers = peersRes.ok ? await peersRes.json() : [];
  1120. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1121. state.wgPeers = Array.isArray(peers) ? peers : [];
  1122. // Badges
  1123. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1124. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1125. const peersCountBadge = document.getElementById('wg-peers-count');
  1126. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1127. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1128. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1129. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1130. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1131. // Render Interfaces
  1132. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1133. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1134. if (ifacesTbody) {
  1135. ifacesTbody.innerHTML = '';
  1136. if (state.wgInterfaces.length === 0) {
  1137. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1138. } else {
  1139. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1140. state.wgInterfaces.forEach(iface => {
  1141. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1142. const tr = document.createElement('tr');
  1143. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1144. tr.innerHTML = `
  1145. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1146. <td class="py-2.5 px-3">
  1147. <div class="flex items-center gap-1.5">
  1148. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1149. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1150. </div>
  1151. </td>
  1152. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1153. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1154. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1155. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1156. ${(iface.public_key || '').substring(0, 10)}... 📋
  1157. </span>
  1158. </td>
  1159. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1160. <td class="py-2.5 px-3 text-center">
  1161. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1162. </td>
  1163. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1164. ${iface.running ? `
  1165. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1166. ` : `
  1167. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1168. `}
  1169. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1170. ${iface.disabled ? 'Enable' : 'Disable'}
  1171. </button>
  1172. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1173. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1174. </td>
  1175. `;
  1176. ifacesTbody.appendChild(tr);
  1177. });
  1178. }
  1179. }
  1180. // Populate filter dropdown in peers tab
  1181. const filterSel = document.getElementById('wg-peers-filter-iface');
  1182. if (filterSel) {
  1183. const currentVal = filterSel.value;
  1184. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1185. state.wgInterfaces.forEach(i => {
  1186. const opt = document.createElement('option');
  1187. opt.value = i.name;
  1188. opt.innerText = i.name;
  1189. if (i.name === currentVal) opt.selected = true;
  1190. filterSel.appendChild(opt);
  1191. });
  1192. }
  1193. renderWGPeers();
  1194. } catch (err) {
  1195. console.error('Failed to load WireGuard:', err);
  1196. }
  1197. }
  1198. function renderWGPeers() {
  1199. const filterSel = document.getElementById('wg-peers-filter-iface');
  1200. const selectedIface = filterSel ? filterSel.value : '';
  1201. const tbody = document.getElementById('wg-peers-table-body');
  1202. const empty = document.getElementById('wg-peers-empty');
  1203. if (!tbody) return;
  1204. tbody.innerHTML = '';
  1205. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1206. if (filtered.length === 0) {
  1207. if (empty) empty.classList.remove('hidden');
  1208. } else {
  1209. if (empty) empty.classList.add('hidden');
  1210. filtered.forEach(p => {
  1211. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1212. const tr = document.createElement('tr');
  1213. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1214. tr.innerHTML = `
  1215. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1216. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1217. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1218. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1219. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1220. ${(p.public_key || '').substring(0, 10)}... 📋
  1221. </span>
  1222. </td>
  1223. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1224. <td class="py-2.5 px-3 text-slate-400 font-mono">${p.endpoint_address ? (p.endpoint_address + (p.endpoint_port ? ':' + p.endpoint_port : '')) : '--'}</td>
  1225. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1226. <td class="py-2.5 px-3 font-mono text-[11px]">
  1227. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1228. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1229. </td>
  1230. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1231. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1232. ${p.disabled ? 'Enable' : 'Disable'}
  1233. </button>
  1234. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1235. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1236. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1237. </td>
  1238. `;
  1239. tbody.appendChild(tr);
  1240. });
  1241. }
  1242. }
  1243. function openAddWGInterfaceModal() {
  1244. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1245. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1246. const nameEl = document.getElementById('wg-iface-modal-name');
  1247. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1248. nameEl.readOnly = false;
  1249. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1250. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1251. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1252. document.getElementById('wg-iface-modal-comment').value = '';
  1253. document.getElementById('wg-iface-modal-pubkey').value = '';
  1254. document.getElementById('wg-iface-modal-privkey').value = '';
  1255. document.getElementById('wg-iface-modal-disabled').checked = false;
  1256. generateWGInterfaceKeys();
  1257. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1258. }
  1259. function openEditWGInterfaceModal(name) {
  1260. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1261. if (!iface) return;
  1262. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1263. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1264. const nameEl = document.getElementById('wg-iface-modal-name');
  1265. nameEl.value = iface.name;
  1266. nameEl.readOnly = false; // ALLOW RENAMING
  1267. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1268. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1269. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1270. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1271. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1272. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1273. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1274. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1275. }
  1276. function closeAddWGInterfaceModal() {
  1277. document.getElementById('wg-iface-modal').classList.add('hidden');
  1278. }
  1279. async function generateWGInterfaceKeys() {
  1280. try {
  1281. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1282. const keys = await res.json();
  1283. if (res.ok) {
  1284. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1285. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1286. }
  1287. } catch (err) {
  1288. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1289. }
  1290. }
  1291. async function onWGInterfacePrivKeyInput() {
  1292. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1293. if (!privKey) return;
  1294. try {
  1295. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1296. method: 'POST',
  1297. headers: { 'Content-Type': 'application/json' },
  1298. body: JSON.stringify({ private_key: privKey })
  1299. });
  1300. if (res.ok) {
  1301. const data = await res.json();
  1302. if (data.public_key) {
  1303. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1304. }
  1305. }
  1306. } catch (err) {
  1307. // Ignore while typing
  1308. }
  1309. }
  1310. function toggleWGPrivKeyVisibility() {
  1311. const el = document.getElementById('wg-iface-modal-privkey');
  1312. const btn = document.getElementById('btn-toggle-wg-privkey');
  1313. if (el.type === 'password') {
  1314. el.type = 'text';
  1315. btn.innerText = '🙈 Hide';
  1316. } else {
  1317. el.type = 'password';
  1318. btn.innerText = '👁️ Show';
  1319. }
  1320. }
  1321. function copyWGInterfacePubKey() {
  1322. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1323. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1324. }
  1325. async function submitSaveWGInterface(e) {
  1326. e.preventDefault();
  1327. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1328. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1329. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1330. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1331. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1332. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1333. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1334. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1335. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1336. try {
  1337. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1338. method: 'POST',
  1339. headers: { 'Content-Type': 'application/json' },
  1340. body: JSON.stringify({
  1341. orig_name: origName,
  1342. name,
  1343. listen_port: port,
  1344. address: addr,
  1345. mtu,
  1346. comment,
  1347. public_key: pub,
  1348. private_key: priv,
  1349. disabled
  1350. })
  1351. });
  1352. const data = await res.json();
  1353. if (res.ok) {
  1354. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1355. closeAddWGInterfaceModal();
  1356. loadWireGuard(false);
  1357. fetchData(false);
  1358. } else {
  1359. showToast('Error', data.error || 'Failed to save interface', 'error');
  1360. }
  1361. } catch (err) {
  1362. showToast('Error', err.message, 'error');
  1363. }
  1364. }
  1365. async function startWGInterface(name) {
  1366. try {
  1367. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1368. if (res.ok) {
  1369. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1370. loadWireGuard(false);
  1371. fetchData(false);
  1372. }
  1373. } catch (err) {
  1374. showToast('Error', err.message, 'error');
  1375. }
  1376. }
  1377. async function stopWGInterface(name) {
  1378. try {
  1379. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1380. if (res.ok) {
  1381. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1382. loadWireGuard(false);
  1383. fetchData(false);
  1384. }
  1385. } catch (err) {
  1386. showToast('Error', err.message, 'error');
  1387. }
  1388. }
  1389. async function toggleWGInterfaceState(name, enable) {
  1390. try {
  1391. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1392. method: 'POST',
  1393. headers: { 'Content-Type': 'application/json' },
  1394. body: JSON.stringify({ enabled: enable })
  1395. });
  1396. if (res.ok) {
  1397. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1398. loadWireGuard(false);
  1399. fetchData(false);
  1400. }
  1401. } catch (err) {
  1402. showToast('Error', err.message, 'error');
  1403. }
  1404. }
  1405. async function deleteWGInterface(name) {
  1406. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1409. if (res.ok) {
  1410. showToast('Deleted', `Interface ${name} removed`, 'success');
  1411. loadWireGuard(false);
  1412. fetchData(false);
  1413. }
  1414. } catch (err) {
  1415. showToast('Error', err.message, 'error');
  1416. }
  1417. }
  1418. function populateWGPeerIfaceSelect(selectedIface = '') {
  1419. const sel = document.getElementById('wg-peer-modal-iface');
  1420. if (!sel) return;
  1421. sel.innerHTML = '';
  1422. (state.wgInterfaces || []).forEach(i => {
  1423. const opt = document.createElement('option');
  1424. opt.value = i.name;
  1425. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1426. if (i.name === selectedIface) opt.selected = true;
  1427. sel.appendChild(opt);
  1428. });
  1429. }
  1430. function openAddWGPeerModal() {
  1431. if ((state.wgInterfaces || []).length === 0) {
  1432. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1433. openAddWGInterfaceModal();
  1434. return;
  1435. }
  1436. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1437. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1438. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1439. populateWGPeerIfaceSelect();
  1440. document.getElementById('wg-peer-modal-name').value = '';
  1441. document.getElementById('wg-peer-modal-pubkey').value = '';
  1442. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1443. document.getElementById('wg-peer-modal-endpoint').value = '';
  1444. document.getElementById('wg-peer-modal-port').value = '';
  1445. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1446. document.getElementById('wg-peer-modal-preshared').value = '';
  1447. document.getElementById('wg-peer-modal-disabled').checked = false;
  1448. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1449. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1450. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1451. }
  1452. function openEditWGPeerModal(ifaceName, pubKey) {
  1453. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1454. if (!peer) {
  1455. showToast('Not Found', 'Peer not found', 'warning');
  1456. return;
  1457. }
  1458. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1459. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1460. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1461. populateWGPeerIfaceSelect(peer.interface);
  1462. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1463. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1464. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1465. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1466. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1467. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1468. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1469. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1470. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1471. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1472. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1473. }
  1474. function closeAddWGPeerModal() {
  1475. document.getElementById('wg-peer-modal').classList.add('hidden');
  1476. }
  1477. async function generatePeerKeypairHelper() {
  1478. try {
  1479. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1480. const keys = await res.json();
  1481. if (res.ok) {
  1482. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1483. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1484. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1485. checkWGPeerKeyValidity();
  1486. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1487. }
  1488. } catch (err) {
  1489. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1490. }
  1491. }
  1492. function copyGeneratedPeerPrivKey() {
  1493. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1494. if (priv) copyToClipboard(priv, 'Client Private Key');
  1495. }
  1496. async function generatePeerPSK() {
  1497. try {
  1498. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1499. const keys = await res.json();
  1500. if (res.ok && keys.private_key) {
  1501. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1502. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1503. }
  1504. } catch (err) {
  1505. showToast('Error', err.message, 'error');
  1506. }
  1507. }
  1508. function checkWGPeerKeyValidity() {
  1509. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1510. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1511. const warningEl = document.getElementById('wg-peer-key-warning');
  1512. if (!warningEl) return;
  1513. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1514. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1515. warningEl.classList.remove('hidden');
  1516. } else {
  1517. warningEl.classList.add('hidden');
  1518. }
  1519. }
  1520. async function submitSaveWGPeer(e) {
  1521. e.preventDefault();
  1522. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1523. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1524. const iface = document.getElementById('wg-peer-modal-iface').value;
  1525. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1526. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1527. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1528. .split(',')
  1529. .map(s => s.trim())
  1530. .filter(s => s.length > 0);
  1531. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1532. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1533. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1534. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1535. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1536. // Validation
  1537. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1538. if (targetIface && targetIface.public_key === pub) {
  1539. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1540. return;
  1541. }
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1544. method: 'POST',
  1545. headers: { 'Content-Type': 'application/json' },
  1546. body: JSON.stringify({
  1547. orig_interface: origIface,
  1548. orig_public_key: origPubKey,
  1549. interface: iface,
  1550. name,
  1551. public_key: pub,
  1552. allowed_ips: allowed,
  1553. endpoint_address: epHost,
  1554. endpoint_port: epPort,
  1555. persistent_keepalive: keepalive,
  1556. preshared_key: psk,
  1557. disabled
  1558. })
  1559. });
  1560. const data = await res.json();
  1561. if (res.ok) {
  1562. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1563. closeAddWGPeerModal();
  1564. loadWireGuard(false);
  1565. } else {
  1566. showToast('Error', data.error || 'Failed to save peer', 'error');
  1567. }
  1568. } catch (err) {
  1569. showToast('Error', err.message, 'error');
  1570. }
  1571. }
  1572. async function toggleWGPeerState(iface, pubkey, enable) {
  1573. try {
  1574. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1575. method: 'POST',
  1576. headers: { 'Content-Type': 'application/json' },
  1577. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1578. });
  1579. const data = await res.json();
  1580. if (res.ok) {
  1581. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1582. loadWireGuard(false);
  1583. } else {
  1584. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1585. }
  1586. } catch (err) {
  1587. showToast('Error', err.message, 'error');
  1588. }
  1589. }
  1590. async function deleteWGPeer(iface, pubkey) {
  1591. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1592. try {
  1593. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1594. method: 'POST',
  1595. headers: { 'Content-Type': 'application/json' },
  1596. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1597. });
  1598. const data = await res.json();
  1599. if (res.ok) {
  1600. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1601. loadWireGuard(false);
  1602. } else {
  1603. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1604. }
  1605. } catch (err) {
  1606. showToast('Error', err.message, 'error');
  1607. }
  1608. }
  1609. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1610. function switchIpsecModalTab(tab) {
  1611. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1612. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1613. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1614. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1615. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1616. if (tab === 'p1') {
  1617. if (p1Tab) {
  1618. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  1619. }
  1620. if (p2Tab) {
  1621. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1622. }
  1623. if (p1Content) p1Content.classList.remove('hidden');
  1624. if (p2Content) p2Content.classList.add('hidden');
  1625. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1626. } else {
  1627. if (p1Tab) {
  1628. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1629. }
  1630. if (p2Tab) {
  1631. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  1632. }
  1633. if (p1Content) p1Content.classList.add('hidden');
  1634. if (p2Content) p2Content.classList.remove('hidden');
  1635. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1636. }
  1637. }
  1638. function toggleIpsecPhaseStep() {
  1639. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1640. if (p1Content && !p1Content.classList.contains('hidden')) {
  1641. switchIpsecModalTab('p2');
  1642. } else {
  1643. switchIpsecModalTab('p1');
  1644. }
  1645. }
  1646. function toggleIpsecPskVisibility() {
  1647. const pskInput = document.getElementById('ipsec-modal-psk');
  1648. if (!pskInput) return;
  1649. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1650. }
  1651. function addIpsecLocalSubnet(val = '') {
  1652. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1653. if (!container) return;
  1654. const row = document.createElement('div');
  1655. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1656. row.innerHTML = `
  1657. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  1658. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  1659. `;
  1660. container.appendChild(row);
  1661. }
  1662. function addIpsecRemoteSubnet(val = '') {
  1663. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1664. if (!container) return;
  1665. const row = document.createElement('div');
  1666. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1667. row.innerHTML = `
  1668. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  1669. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  1670. `;
  1671. container.appendChild(row);
  1672. }
  1673. function updateIpsecEspProposalFromPFS(val) {
  1674. const prop = document.getElementById('ipsec-modal-espprop');
  1675. if (!prop) return;
  1676. if (val === 'none') {
  1677. prop.value = 'aes256-sha256,aes128-sha256,default';
  1678. } else {
  1679. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1680. }
  1681. }
  1682. function updateIpsecIkeProposalFromDH(dh) {
  1683. const el = document.getElementById('ipsec-modal-ikeprop');
  1684. if (el) {
  1685. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1686. }
  1687. }
  1688. function safeSetVal(id, val) {
  1689. const el = document.getElementById(id);
  1690. if (el) el.value = val;
  1691. }
  1692. function safeSetChecked(id, val) {
  1693. const el = document.getElementById(id);
  1694. if (el) el.checked = !!val;
  1695. }
  1696. function safeGetVal(id, def = '') {
  1697. const el = document.getElementById(id);
  1698. return el ? el.value : def;
  1699. }
  1700. async function loadIPSec(populateInputs = true) {
  1701. try {
  1702. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1703. const list = await res.json();
  1704. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1705. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1706. const badge = document.getElementById('ipsec-sas-badge');
  1707. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1708. const tbody = document.getElementById('ipsec-table-body');
  1709. const empty = document.getElementById('ipsec-empty');
  1710. if (!tbody) return;
  1711. tbody.innerHTML = '';
  1712. if (state.ipsecTunnels.length === 0) {
  1713. if (empty) empty.classList.remove('hidden');
  1714. } else {
  1715. if (empty) empty.classList.add('hidden');
  1716. state.ipsecTunnels.forEach(c => {
  1717. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1718. const tr = document.createElement('tr');
  1719. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1720. // Local subnets tags
  1721. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1722. 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('');
  1723. // Remote subnets tags
  1724. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1725. 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('');
  1726. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1727. const p2Name = c.phase2_name || `${c.name}_p2`;
  1728. tr.innerHTML = `
  1729. <td class="py-2.5 px-3 text-center">
  1730. ${isEstablished ? `
  1731. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1732. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1733. <span>UP</span>
  1734. </span>
  1735. ` : (c.disabled ? `
  1736. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1737. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1738. <span>DOWN</span>
  1739. </span>
  1740. ` : `
  1741. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1742. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1743. <span>IDLE</span>
  1744. </span>
  1745. `)}
  1746. </td>
  1747. <td class="py-2.5 px-4 font-bold text-white">
  1748. <div class="flex items-center gap-2">
  1749. <span class="text-amber-400">🛡</span>
  1750. <div>
  1751. <div>${escapeHtml(c.name)}</div>
  1752. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1753. </div>
  1754. </div>
  1755. </td>
  1756. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1757. <td class="py-2.5 px-4 font-sans">
  1758. <div class="flex items-center gap-1.5">
  1759. <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>
  1760. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1761. </div>
  1762. </td>
  1763. <td class="py-2.5 px-4">
  1764. <div class="space-y-1">
  1765. <div class="flex items-center flex-wrap gap-1">
  1766. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1767. ${localBadges}
  1768. </div>
  1769. <div class="flex items-center flex-wrap gap-1">
  1770. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1771. ${remoteBadges}
  1772. </div>
  1773. </div>
  1774. </td>
  1775. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1776. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1777. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1778. </div>
  1779. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1780. </td>
  1781. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1782. ${isEstablished ? `
  1783. <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>
  1784. ` : `
  1785. <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>
  1786. `}
  1787. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1788. ${c.disabled ? 'Enable' : 'Disable'}
  1789. </button>
  1790. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1791. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1792. </td>
  1793. `;
  1794. tbody.appendChild(tr);
  1795. });
  1796. }
  1797. } catch (err) {
  1798. console.error('Failed to load IPSec:', err);
  1799. }
  1800. }
  1801. function openAddIPSecModal() {
  1802. const modal = document.getElementById('ipsec-modal');
  1803. if (!modal) return;
  1804. const title = document.getElementById('ipsec-modal-title');
  1805. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1806. // Phase 1 Fields
  1807. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1808. const nameEl = document.getElementById('ipsec-modal-name');
  1809. if (nameEl) nameEl.readOnly = false;
  1810. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1811. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1812. safeSetVal('ipsec-modal-remotegw', '');
  1813. safeSetVal('ipsec-modal-localaddrs', '');
  1814. safeSetVal('ipsec-modal-comments', '');
  1815. safeSetVal('ipsec-modal-psk', '');
  1816. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1817. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1818. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1819. safeSetVal('ipsec-modal-localid', '');
  1820. safeSetVal('ipsec-modal-remoteid', '');
  1821. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1822. // Phase 2 Fields
  1823. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1824. safeSetVal('ipsec-modal-espkeylife', '28800');
  1825. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1826. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1827. safeSetChecked('ipsec-modal-autostart', true);
  1828. safeSetChecked('ipsec-modal-disabled', false);
  1829. // Clear & Populate default dynamic subnets
  1830. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1831. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1832. if (localContainer) {
  1833. localContainer.innerHTML = '';
  1834. addIpsecLocalSubnet('192.168.10.0/24');
  1835. }
  1836. if (remoteContainer) {
  1837. remoteContainer.innerHTML = '';
  1838. addIpsecRemoteSubnet('192.168.20.0/24');
  1839. }
  1840. switchIpsecModalTab('p1');
  1841. modal.classList.remove('hidden');
  1842. }
  1843. function openEditIPSecModal(name) {
  1844. const modal = document.getElementById('ipsec-modal');
  1845. if (!modal) return;
  1846. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1847. if (!conn) return;
  1848. const title = document.getElementById('ipsec-modal-title');
  1849. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1850. // Phase 1 Fields
  1851. safeSetVal('ipsec-modal-name', conn.name);
  1852. const nameEl = document.getElementById('ipsec-modal-name');
  1853. if (nameEl) nameEl.readOnly = true;
  1854. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1855. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1856. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1857. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1858. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1859. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1860. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1861. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1862. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1863. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1864. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1865. // Phase 2 Fields
  1866. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1867. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1868. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1869. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1870. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1871. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1872. // Populate dynamic subnets
  1873. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1874. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1875. if (localContainer) {
  1876. localContainer.innerHTML = '';
  1877. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1878. locals.forEach(s => addIpsecLocalSubnet(s));
  1879. }
  1880. if (remoteContainer) {
  1881. remoteContainer.innerHTML = '';
  1882. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1883. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1884. }
  1885. switchIpsecModalTab('p1');
  1886. modal.classList.remove('hidden');
  1887. }
  1888. function closeAddIPSecModal() {
  1889. const modal = document.getElementById('ipsec-modal');
  1890. if (modal) modal.classList.add('hidden');
  1891. }
  1892. async function submitSaveIPSec(e) {
  1893. if (e) e.preventDefault();
  1894. const name = safeGetVal('ipsec-modal-name').trim();
  1895. if (!name) {
  1896. showToast('Error', 'Tunnel name is required', 'error');
  1897. return;
  1898. }
  1899. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1900. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1901. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1902. const comments = safeGetVal('ipsec-modal-comments').trim();
  1903. const psk = safeGetVal('ipsec-modal-psk');
  1904. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1905. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1906. const localId = safeGetVal('ipsec-modal-localid').trim();
  1907. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1908. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1909. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1910. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1911. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1912. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1913. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1914. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1915. // Scrape dynamic local and remote subnets
  1916. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1917. const localSubnets = [];
  1918. localInputs.forEach(inp => {
  1919. const v = inp.value.trim();
  1920. if (v) localSubnets.push(v);
  1921. });
  1922. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1923. const remoteSubnets = [];
  1924. remoteInputs.forEach(inp => {
  1925. const v = inp.value.trim();
  1926. if (v) remoteSubnets.push(v);
  1927. });
  1928. try {
  1929. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1930. method: 'POST',
  1931. headers: { 'Content-Type': 'application/json' },
  1932. body: JSON.stringify({
  1933. name,
  1934. comment: comments,
  1935. ike_version: ikeVersion,
  1936. local_addrs: localAddrs,
  1937. remote_addrs: remotegw,
  1938. preshared_key: psk,
  1939. ike_proposals: ikeProposals,
  1940. ike_keylife: ikeKeylife,
  1941. local_id: localId,
  1942. remote_id: remoteId,
  1943. dpd: dpd,
  1944. phase2_name: phase2Name,
  1945. esp_proposals: espProposals,
  1946. esp_keylife: espKeylife,
  1947. pfs_group: pfsGroup,
  1948. pfs: pfsGroup !== 'none',
  1949. local_subnets: localSubnets,
  1950. remote_subnets: remoteSubnets,
  1951. local_subnet: localSubnets[0] || '0.0.0.0/0',
  1952. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  1953. auto_start: autostart,
  1954. disabled
  1955. })
  1956. });
  1957. if (res.ok) {
  1958. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  1959. closeAddIPSecModal();
  1960. loadIPSec(false);
  1961. } else {
  1962. const err = await res.json();
  1963. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  1964. }
  1965. } catch (err) {
  1966. showToast('Error', err.message, 'error');
  1967. }
  1968. }
  1969. async function startIPSecTunnel(name) {
  1970. try {
  1971. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1972. if (res.ok) {
  1973. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  1974. setTimeout(() => loadIPSec(false), 2000);
  1975. }
  1976. } catch (err) {
  1977. showToast('Error', err.message, 'error');
  1978. }
  1979. }
  1980. async function stopIPSecTunnel(name) {
  1981. try {
  1982. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1983. if (res.ok) {
  1984. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  1985. loadIPSec(false);
  1986. }
  1987. } catch (err) {
  1988. showToast('Error', err.message, 'error');
  1989. }
  1990. }
  1991. async function toggleIPSecState(name, enable) {
  1992. try {
  1993. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  1994. method: 'POST',
  1995. headers: { 'Content-Type': 'application/json' },
  1996. body: JSON.stringify({ enabled: enable })
  1997. });
  1998. if (res.ok) {
  1999. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2000. loadIPSec(false);
  2001. }
  2002. } catch (err) {
  2003. showToast('Error', err.message, 'error');
  2004. }
  2005. }
  2006. async function deleteIPSecConn(name) {
  2007. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2008. try {
  2009. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2010. if (res.ok) {
  2011. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2012. loadIPSec(false);
  2013. fetchData(false);
  2014. }
  2015. } catch (err) {
  2016. showToast('Error', err.message, 'error');
  2017. }
  2018. }
  2019. // ======================== L2TP Multi-Instance ========================
  2020. async function loadL2TP(populateInputs = true) {
  2021. try {
  2022. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2023. const list = await res.json();
  2024. state.l2tpList = Array.isArray(list) ? list : [];
  2025. const badge = document.getElementById('l2tp-count-badge');
  2026. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2027. const tbody = document.getElementById('l2tp-table-body');
  2028. const empty = document.getElementById('l2tp-empty');
  2029. if (!tbody) return;
  2030. tbody.innerHTML = '';
  2031. if (state.l2tpList.length === 0) {
  2032. if (empty) empty.classList.remove('hidden');
  2033. } else {
  2034. if (empty) empty.classList.add('hidden');
  2035. state.l2tpList.forEach(inst => {
  2036. const tr = document.createElement('tr');
  2037. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2038. tr.innerHTML = `
  2039. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2040. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  2041. <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
  2042. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  2043. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  2044. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  2045. <td class="py-2.5 px-3 text-center">
  2046. <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'}">
  2047. ${inst.default_route ? 'Yes' : 'No'}
  2048. </span>
  2049. </td>
  2050. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2051. ${inst.running ? `
  2052. <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2053. ` : `
  2054. <button onclick="connectL2TPInstance('${inst.name}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2055. `}
  2056. <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2057. ${inst.disabled ? 'Enable' : 'Disable'}
  2058. </button>
  2059. <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2060. <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2061. </td>
  2062. `;
  2063. tbody.appendChild(tr);
  2064. });
  2065. }
  2066. } catch (err) {
  2067. console.error('Failed to load L2TP:', err);
  2068. }
  2069. }
  2070. function openAddL2TPModal() {
  2071. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2072. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2073. document.getElementById('l2tp-modal-name').readOnly = false;
  2074. document.getElementById('l2tp-modal-server').value = '';
  2075. document.getElementById('l2tp-modal-user').value = '';
  2076. document.getElementById('l2tp-modal-pass').value = '';
  2077. document.getElementById('l2tp-modal-ipsec').value = '';
  2078. document.getElementById('l2tp-modal-defroute').checked = true;
  2079. document.getElementById('l2tp-modal-disabled').checked = false;
  2080. document.getElementById('l2tp-modal').classList.remove('hidden');
  2081. }
  2082. function openEditL2TPModal(name) {
  2083. const inst = (state.l2tpList || []).find(i => i.name === name);
  2084. if (!inst) return;
  2085. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2086. document.getElementById('l2tp-modal-name').value = inst.name;
  2087. document.getElementById('l2tp-modal-name').readOnly = true;
  2088. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2089. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2090. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2091. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2092. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2093. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2094. document.getElementById('l2tp-modal').classList.remove('hidden');
  2095. }
  2096. function closeL2TPModal() {
  2097. document.getElementById('l2tp-modal').classList.add('hidden');
  2098. }
  2099. async function submitSaveL2TP(e) {
  2100. e.preventDefault();
  2101. const name = document.getElementById('l2tp-modal-name').value.trim();
  2102. const server = document.getElementById('l2tp-modal-server').value.trim();
  2103. const user = document.getElementById('l2tp-modal-user').value.trim();
  2104. const pass = document.getElementById('l2tp-modal-pass').value;
  2105. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2106. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2107. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2108. try {
  2109. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2110. method: 'POST',
  2111. headers: { 'Content-Type': 'application/json' },
  2112. body: JSON.stringify({
  2113. name,
  2114. connect_to: server,
  2115. username: user,
  2116. password: pass,
  2117. ipsec_secret: ipsec,
  2118. default_route: defRoute,
  2119. disabled
  2120. })
  2121. });
  2122. if (res.ok) {
  2123. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2124. closeL2TPModal();
  2125. loadL2TP(false);
  2126. fetchData(false);
  2127. }
  2128. } catch (err) {
  2129. showToast('Error', err.message, 'error');
  2130. }
  2131. }
  2132. async function connectL2TPInstance(name) {
  2133. try {
  2134. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2135. if (res.ok) {
  2136. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2137. setTimeout(() => loadL2TP(false), 2000);
  2138. }
  2139. } catch (err) {
  2140. showToast('Error', err.message, 'error');
  2141. }
  2142. }
  2143. async function disconnectL2TPInstance(name) {
  2144. try {
  2145. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2146. if (res.ok) {
  2147. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2148. loadL2TP(false);
  2149. }
  2150. } catch (err) {
  2151. showToast('Error', err.message, 'error');
  2152. }
  2153. }
  2154. async function toggleL2TPState(name, enable) {
  2155. try {
  2156. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2157. method: 'POST',
  2158. headers: { 'Content-Type': 'application/json' },
  2159. body: JSON.stringify({ enabled: enable })
  2160. });
  2161. if (res.ok) {
  2162. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2163. loadL2TP(false);
  2164. }
  2165. } catch (err) {
  2166. showToast('Error', err.message, 'error');
  2167. }
  2168. }
  2169. async function deleteL2TPInstance(name) {
  2170. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2171. try {
  2172. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2173. if (res.ok) {
  2174. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2175. loadL2TP(false);
  2176. fetchData(false);
  2177. }
  2178. } catch (err) {
  2179. showToast('Error', err.message, 'error');
  2180. }
  2181. }
  2182. // ======================== PPTP Multi-Instance ========================
  2183. async function loadPPTP(populateInputs = true) {
  2184. try {
  2185. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2186. const list = await res.json();
  2187. state.pptpList = Array.isArray(list) ? list : [];
  2188. const badge = document.getElementById('pptp-count-badge');
  2189. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2190. const tbody = document.getElementById('pptp-table-body');
  2191. const empty = document.getElementById('pptp-empty');
  2192. if (!tbody) return;
  2193. tbody.innerHTML = '';
  2194. if (state.pptpList.length === 0) {
  2195. if (empty) empty.classList.remove('hidden');
  2196. } else {
  2197. if (empty) empty.classList.add('hidden');
  2198. state.pptpList.forEach(inst => {
  2199. const tr = document.createElement('tr');
  2200. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2201. tr.innerHTML = `
  2202. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2203. <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
  2204. <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
  2205. <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
  2206. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
  2207. <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
  2208. <td class="py-2.5 px-3 text-center">
  2209. <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'}">
  2210. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2211. </span>
  2212. </td>
  2213. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2214. ${inst.running ? `
  2215. <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2216. ` : `
  2217. <button onclick="connectPPTPInstance('${inst.name}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2218. `}
  2219. <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2220. ${inst.disabled ? 'Enable' : 'Disable'}
  2221. </button>
  2222. <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2223. <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2224. </td>
  2225. `;
  2226. tbody.appendChild(tr);
  2227. });
  2228. }
  2229. } catch (err) {
  2230. console.error('Failed to load PPTP:', err);
  2231. }
  2232. }
  2233. function openAddPPTPModal() {
  2234. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2235. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2236. document.getElementById('pptp-modal-name').readOnly = false;
  2237. document.getElementById('pptp-modal-server').value = '';
  2238. document.getElementById('pptp-modal-user').value = '';
  2239. document.getElementById('pptp-modal-pass').value = '';
  2240. document.getElementById('pptp-modal-mppe').checked = true;
  2241. document.getElementById('pptp-modal-defroute').checked = true;
  2242. document.getElementById('pptp-modal-disabled').checked = false;
  2243. document.getElementById('pptp-modal').classList.remove('hidden');
  2244. }
  2245. function openEditPPTPModal(name) {
  2246. const inst = (state.pptpList || []).find(i => i.name === name);
  2247. if (!inst) return;
  2248. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2249. document.getElementById('pptp-modal-name').value = inst.name;
  2250. document.getElementById('pptp-modal-name').readOnly = true;
  2251. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2252. document.getElementById('pptp-modal-user').value = inst.username || '';
  2253. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2254. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2255. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2256. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2257. document.getElementById('pptp-modal').classList.remove('hidden');
  2258. }
  2259. function closePPTPModal() {
  2260. document.getElementById('pptp-modal').classList.add('hidden');
  2261. }
  2262. async function submitSavePPTP(e) {
  2263. e.preventDefault();
  2264. const name = document.getElementById('pptp-modal-name').value.trim();
  2265. const server = document.getElementById('pptp-modal-server').value.trim();
  2266. const user = document.getElementById('pptp-modal-user').value.trim();
  2267. const pass = document.getElementById('pptp-modal-pass').value;
  2268. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2269. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2270. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2271. try {
  2272. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2273. method: 'POST',
  2274. headers: { 'Content-Type': 'application/json' },
  2275. body: JSON.stringify({
  2276. name,
  2277. connect_to: server,
  2278. username: user,
  2279. password: pass,
  2280. require_mppe: mppe,
  2281. default_route: defRoute,
  2282. auto_reconnect: true,
  2283. disabled
  2284. })
  2285. });
  2286. if (res.ok) {
  2287. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2288. closePPTPModal();
  2289. loadPPTP(false);
  2290. fetchData(false);
  2291. }
  2292. } catch (err) {
  2293. showToast('Error', err.message, 'error');
  2294. }
  2295. }
  2296. async function connectPPTPInstance(name) {
  2297. try {
  2298. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2299. if (res.ok) {
  2300. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2301. setTimeout(() => loadPPTP(false), 2000);
  2302. }
  2303. } catch (err) {
  2304. showToast('Error', err.message, 'error');
  2305. }
  2306. }
  2307. async function disconnectPPTPInstance(name) {
  2308. try {
  2309. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2310. if (res.ok) {
  2311. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2312. loadPPTP(false);
  2313. }
  2314. } catch (err) {
  2315. showToast('Error', err.message, 'error');
  2316. }
  2317. }
  2318. async function togglePPTPState(name, enable) {
  2319. try {
  2320. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2321. method: 'POST',
  2322. headers: { 'Content-Type': 'application/json' },
  2323. body: JSON.stringify({ enabled: enable })
  2324. });
  2325. if (res.ok) {
  2326. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2327. loadPPTP(false);
  2328. }
  2329. } catch (err) {
  2330. showToast('Error', err.message, 'error');
  2331. }
  2332. }
  2333. async function deletePPTPInstance(name) {
  2334. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2335. try {
  2336. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2337. if (res.ok) {
  2338. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2339. loadPPTP(false);
  2340. fetchData(false);
  2341. }
  2342. } catch (err) {
  2343. showToast('Error', err.message, 'error');
  2344. }
  2345. }
  2346. // ---------------- Modal & Helper Functions ----------------
  2347. function openVlanModal(defaultParent = '') {
  2348. const select = document.getElementById('vlan-parent');
  2349. select.innerHTML = '';
  2350. const allIfaces = state.interfaces || [];
  2351. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2352. if (eligible.length === 0) {
  2353. const opt = document.createElement('option');
  2354. opt.value = '';
  2355. opt.innerText = 'No VLAN-capable interfaces available';
  2356. select.appendChild(opt);
  2357. } else {
  2358. eligible.forEach(i => {
  2359. const opt = document.createElement('option');
  2360. opt.value = i.name;
  2361. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2362. if (i.name === defaultParent) opt.selected = true;
  2363. select.appendChild(opt);
  2364. });
  2365. }
  2366. document.getElementById('vlan-id').value = '';
  2367. document.getElementById('vlan-name').value = '';
  2368. document.getElementById('vlan-ip').value = '';
  2369. document.getElementById('vlan-desc').value = '';
  2370. autoSuggestVlanName();
  2371. document.getElementById('vlan-modal').classList.remove('hidden');
  2372. }
  2373. function closeVlanModal() {
  2374. document.getElementById('vlan-modal').classList.add('hidden');
  2375. }
  2376. function autoSuggestVlanName() {
  2377. const parent = document.getElementById('vlan-parent').value;
  2378. if (!parent) return;
  2379. const id = document.getElementById('vlan-id').value;
  2380. const nameInput = document.getElementById('vlan-name');
  2381. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2382. }
  2383. function setSubnetPreset(cidr) {
  2384. const ipInput = document.getElementById('vlan-ip');
  2385. const id = document.getElementById('vlan-id').value || '10';
  2386. ipInput.value = `192.168.${id}.1${cidr}`;
  2387. }
  2388. async function submitCreateVlan(e) {
  2389. e.preventDefault();
  2390. const btn = document.getElementById('vlan-submit-btn');
  2391. btn.disabled = true;
  2392. btn.innerText = 'Creating...';
  2393. const parent = document.getElementById('vlan-parent').value;
  2394. if (!parent) {
  2395. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2396. btn.disabled = false;
  2397. btn.innerText = 'Create VLAN';
  2398. return;
  2399. }
  2400. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2401. const name = document.getElementById('vlan-name').value.trim();
  2402. const ip = document.getElementById('vlan-ip').value.trim();
  2403. const role = document.getElementById('vlan-role').value;
  2404. const desc = document.getElementById('vlan-desc').value.trim();
  2405. try {
  2406. const res = await fetch(`${API_BASE}/vlans`, {
  2407. method: 'POST',
  2408. headers: { 'Content-Type': 'application/json' },
  2409. body: JSON.stringify({
  2410. parent_name: parent,
  2411. vlan_id: id,
  2412. name: name,
  2413. ip_address: ip,
  2414. role: role,
  2415. description: desc,
  2416. mtu: 1500,
  2417. auto_up: true
  2418. })
  2419. });
  2420. const data = await res.json();
  2421. if (res.ok) {
  2422. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2423. state.expandedParents.add(parent);
  2424. closeVlanModal();
  2425. await fetchData(true);
  2426. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2427. } else {
  2428. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2429. }
  2430. } catch (err) {
  2431. showToast('Error', err.message, 'error');
  2432. } finally {
  2433. btn.disabled = false;
  2434. btn.innerText = 'Create VLAN';
  2435. }
  2436. }
  2437. async function confirmDeleteVlan(name) {
  2438. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2439. try {
  2440. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2441. if (res.ok) {
  2442. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2443. closeIfaceModal();
  2444. fetchData(true);
  2445. }
  2446. } catch (err) {
  2447. showToast('Error', err.message, 'error');
  2448. }
  2449. }
  2450. function openIfaceModal(name) {
  2451. const iface = (state.interfaces || []).find(i => i.name === name);
  2452. if (!iface) return;
  2453. state.currentModalIface = iface.name;
  2454. document.getElementById('modal-iface-name').innerText = iface.name;
  2455. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2456. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2457. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2458. document.getElementById('modal-iface-desc').value = iface.description || '';
  2459. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2460. if (iface.is_vlan) {
  2461. delBtn.classList.remove('hidden');
  2462. } else {
  2463. delBtn.classList.add('hidden');
  2464. }
  2465. renderModalIPs(iface);
  2466. document.getElementById('iface-modal').classList.remove('hidden');
  2467. }
  2468. function renderModalIPs(iface) {
  2469. const container = document.getElementById('modal-ip-list');
  2470. container.innerHTML = '';
  2471. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2472. if (addrs.length === 0) {
  2473. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2474. return;
  2475. }
  2476. addrs.forEach(addr => {
  2477. const row = document.createElement('div');
  2478. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2479. row.innerHTML = `
  2480. <span class="text-white">${addr}</span>
  2481. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2482. `;
  2483. container.appendChild(row);
  2484. });
  2485. }
  2486. function closeIfaceModal() {
  2487. document.getElementById('iface-modal').classList.add('hidden');
  2488. state.currentModalIface = null;
  2489. }
  2490. async function setIfaceState(name, newState) {
  2491. await toggleInterfaceState(name, newState);
  2492. const updated = (state.interfaces || []).find(i => i.name === name);
  2493. if (updated) openIfaceModal(name);
  2494. }
  2495. async function applyMTU() {
  2496. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2497. try {
  2498. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2499. method: 'POST',
  2500. headers: { 'Content-Type': 'application/json' },
  2501. body: JSON.stringify({ mtu })
  2502. });
  2503. if (res.ok) {
  2504. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2505. fetchData(false);
  2506. }
  2507. } catch (err) {
  2508. showToast('Error', err.message, 'error');
  2509. }
  2510. }
  2511. async function addInterfaceIP() {
  2512. const ip = document.getElementById('modal-new-ip').value.trim();
  2513. if (!ip) return;
  2514. try {
  2515. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2516. method: 'POST',
  2517. headers: { 'Content-Type': 'application/json' },
  2518. body: JSON.stringify({ ip })
  2519. });
  2520. if (res.ok) {
  2521. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2522. document.getElementById('modal-new-ip').value = '';
  2523. await fetchData(false);
  2524. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2525. if (iface) renderModalIPs(iface);
  2526. } else {
  2527. const err = await res.json();
  2528. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2529. }
  2530. } catch (err) {
  2531. showToast('Error', err.message, 'error');
  2532. }
  2533. }
  2534. async function removeInterfaceIP(ip) {
  2535. if (!confirm(`Remove IP ${ip}?`)) return;
  2536. try {
  2537. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2538. method: 'DELETE',
  2539. headers: { 'Content-Type': 'application/json' },
  2540. body: JSON.stringify({ ip })
  2541. });
  2542. if (res.ok) {
  2543. showToast('IP Removed', `Removed ${ip}`, 'success');
  2544. await fetchData(false);
  2545. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2546. if (iface) renderModalIPs(iface);
  2547. }
  2548. } catch (err) {
  2549. showToast('Error', err.message, 'error');
  2550. }
  2551. }
  2552. async function saveInterfaceMetadata() {
  2553. const role = document.getElementById('modal-iface-role').value;
  2554. const desc = document.getElementById('modal-iface-desc').value.trim();
  2555. try {
  2556. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2557. method: 'POST',
  2558. headers: { 'Content-Type': 'application/json' },
  2559. body: JSON.stringify({ role, description: desc })
  2560. });
  2561. if (res.ok) {
  2562. showToast('Saved', 'Metadata updated', 'success');
  2563. closeIfaceModal();
  2564. fetchData(false);
  2565. }
  2566. } catch (err) {
  2567. showToast('Error', err.message, 'error');
  2568. }
  2569. }
  2570. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2571. state.fwSubTab = 'filter';
  2572. state.routesSubTab = 'routes';
  2573. function renderRuleFlag(disabled, hasComment) {
  2574. let flags = '';
  2575. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2576. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2577. return flags || '<span class="text-slate-600">-</span>';
  2578. }
  2579. function renderActionBadge(action) {
  2580. const act = (action || '').toLowerCase();
  2581. let color = 'bg-slate-800 text-slate-300';
  2582. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2583. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2584. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2585. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2586. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2587. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2588. }
  2589. function switchFWSubTab(tab) {
  2590. state.fwSubTab = tab;
  2591. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2592. tabs.forEach(t => {
  2593. const panel = document.getElementById(`fw-subtab-${t}`);
  2594. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2595. if (panel) {
  2596. if (t === tab) panel.classList.remove('hidden');
  2597. else panel.classList.add('hidden');
  2598. }
  2599. if (btn) {
  2600. if (t === tab) {
  2601. 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';
  2602. } else {
  2603. 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';
  2604. }
  2605. }
  2606. });
  2607. const addBtn = document.getElementById('fw-primary-add-btn');
  2608. if (addBtn) {
  2609. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2610. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2611. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2612. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2613. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2614. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2615. }
  2616. if (tab === 'geo') loadGeoIP();
  2617. if (tab === 'connections') loadConnections();
  2618. setTimeout(initTableSorting, 50);
  2619. }
  2620. function openCurrentFWModal() {
  2621. if (state.fwSubTab === 'filter') openAddFilterModal();
  2622. else if (state.fwSubTab === 'nat') openAddNATModal();
  2623. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2624. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2625. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2626. else if (state.fwSubTab === 'connections') loadConnections();
  2627. }
  2628. async function loadFirewall(populateDropdowns = true) {
  2629. try {
  2630. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2631. fetch(`${API_BASE}/firewall/summary`),
  2632. fetch(`${API_BASE}/firewall/filter`),
  2633. fetch(`${API_BASE}/firewall/nat`),
  2634. fetch(`${API_BASE}/firewall/mangle`),
  2635. fetch(`${API_BASE}/firewall/address-lists`),
  2636. fetch(`${API_BASE}/firewall/geoip/status`),
  2637. fetch(`${API_BASE}/firewall/geoip/countries`)
  2638. ]);
  2639. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2640. if (filterRes.ok) state.filterRules = await filterRes.json();
  2641. if (natRes.ok) state.natRules = await natRes.json();
  2642. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2643. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2644. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2645. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2646. // Badges
  2647. const bFilter = document.getElementById('fw-badge-filter');
  2648. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2649. const bNat = document.getElementById('fw-badge-nat');
  2650. if (bNat) bNat.innerText = (state.natRules || []).length;
  2651. const bMangle = document.getElementById('fw-badge-mangle');
  2652. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2653. const bAddr = document.getElementById('fw-badge-addrlist');
  2654. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2655. const bGeo = document.getElementById('fw-badge-geo');
  2656. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2657. renderFilterRules();
  2658. renderNATRules();
  2659. renderMangleRules();
  2660. renderAddressLists();
  2661. renderGeoCountries();
  2662. if (state.fwSubTab === 'connections') {
  2663. loadConnections();
  2664. }
  2665. } catch (err) {
  2666. console.error('Failed to load firewall:', err);
  2667. }
  2668. }
  2669. // ----------------- Filter Rules -----------------
  2670. function renderFilterRules() {
  2671. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2672. const tbody = document.getElementById('filter-table-body');
  2673. const empty = document.getElementById('filter-empty');
  2674. if (!tbody) return;
  2675. tbody.innerHTML = '';
  2676. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2677. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2678. if (rules.length === 0) {
  2679. empty?.classList.remove('hidden');
  2680. return;
  2681. }
  2682. empty?.classList.add('hidden');
  2683. rules.forEach((r, idx) => {
  2684. const tr = document.createElement('tr');
  2685. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2686. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2687. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2688. let actionExtra = '';
  2689. if (r.action === 'reject') {
  2690. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2691. } else if (r.action === 'jump') {
  2692. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2693. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2694. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2695. } else if (r.action === 'log' && r.log_prefix) {
  2696. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2697. }
  2698. tr.innerHTML = `
  2699. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2700. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2701. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2702. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2703. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2704. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2705. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2706. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2707. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2708. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2709. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2710. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2711. </td>
  2712. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2713. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2714. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2715. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2716. <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>
  2717. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2718. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2719. </td>
  2720. `;
  2721. tbody.appendChild(tr);
  2722. });
  2723. }
  2724. function formatTarget(addr, list, geo) {
  2725. const parts = [];
  2726. if (addr) parts.push(`<span>${addr}</span>`);
  2727. if (list) {
  2728. const inv = list.startsWith('!') ? '!' : '';
  2729. const clean = list.replace(/^!/, '');
  2730. 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>`);
  2731. }
  2732. if (geo) {
  2733. const inv = geo.startsWith('!') ? '!' : '';
  2734. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2735. 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>`);
  2736. }
  2737. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2738. return parts.join(' ');
  2739. }
  2740. function populateInterfaceSelect(selectId, currentVal = '') {
  2741. const sel = document.getElementById(selectId);
  2742. if (!sel) return;
  2743. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2744. (state.interfaces || []).forEach(i => {
  2745. const opt = document.createElement('option');
  2746. opt.value = i.name;
  2747. opt.innerText = `${i.name} (${i.role || i.type})`;
  2748. if (i.name === currentVal) opt.selected = true;
  2749. sel.appendChild(opt);
  2750. });
  2751. }
  2752. function populateAddressListSelect(selectId, currentVal = '') {
  2753. const sel = document.getElementById(selectId);
  2754. if (!sel) return;
  2755. sel.innerHTML = '<option value="">(None)</option>';
  2756. const cleanVal = (currentVal || '').replace(/^!/, '');
  2757. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2758. customNames.forEach(name => {
  2759. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2760. const opt = document.createElement('option');
  2761. opt.value = name;
  2762. opt.innerText = `${name} (${count} entries)`;
  2763. if (name === cleanVal) opt.selected = true;
  2764. sel.appendChild(opt);
  2765. });
  2766. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2767. const opt = document.createElement('option');
  2768. opt.value = cleanVal;
  2769. opt.innerText = cleanVal;
  2770. opt.selected = true;
  2771. sel.appendChild(opt);
  2772. }
  2773. populateCommonAddrListDatalist();
  2774. }
  2775. function populateCommonAddrListDatalist() {
  2776. const dl = document.getElementById('fw-addrlist-datalist');
  2777. if (!dl) return;
  2778. dl.innerHTML = '';
  2779. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2780. names.forEach(name => {
  2781. const opt = document.createElement('option');
  2782. opt.value = name;
  2783. dl.appendChild(opt);
  2784. });
  2785. }
  2786. function populateGeoIPSelect(selectId, currentVal = '') {
  2787. const sel = document.getElementById(selectId);
  2788. if (!sel) return;
  2789. sel.innerHTML = '<option value="">(None)</option>';
  2790. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2791. // Presets optgroup
  2792. const grpPresets = document.createElement('optgroup');
  2793. grpPresets.label = '⚡ Regional Presets';
  2794. const presets = [
  2795. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2796. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2797. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2798. ];
  2799. presets.forEach(p => {
  2800. const opt = document.createElement('option');
  2801. opt.value = p.code;
  2802. opt.innerText = p.label;
  2803. if (p.code === cleanVal) opt.selected = true;
  2804. grpPresets.appendChild(opt);
  2805. });
  2806. sel.appendChild(grpPresets);
  2807. // All Countries optgroup
  2808. const grpCountries = document.createElement('optgroup');
  2809. grpCountries.label = '🌍 All Countries';
  2810. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2811. countries.forEach(c => {
  2812. const opt = document.createElement('option');
  2813. opt.value = c.code;
  2814. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2815. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2816. if (c.code === cleanVal) opt.selected = true;
  2817. grpCountries.appendChild(opt);
  2818. });
  2819. sel.appendChild(grpCountries);
  2820. }
  2821. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2822. function switchFwRuleTab(tab) {
  2823. state.activeFwRuleTab = tab;
  2824. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2825. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2826. btn.classList.add('text-slate-400', 'border-transparent');
  2827. });
  2828. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2829. if (activeBtn) {
  2830. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2831. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2832. }
  2833. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2834. const activePane = document.getElementById(`fw-pane-${tab}`);
  2835. if (activePane) activePane.classList.remove('hidden');
  2836. if (tab === 'statistics') {
  2837. startFwStatPolling();
  2838. } else {
  2839. stopFwStatPolling();
  2840. }
  2841. }
  2842. function toggleFwField(fieldKey, expand) {
  2843. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2844. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2845. if (!plusBtn || !fieldBox) return;
  2846. if (expand) {
  2847. plusBtn.classList.add('hidden');
  2848. fieldBox.classList.remove('hidden');
  2849. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2850. if (valInput) valInput.focus();
  2851. } else {
  2852. fieldBox.classList.add('hidden');
  2853. plusBtn.classList.remove('hidden');
  2854. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2855. if (valInput) {
  2856. if (valInput.tagName === 'SELECT') {
  2857. valInput.selectedIndex = 0;
  2858. } else {
  2859. valInput.value = '';
  2860. }
  2861. }
  2862. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2863. if (invInput) invInput.checked = false;
  2864. if (fieldKey === 'cs') {
  2865. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2866. const el = document.getElementById(id);
  2867. if (el) el.checked = false;
  2868. });
  2869. }
  2870. if (fieldKey === 'natstate') {
  2871. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2872. const el = document.getElementById(id);
  2873. if (el) el.checked = false;
  2874. });
  2875. }
  2876. if (fieldKey === 'days') {
  2877. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2878. const el = document.getElementById(`fw-day-${d}`);
  2879. if (el) el.checked = true;
  2880. });
  2881. }
  2882. }
  2883. }
  2884. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2885. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2886. toggleFwField(fieldKey, true);
  2887. let strVal = String(value);
  2888. if (hasInvert) {
  2889. const inv = strVal.startsWith('!');
  2890. if (inv) strVal = strVal.slice(1);
  2891. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2892. if (invEl) invEl.checked = inv;
  2893. }
  2894. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2895. if (valEl) valEl.value = strVal;
  2896. } else {
  2897. toggleFwField(fieldKey, false);
  2898. }
  2899. }
  2900. function getFwFieldVal(fieldKey, hasInvert = false) {
  2901. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2902. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2903. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2904. let v = valEl ? valEl.value.trim() : '';
  2905. if (!v) return '';
  2906. if (hasInvert) {
  2907. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2908. if (invEl && invEl.checked) {
  2909. v = '!' + v.replace(/^!/, '');
  2910. }
  2911. }
  2912. return v;
  2913. }
  2914. function toggleMaximizeFilterModal() {
  2915. const win = document.getElementById('filter-modal-window');
  2916. if (!win) return;
  2917. if (win.classList.contains('max-w-[720px]')) {
  2918. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2919. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2920. } else {
  2921. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  2922. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  2923. }
  2924. }
  2925. function openAddFilterModal() {
  2926. switchFwRuleTab('general');
  2927. const badge = document.getElementById('fw-modal-badge');
  2928. if (badge) badge.innerText = 'New...';
  2929. document.getElementById('filter-modal-id').value = '';
  2930. document.getElementById('filter-modal-enabled').checked = true;
  2931. document.getElementById('filter-modal-comment').value = '';
  2932. document.getElementById('filter-modal-chain').value = 'forward';
  2933. document.getElementById('filter-modal-action').value = 'accept';
  2934. document.getElementById('filter-modal-log').checked = false;
  2935. populateInterfaceSelect('fw-val-iniface');
  2936. populateInterfaceSelect('fw-val-outiface');
  2937. populateAddressListSelect('fw-val-srclist');
  2938. populateAddressListSelect('fw-val-dstlist');
  2939. populateGeoIPSelect('fw-val-srcgeo');
  2940. populateGeoIPSelect('fw-val-dstgeo');
  2941. const allFieldKeys = [
  2942. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  2943. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  2944. 'routingmark', 'conntype', 'cs', 'natstate',
  2945. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  2946. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  2947. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  2948. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  2949. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  2950. ];
  2951. allFieldKeys.forEach(k => toggleFwField(k, false));
  2952. resetCurrentRuleCounters();
  2953. toggleFilterActionFields();
  2954. document.getElementById('filter-modal').classList.remove('hidden');
  2955. }
  2956. function openEditFilterModal(id) {
  2957. const r = (state.filterRules || []).find(rule => rule.id === id);
  2958. if (!r) return;
  2959. switchFwRuleTab('general');
  2960. const badge = document.getElementById('fw-modal-badge');
  2961. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  2962. document.getElementById('filter-modal-id').value = r.id;
  2963. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  2964. document.getElementById('filter-modal-comment').value = r.comment || '';
  2965. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  2966. document.getElementById('filter-modal-action').value = r.action || 'accept';
  2967. document.getElementById('filter-modal-log').checked = !!r.log;
  2968. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  2969. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  2970. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  2971. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  2972. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  2973. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  2974. setFwFieldVal('src', r.src_address, true);
  2975. setFwFieldVal('dst', r.dst_address, true);
  2976. setFwFieldVal('srclist', r.src_address_list, true);
  2977. setFwFieldVal('dstlist', r.dst_address_list, true);
  2978. setFwFieldVal('srcgeo', r.src_geoip, true);
  2979. setFwFieldVal('dstgeo', r.dst_geoip, true);
  2980. if (r.protocol && r.protocol !== 'all') {
  2981. setFwFieldVal('proto', r.protocol, true);
  2982. } else {
  2983. toggleFwField('proto', false);
  2984. }
  2985. setFwFieldVal('sport', r.src_port, true);
  2986. setFwFieldVal('dport', r.dst_port, true);
  2987. setFwFieldVal('anyport', r.any_port, true);
  2988. setFwFieldVal('iniface', r.in_interface, true);
  2989. setFwFieldVal('outiface', r.out_interface, true);
  2990. setFwFieldVal('inifacelist', r.in_interface_list, true);
  2991. setFwFieldVal('outifacelist', r.out_interface_list, true);
  2992. setFwFieldVal('pktmark', r.packet_mark, true);
  2993. setFwFieldVal('connmark', r.connection_mark, true);
  2994. setFwFieldVal('routingmark', r.routing_mark, true);
  2995. setFwFieldVal('conntype', r.connection_type, false);
  2996. const states = r.connection_state || [];
  2997. if (states.length > 0) {
  2998. toggleFwField('cs', true);
  2999. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3000. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3001. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3002. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3003. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3004. } else {
  3005. toggleFwField('cs', false);
  3006. }
  3007. const natStates = r.connection_nat_state || [];
  3008. if (natStates.length > 0) {
  3009. toggleFwField('natstate', true);
  3010. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3011. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3012. } else {
  3013. toggleFwField('natstate', false);
  3014. }
  3015. // Advanced tab fields
  3016. setFwFieldVal('layer7', r.layer7_protocol, false);
  3017. setFwFieldVal('content', r.content, false);
  3018. setFwFieldVal('connbytes', r.connection_bytes, false);
  3019. setFwFieldVal('connrate', r.connection_rate, false);
  3020. setFwFieldVal('pcc', r.pcc, false);
  3021. setFwFieldVal('srcmac', r.src_mac_address, true);
  3022. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3023. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3024. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3025. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3026. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3027. setFwFieldVal('tlshost', r.tls_host, false);
  3028. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3029. setFwFieldVal('priority', r.priority, false);
  3030. setFwFieldVal('dscp', r.dscp, false);
  3031. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3032. if (r.tos) {
  3033. const tosEl = document.getElementById('fw-val-tos');
  3034. if (tosEl) tosEl.value = r.tos;
  3035. }
  3036. setFwFieldVal('pktsize', r.packet_size, false);
  3037. setFwFieldVal('random', r.random, false);
  3038. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3039. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3040. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3041. setFwFieldVal('ttl', r.ttl, false);
  3042. // Extra tab fields
  3043. setFwFieldVal('time', r.time, false);
  3044. if (r.days) {
  3045. toggleFwField('days', true);
  3046. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3047. const chk = document.getElementById(`fw-day-${d}`);
  3048. if (chk) chk.checked = r.days.includes(d);
  3049. });
  3050. } else {
  3051. toggleFwField('days', false);
  3052. }
  3053. setFwFieldVal('limit', r.limit, false);
  3054. setFwFieldVal('dstlimit', r.dst_limit, false);
  3055. setFwFieldVal('psd', r.psd, false);
  3056. // Action fields
  3057. if (r.reject_with) {
  3058. const rwEl = document.getElementById('filter-modal-rejectwith');
  3059. if (rwEl) rwEl.value = r.reject_with;
  3060. }
  3061. if (r.jump_target) {
  3062. const jtEl = document.getElementById('filter-modal-jumptarget');
  3063. if (jtEl) jtEl.value = r.jump_target;
  3064. }
  3065. if (r.address_list) {
  3066. const alEl = document.getElementById('filter-modal-action-addrlist');
  3067. if (alEl) alEl.value = r.address_list;
  3068. }
  3069. if (r.address_list_timeout) {
  3070. const toEl = document.getElementById('filter-modal-action-timeout');
  3071. if (toEl) toEl.value = r.address_list_timeout;
  3072. }
  3073. setFwFieldVal('logprefix', r.log_prefix, false);
  3074. // Statistics
  3075. const bEl = document.getElementById('fw-stat-bytes');
  3076. const pEl = document.getElementById('fw-stat-packets');
  3077. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3078. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3079. state.fwLastBytes = r.bytes || 0;
  3080. state.fwLastPackets = r.packets || 0;
  3081. state.fwLastTimestamp = Date.now();
  3082. state.fwStatRateHistory = new Array(30).fill(0);
  3083. state.fwStatPktHistory = new Array(30).fill(0);
  3084. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3085. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3086. toggleFilterActionFields();
  3087. document.getElementById('filter-modal').classList.remove('hidden');
  3088. }
  3089. function closeFilterModal() {
  3090. stopFwStatPolling();
  3091. document.getElementById('filter-modal').classList.add('hidden');
  3092. }
  3093. function toggleFilterActionFields() {
  3094. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3095. const rejectBox = document.getElementById('filter-action-reject-box');
  3096. const jumpBox = document.getElementById('filter-action-jump-box');
  3097. const addrBox = document.getElementById('filter-action-addrlist-box');
  3098. if (rejectBox) {
  3099. if (act === 'reject') rejectBox.classList.remove('hidden');
  3100. else rejectBox.classList.add('hidden');
  3101. }
  3102. if (jumpBox) {
  3103. if (act === 'jump') jumpBox.classList.remove('hidden');
  3104. else jumpBox.classList.add('hidden');
  3105. }
  3106. if (addrBox) {
  3107. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3108. addrBox.classList.remove('hidden');
  3109. } else {
  3110. addrBox.classList.add('hidden');
  3111. }
  3112. }
  3113. if (act === 'log') {
  3114. const logEl = document.getElementById('filter-modal-log');
  3115. if (logEl) logEl.checked = true;
  3116. toggleFwField('logprefix', true);
  3117. }
  3118. }
  3119. function toggleFwLogPrefix() {
  3120. const isLog = document.getElementById('filter-modal-log')?.checked;
  3121. toggleFwField('logprefix', !!isLog);
  3122. }
  3123. function copyFilterRule() {
  3124. document.getElementById('filter-modal-id').value = '';
  3125. const badge = document.getElementById('fw-modal-badge');
  3126. if (badge) badge.innerText = 'New...';
  3127. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3128. }
  3129. function resetCurrentRuleCounters() {
  3130. state.fwStatRateHistory = new Array(30).fill(0);
  3131. state.fwStatPktHistory = new Array(30).fill(0);
  3132. state.fwLastBytes = 0;
  3133. state.fwLastPackets = 0;
  3134. state.fwLastTimestamp = Date.now();
  3135. const bEl = document.getElementById('fw-stat-bytes');
  3136. const pEl = document.getElementById('fw-stat-packets');
  3137. const rEl = document.getElementById('fw-stat-rate');
  3138. const prEl = document.getElementById('fw-stat-pktrate');
  3139. if (bEl) bEl.value = '0 B';
  3140. if (pEl) pEl.value = '0';
  3141. if (rEl) rEl.value = '0 bps';
  3142. if (prEl) prEl.value = '0 p/s';
  3143. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3144. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3145. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3146. }
  3147. async function resetAllFwCounters() {
  3148. try {
  3149. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3150. if (res.ok) {
  3151. resetCurrentRuleCounters();
  3152. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3153. loadFirewall(false);
  3154. }
  3155. } catch (err) {
  3156. showToast('Error', err.message, 'error');
  3157. }
  3158. }
  3159. async function applyFilterRule(closeAfter = false) {
  3160. const id = document.getElementById('filter-modal-id').value;
  3161. const chain = document.getElementById('filter-modal-chain').value;
  3162. const action = document.getElementById('filter-modal-action').value;
  3163. const comment = document.getElementById('filter-modal-comment').value.trim();
  3164. const enabled = document.getElementById('filter-modal-enabled').checked;
  3165. const src = getFwFieldVal('src', true);
  3166. const dst = getFwFieldVal('dst', true);
  3167. const srclist = getFwFieldVal('srclist', true);
  3168. const dstlist = getFwFieldVal('dstlist', true);
  3169. const srcgeo = getFwFieldVal('srcgeo', true);
  3170. const dstgeo = getFwFieldVal('dstgeo', true);
  3171. const proto = getFwFieldVal('proto', true);
  3172. const sport = getFwFieldVal('sport', true);
  3173. const dport = getFwFieldVal('dport', true);
  3174. const anyport = getFwFieldVal('anyport', true);
  3175. const iniface = getFwFieldVal('iniface', true);
  3176. const outiface = getFwFieldVal('outiface', true);
  3177. const inifacelist = getFwFieldVal('inifacelist', true);
  3178. const outifacelist = getFwFieldVal('outifacelist', true);
  3179. const pktmark = getFwFieldVal('pktmark', true);
  3180. const connmark = getFwFieldVal('connmark', true);
  3181. const routingmark = getFwFieldVal('routingmark', true);
  3182. const conntype = getFwFieldVal('conntype', false);
  3183. const states = [];
  3184. const csBox = document.getElementById('fw-field-cs');
  3185. if (csBox && !csBox.classList.contains('hidden')) {
  3186. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3187. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3188. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3189. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3190. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3191. }
  3192. const natStates = [];
  3193. const natBox = document.getElementById('fw-field-natstate');
  3194. if (natBox && !natBox.classList.contains('hidden')) {
  3195. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3196. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3197. }
  3198. const payload = {
  3199. id,
  3200. chain,
  3201. action,
  3202. protocol: proto || 'all',
  3203. src_address: src,
  3204. dst_address: dst,
  3205. src_port: sport,
  3206. dst_port: dport,
  3207. any_port: anyport,
  3208. in_interface: iniface,
  3209. out_interface: outiface,
  3210. in_interface_list: inifacelist,
  3211. out_interface_list: outifacelist,
  3212. packet_mark: pktmark,
  3213. connection_mark: connmark,
  3214. routing_mark: routingmark,
  3215. connection_type: conntype,
  3216. connection_state: states,
  3217. connection_nat_state: natStates,
  3218. src_address_list: srclist,
  3219. dst_address_list: dstlist,
  3220. src_geoip: srcgeo,
  3221. dst_geoip: dstgeo,
  3222. comment,
  3223. disabled: !enabled,
  3224. // Advanced tab
  3225. layer7_protocol: getFwFieldVal('layer7', false),
  3226. content: getFwFieldVal('content', false),
  3227. connection_bytes: getFwFieldVal('connbytes', false),
  3228. connection_rate: getFwFieldVal('connrate', false),
  3229. pcc: getFwFieldVal('pcc', false),
  3230. src_mac_address: getFwFieldVal('srcmac', true),
  3231. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3232. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3233. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3234. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3235. ipsec_policy: getFwFieldVal('ipsec', false),
  3236. tls_host: getFwFieldVal('tlshost', false),
  3237. ingress_priority: getFwFieldVal('ingresspriority', false),
  3238. priority: getFwFieldVal('priority', false),
  3239. dscp: getFwFieldVal('dscp', false),
  3240. tcp_mss: getFwFieldVal('tcpmss', false),
  3241. tos: document.getElementById('fw-val-tos')?.value || '',
  3242. packet_size: getFwFieldVal('pktsize', false),
  3243. random: getFwFieldVal('random', false),
  3244. tcp_flags: getFwFieldVal('tcpflags', false),
  3245. icmp_options: getFwFieldVal('icmpoptions', false),
  3246. ipv4_options: getFwFieldVal('ipv4options', false),
  3247. ttl: getFwFieldVal('ttl', false),
  3248. // Extra tab
  3249. time: getFwFieldVal('time', false),
  3250. limit: getFwFieldVal('limit', false),
  3251. dst_limit: getFwFieldVal('dstlimit', false),
  3252. psd: getFwFieldVal('psd', false),
  3253. // Action tab
  3254. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3255. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3256. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3257. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3258. log: document.getElementById('filter-modal-log')?.checked || false,
  3259. log_prefix: getFwFieldVal('logprefix', false)
  3260. };
  3261. try {
  3262. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3263. method: 'POST',
  3264. headers: { 'Content-Type': 'application/json' },
  3265. body: JSON.stringify(payload)
  3266. });
  3267. if (res.ok) {
  3268. const data = await res.json();
  3269. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3270. loadFirewall(false);
  3271. if (closeAfter) {
  3272. closeFilterModal();
  3273. } else {
  3274. if (data.id) {
  3275. document.getElementById('filter-modal-id').value = data.id;
  3276. const badge = document.getElementById('fw-modal-badge');
  3277. if (badge) badge.innerText = `#${data.id}`;
  3278. }
  3279. }
  3280. } else {
  3281. const err = await res.json();
  3282. showToast('Error', err.message || 'Failed to save rule', 'error');
  3283. }
  3284. } catch (err) {
  3285. showToast('Error', err.message, 'error');
  3286. }
  3287. }
  3288. function submitSaveFilterRule(e) {
  3289. if (e && e.preventDefault) e.preventDefault();
  3290. return applyFilterRule(true);
  3291. }
  3292. function startFwStatPolling() {
  3293. stopFwStatPolling();
  3294. pollRuleStats();
  3295. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3296. }
  3297. function stopFwStatPolling() {
  3298. if (state.fwStatInterval) {
  3299. clearInterval(state.fwStatInterval);
  3300. state.fwStatInterval = null;
  3301. }
  3302. }
  3303. async function pollRuleStats() {
  3304. const id = document.getElementById('filter-modal-id')?.value;
  3305. if (!id) {
  3306. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3307. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3308. return;
  3309. }
  3310. try {
  3311. const res = await fetch(`${API_BASE}/firewall/filter`);
  3312. if (!res.ok) return;
  3313. const rules = await res.json();
  3314. const r = rules.find(x => x.id === id);
  3315. if (!r) return;
  3316. const now = Date.now();
  3317. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3318. state.fwLastTimestamp = now;
  3319. const curBytes = r.bytes || 0;
  3320. const curPackets = r.packets || 0;
  3321. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3322. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3323. state.fwLastBytes = curBytes;
  3324. state.fwLastPackets = curPackets;
  3325. const rateBps = Math.round((deltaBytes * 8) / dt);
  3326. const ratePkt = Math.round(deltaPkts / dt);
  3327. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3328. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3329. state.fwStatRateHistory.push(rateBps);
  3330. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3331. state.fwStatPktHistory.push(ratePkt);
  3332. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3333. const bEl = document.getElementById('fw-stat-bytes');
  3334. const pEl = document.getElementById('fw-stat-packets');
  3335. const rEl = document.getElementById('fw-stat-rate');
  3336. const prEl = document.getElementById('fw-stat-pktrate');
  3337. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3338. if (pEl) pEl.value = curPackets.toLocaleString();
  3339. if (rEl) rEl.value = formatBps(rateBps);
  3340. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3341. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3342. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3343. } catch (e) {
  3344. console.error('Error polling rule stats', e);
  3345. }
  3346. }
  3347. function formatBps(bps) {
  3348. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3349. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3350. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3351. return bps + ' bps';
  3352. }
  3353. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3354. const svg = document.getElementById(svgId);
  3355. if (!svg) return;
  3356. const w = 500;
  3357. const h = 100;
  3358. const paddingRight = 45;
  3359. const graphWidth = w - paddingRight;
  3360. const maxVal = Math.max(5, ...dataArray);
  3361. const currentVal = dataArray[dataArray.length - 1] || 0;
  3362. const leg = document.getElementById(legendId);
  3363. if (leg) {
  3364. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3365. }
  3366. let gridLines = '';
  3367. for (let i = 0; i <= 5; i++) {
  3368. const y = 8 + (i * (h - 18) / 5);
  3369. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3370. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3371. gridLines += `
  3372. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3373. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3374. `;
  3375. }
  3376. const step = graphWidth / (dataArray.length - 1);
  3377. const points = dataArray.map((val, idx) => {
  3378. const x = idx * step;
  3379. const y = (h - 10) - (val / maxVal) * (h - 20);
  3380. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3381. });
  3382. const polylineStr = points.join(' ');
  3383. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3384. svg.innerHTML = `
  3385. ${gridLines}
  3386. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3387. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3388. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3389. `;
  3390. }
  3391. async function moveFilterRule(id, dir) {
  3392. try {
  3393. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3394. method: 'POST',
  3395. headers: { 'Content-Type': 'application/json' },
  3396. body: JSON.stringify({ direction: dir })
  3397. });
  3398. if (res.ok) loadFirewall(false);
  3399. } catch (err) {
  3400. showToast('Error', err.message, 'error');
  3401. }
  3402. }
  3403. async function toggleFilterRuleState(id, disabled) {
  3404. try {
  3405. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3406. method: 'POST',
  3407. headers: { 'Content-Type': 'application/json' },
  3408. body: JSON.stringify({ disabled })
  3409. });
  3410. if (res.ok) loadFirewall(false);
  3411. } catch (err) {
  3412. showToast('Error', err.message, 'error');
  3413. }
  3414. }
  3415. async function deleteFilterRule(id) {
  3416. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3417. try {
  3418. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3419. if (res.ok) {
  3420. showToast('Deleted', 'Filter rule removed', 'success');
  3421. loadFirewall(false);
  3422. }
  3423. } catch (err) {
  3424. showToast('Error', err.message, 'error');
  3425. }
  3426. }
  3427. // ----------------- NAT Rules -----------------
  3428. function renderNATRules() {
  3429. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3430. const tbody = document.getElementById('nat-table-body');
  3431. const empty = document.getElementById('nat-empty');
  3432. if (!tbody) return;
  3433. tbody.innerHTML = '';
  3434. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3435. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3436. if (rules.length === 0) {
  3437. empty?.classList.remove('hidden');
  3438. return;
  3439. }
  3440. empty?.classList.add('hidden');
  3441. rules.forEach((r, idx) => {
  3442. const tr = document.createElement('tr');
  3443. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3444. let toTarget = '-';
  3445. if (r.action === 'jump') {
  3446. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3447. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3448. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3449. } else if (r.action === 'redirect') {
  3450. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3451. } else if (r.action === 'masquerade') {
  3452. 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>`;
  3453. } else if (r.action === 'log') {
  3454. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3455. } else {
  3456. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3457. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3458. }
  3459. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3460. tr.innerHTML = `
  3461. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3462. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3463. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3464. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3465. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3466. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3467. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3468. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3469. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3470. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3471. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3472. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3473. </td>
  3474. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3475. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3476. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3477. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3478. <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>
  3479. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3480. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3481. </td>
  3482. `;
  3483. tbody.appendChild(tr);
  3484. });
  3485. }
  3486. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3487. function switchNATRuleTab(tab) {
  3488. state.activeNATRuleTab = tab;
  3489. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3490. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3491. btn.classList.add('text-slate-400', 'border-transparent');
  3492. });
  3493. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3494. if (activeBtn) {
  3495. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3496. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3497. }
  3498. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3499. const activePane = document.getElementById(`nat-pane-${tab}`);
  3500. if (activePane) activePane.classList.remove('hidden');
  3501. if (tab === 'statistics') {
  3502. startNATStatPolling();
  3503. } else {
  3504. stopNATStatPolling();
  3505. }
  3506. }
  3507. function toggleNATField(fieldKey, expand) {
  3508. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3509. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3510. if (!plusBtn || !fieldBox) return;
  3511. if (expand) {
  3512. plusBtn.classList.add('hidden');
  3513. fieldBox.classList.remove('hidden');
  3514. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3515. if (valInput) valInput.focus();
  3516. } else {
  3517. fieldBox.classList.add('hidden');
  3518. plusBtn.classList.remove('hidden');
  3519. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3520. if (valInput) {
  3521. if (valInput.tagName === 'SELECT') {
  3522. valInput.selectedIndex = 0;
  3523. } else {
  3524. valInput.value = '';
  3525. }
  3526. }
  3527. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3528. if (invInput) invInput.checked = false;
  3529. if (fieldKey === 'days') {
  3530. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3531. const el = document.getElementById(`nat-day-${d}`);
  3532. if (el) el.checked = true;
  3533. });
  3534. }
  3535. }
  3536. }
  3537. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3538. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3539. toggleNATField(fieldKey, true);
  3540. let strVal = String(value);
  3541. if (hasInvert) {
  3542. const inv = strVal.startsWith('!');
  3543. if (inv) strVal = strVal.slice(1);
  3544. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3545. if (invEl) invEl.checked = inv;
  3546. }
  3547. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3548. if (valEl) valEl.value = strVal;
  3549. } else {
  3550. toggleNATField(fieldKey, false);
  3551. }
  3552. }
  3553. function getNATFieldVal(fieldKey, hasInvert = false) {
  3554. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3555. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3556. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3557. let v = valEl ? valEl.value.trim() : '';
  3558. if (!v) return '';
  3559. if (hasInvert) {
  3560. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3561. if (invEl && invEl.checked) {
  3562. v = '!' + v.replace(/^!/, '');
  3563. }
  3564. }
  3565. return v;
  3566. }
  3567. function toggleMaximizeNATModal() {
  3568. const win = document.getElementById('nat-modal-window');
  3569. if (!win) return;
  3570. if (win.classList.contains('max-w-[720px]')) {
  3571. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3572. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3573. } else {
  3574. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3575. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3576. }
  3577. }
  3578. function handleNATChainChange() {
  3579. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3580. const actSel = document.getElementById('nat-modal-action');
  3581. if (actSel) {
  3582. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3583. actSel.value = 'masquerade';
  3584. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3585. actSel.value = 'dst-nat';
  3586. }
  3587. }
  3588. toggleNATActionFields();
  3589. }
  3590. function toggleNATActionFields() {
  3591. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3592. const rowAddr = document.getElementById('nat-row-toaddr');
  3593. const rowPort = document.getElementById('nat-row-toport');
  3594. const jumpBox = document.getElementById('nat-action-jump-box');
  3595. const addrBox = document.getElementById('nat-action-addrlist-box');
  3596. // Hide all dynamic rows first
  3597. if (rowAddr) rowAddr.classList.add('hidden');
  3598. if (rowPort) rowPort.classList.add('hidden');
  3599. if (jumpBox) jumpBox.classList.add('hidden');
  3600. if (addrBox) addrBox.classList.add('hidden');
  3601. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3602. if (rowAddr) rowAddr.classList.remove('hidden');
  3603. if (rowPort) rowPort.classList.remove('hidden');
  3604. } else if (act === 'redirect' || act === 'masquerade') {
  3605. if (rowPort) rowPort.classList.remove('hidden');
  3606. } else if (act === 'jump') {
  3607. if (jumpBox) jumpBox.classList.remove('hidden');
  3608. } else if (act.includes('address-list') || act.includes('address list')) {
  3609. if (addrBox) addrBox.classList.remove('hidden');
  3610. }
  3611. if (act === 'log') {
  3612. const logEl = document.getElementById('nat-modal-log');
  3613. if (logEl) logEl.checked = true;
  3614. toggleNATField('logprefix', true);
  3615. }
  3616. }
  3617. function toggleNATLogPrefix() {
  3618. const isLog = document.getElementById('nat-modal-log')?.checked;
  3619. toggleNATField('logprefix', !!isLog);
  3620. }
  3621. function openAddNATModal() {
  3622. switchNATRuleTab('general');
  3623. const badge = document.getElementById('nat-modal-badge');
  3624. if (badge) badge.innerText = 'New...';
  3625. document.getElementById('nat-modal-id').value = '';
  3626. document.getElementById('nat-modal-enabled').checked = true;
  3627. document.getElementById('nat-modal-comment').value = '';
  3628. document.getElementById('nat-modal-chain').value = 'srcnat';
  3629. document.getElementById('nat-modal-action').value = 'masquerade';
  3630. document.getElementById('nat-modal-toaddr').value = '';
  3631. document.getElementById('nat-modal-toport').value = '';
  3632. document.getElementById('nat-modal-log').checked = false;
  3633. populateInterfaceSelect('nat-val-iniface');
  3634. populateInterfaceSelect('nat-val-outiface');
  3635. populateAddressListSelect('nat-val-srclist');
  3636. populateAddressListSelect('nat-val-dstlist');
  3637. populateGeoIPSelect('nat-val-srcgeo');
  3638. populateGeoIPSelect('nat-val-dstgeo');
  3639. const allFieldKeys = [
  3640. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3641. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3642. 'routingmark', 'conntype',
  3643. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3644. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3645. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3646. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3647. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3648. ];
  3649. allFieldKeys.forEach(k => toggleNATField(k, false));
  3650. resetCurrentNATRuleCounters();
  3651. toggleNATActionFields();
  3652. document.getElementById('nat-modal').classList.remove('hidden');
  3653. }
  3654. function openEditNATModal(id) {
  3655. const r = (state.natRules || []).find(rule => rule.id === id);
  3656. if (!r) return;
  3657. switchNATRuleTab('general');
  3658. const badge = document.getElementById('nat-modal-badge');
  3659. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3660. document.getElementById('nat-modal-id').value = r.id;
  3661. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3662. document.getElementById('nat-modal-comment').value = r.comment || '';
  3663. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3664. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3665. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3666. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3667. document.getElementById('nat-modal-log').checked = !!r.log;
  3668. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3669. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3670. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3671. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3672. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3673. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3674. setNATFieldVal('src', r.src_address, true);
  3675. setNATFieldVal('dst', r.dst_address, true);
  3676. setNATFieldVal('srclist', r.src_address_list, true);
  3677. setNATFieldVal('dstlist', r.dst_address_list, true);
  3678. setNATFieldVal('srcgeo', r.src_geoip, true);
  3679. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3680. if (r.protocol && r.protocol !== 'all') {
  3681. setNATFieldVal('proto', r.protocol, true);
  3682. } else {
  3683. toggleNATField('proto', false);
  3684. }
  3685. setNATFieldVal('sport', r.src_port, true);
  3686. setNATFieldVal('dport', r.dst_port, true);
  3687. setNATFieldVal('anyport', r.any_port, true);
  3688. setNATFieldVal('iniface', r.in_interface, true);
  3689. setNATFieldVal('outiface', r.out_interface, true);
  3690. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3691. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3692. setNATFieldVal('pktmark', r.packet_mark, true);
  3693. setNATFieldVal('connmark', r.connection_mark, true);
  3694. setNATFieldVal('routingmark', r.routing_mark, true);
  3695. setNATFieldVal('conntype', r.connection_type, false);
  3696. // Advanced tab fields
  3697. setNATFieldVal('layer7', r.layer7_protocol, false);
  3698. setNATFieldVal('content', r.content, false);
  3699. setNATFieldVal('connbytes', r.connection_bytes, false);
  3700. setNATFieldVal('connrate', r.connection_rate, false);
  3701. setNATFieldVal('pcc', r.pcc, false);
  3702. setNATFieldVal('srcmac', r.src_mac_address, true);
  3703. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3704. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3705. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3706. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3707. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3708. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3709. setNATFieldVal('priority', r.priority, false);
  3710. setNATFieldVal('dscp', r.dscp, false);
  3711. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3712. if (r.tos) {
  3713. const tosEl = document.getElementById('nat-val-tos');
  3714. if (tosEl) tosEl.value = r.tos;
  3715. }
  3716. setNATFieldVal('pktsize', r.packet_size, false);
  3717. setNATFieldVal('random', r.random, false);
  3718. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3719. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3720. setNATFieldVal('ttl', r.ttl, false);
  3721. // Extra tab fields
  3722. setNATFieldVal('time', r.time, false);
  3723. if (r.days) {
  3724. toggleNATField('days', true);
  3725. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3726. const chk = document.getElementById(`nat-day-${d}`);
  3727. if (chk) chk.checked = r.days.includes(d);
  3728. });
  3729. } else {
  3730. toggleNATField('days', false);
  3731. }
  3732. setNATFieldVal('limit', r.limit, false);
  3733. setNATFieldVal('dstlimit', r.dst_limit, false);
  3734. setNATFieldVal('psd', r.psd, false);
  3735. // Action fields
  3736. if (r.jump_target) {
  3737. const jtEl = document.getElementById('nat-modal-jumptarget');
  3738. if (jtEl) jtEl.value = r.jump_target;
  3739. }
  3740. if (r.address_list) {
  3741. const alEl = document.getElementById('nat-modal-action-addrlist');
  3742. if (alEl) alEl.value = r.address_list;
  3743. }
  3744. if (r.address_list_timeout) {
  3745. const toEl = document.getElementById('nat-modal-action-timeout');
  3746. if (toEl) toEl.value = r.address_list_timeout;
  3747. }
  3748. setNATFieldVal('logprefix', r.log_prefix, false);
  3749. // Statistics
  3750. const bEl = document.getElementById('nat-stat-bytes');
  3751. const pEl = document.getElementById('nat-stat-packets');
  3752. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3753. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3754. state.natLastBytes = r.bytes || 0;
  3755. state.natLastPackets = r.packets || 0;
  3756. state.natLastTimestamp = Date.now();
  3757. state.natStatRateHistory = new Array(30).fill(0);
  3758. state.natStatPktHistory = new Array(30).fill(0);
  3759. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3760. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3761. toggleNATActionFields();
  3762. document.getElementById('nat-modal').classList.remove('hidden');
  3763. }
  3764. function closeNATModal() {
  3765. stopNATStatPolling();
  3766. document.getElementById('nat-modal').classList.add('hidden');
  3767. }
  3768. function copyNATRule() {
  3769. document.getElementById('nat-modal-id').value = '';
  3770. const badge = document.getElementById('nat-modal-badge');
  3771. if (badge) badge.innerText = 'New...';
  3772. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3773. }
  3774. function resetCurrentNATRuleCounters() {
  3775. state.natStatRateHistory = new Array(30).fill(0);
  3776. state.natStatPktHistory = new Array(30).fill(0);
  3777. state.natLastBytes = 0;
  3778. state.natLastPackets = 0;
  3779. state.natLastTimestamp = Date.now();
  3780. const bEl = document.getElementById('nat-stat-bytes');
  3781. const pEl = document.getElementById('nat-stat-packets');
  3782. const rEl = document.getElementById('nat-stat-rate');
  3783. const prEl = document.getElementById('nat-stat-pktrate');
  3784. if (bEl) bEl.value = '0 B';
  3785. if (pEl) pEl.value = '0';
  3786. if (rEl) rEl.value = '0 bps';
  3787. if (prEl) prEl.value = '0 p/s';
  3788. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3789. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3790. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3791. }
  3792. async function applyNATRule(closeAfter = false) {
  3793. const id = document.getElementById('nat-modal-id').value;
  3794. const chain = document.getElementById('nat-modal-chain').value;
  3795. const action = document.getElementById('nat-modal-action').value;
  3796. const comment = document.getElementById('nat-modal-comment').value.trim();
  3797. const enabled = document.getElementById('nat-modal-enabled').checked;
  3798. const src = getNATFieldVal('src', true);
  3799. const dst = getNATFieldVal('dst', true);
  3800. const srclist = getNATFieldVal('srclist', true);
  3801. const dstlist = getNATFieldVal('dstlist', true);
  3802. const srcgeo = getNATFieldVal('srcgeo', true);
  3803. const dstgeo = getNATFieldVal('dstgeo', true);
  3804. const proto = getNATFieldVal('proto', true);
  3805. const sport = getNATFieldVal('sport', true);
  3806. const dport = getNATFieldVal('dport', true);
  3807. const anyport = getNATFieldVal('anyport', true);
  3808. const iniface = getNATFieldVal('iniface', true);
  3809. const outiface = getNATFieldVal('outiface', true);
  3810. const inifacelist = getNATFieldVal('inifacelist', true);
  3811. const outifacelist = getNATFieldVal('outifacelist', true);
  3812. const pktmark = getNATFieldVal('pktmark', true);
  3813. const connmark = getNATFieldVal('connmark', true);
  3814. const routingmark = getNATFieldVal('routingmark', true);
  3815. const conntype = getNATFieldVal('conntype', false);
  3816. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3817. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3818. const payload = {
  3819. id,
  3820. chain,
  3821. action,
  3822. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3823. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3824. protocol: proto || 'all',
  3825. src_address: src,
  3826. dst_address: dst,
  3827. src_port: sport,
  3828. dst_port: dport,
  3829. any_port: anyport,
  3830. in_interface: iniface,
  3831. out_interface: outiface,
  3832. in_interface_list: inifacelist,
  3833. out_interface_list: outifacelist,
  3834. packet_mark: pktmark,
  3835. connection_mark: connmark,
  3836. routing_mark: routingmark,
  3837. connection_type: conntype,
  3838. src_address_list: srclist,
  3839. dst_address_list: dstlist,
  3840. src_geoip: srcgeo,
  3841. dst_geoip: dstgeo,
  3842. comment,
  3843. disabled: !enabled,
  3844. // Advanced tab
  3845. layer7_protocol: getNATFieldVal('layer7', false),
  3846. content: getNATFieldVal('content', false),
  3847. connection_bytes: getNATFieldVal('connbytes', false),
  3848. connection_rate: getNATFieldVal('connrate', false),
  3849. pcc: getNATFieldVal('pcc', false),
  3850. src_mac_address: getNATFieldVal('srcmac', true),
  3851. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3852. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3853. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3854. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3855. ipsec_policy: getNATFieldVal('ipsec', false),
  3856. ingress_priority: getNATFieldVal('ingresspriority', false),
  3857. priority: getNATFieldVal('priority', false),
  3858. dscp: getNATFieldVal('dscp', false),
  3859. tcp_mss: getNATFieldVal('tcpmss', false),
  3860. tos: document.getElementById('nat-val-tos')?.value || '',
  3861. packet_size: getNATFieldVal('pktsize', false),
  3862. random: getNATFieldVal('random', false),
  3863. icmp_options: getNATFieldVal('icmpoptions', false),
  3864. ipv4_options: getNATFieldVal('ipv4options', false),
  3865. ttl: getNATFieldVal('ttl', false),
  3866. // Extra tab
  3867. time: getNATFieldVal('time', false),
  3868. limit: getNATFieldVal('limit', false),
  3869. dst_limit: getNATFieldVal('dstlimit', false),
  3870. psd: getNATFieldVal('psd', false),
  3871. // Action tab
  3872. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3873. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3874. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3875. log: document.getElementById('nat-modal-log')?.checked || false,
  3876. log_prefix: getNATFieldVal('logprefix', false)
  3877. };
  3878. try {
  3879. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3880. method: 'POST',
  3881. headers: { 'Content-Type': 'application/json' },
  3882. body: JSON.stringify(payload)
  3883. });
  3884. if (res.ok) {
  3885. const data = await res.json();
  3886. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3887. loadFirewall(false);
  3888. if (closeAfter) {
  3889. closeNATModal();
  3890. } else {
  3891. if (data.id) {
  3892. document.getElementById('nat-modal-id').value = data.id;
  3893. const badge = document.getElementById('nat-modal-badge');
  3894. if (badge) badge.innerText = `#${data.id}`;
  3895. }
  3896. }
  3897. } else {
  3898. const err = await res.json();
  3899. showToast('Error', err.message || 'Failed to save rule', 'error');
  3900. }
  3901. } catch (err) {
  3902. showToast('Error', err.message, 'error');
  3903. }
  3904. }
  3905. function submitSaveNATRule(e) {
  3906. if (e && e.preventDefault) e.preventDefault();
  3907. return applyNATRule(true);
  3908. }
  3909. function startNATStatPolling() {
  3910. stopNATStatPolling();
  3911. pollNATRuleStats();
  3912. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3913. }
  3914. function stopNATStatPolling() {
  3915. if (state.natStatInterval) {
  3916. clearInterval(state.natStatInterval);
  3917. state.natStatInterval = null;
  3918. }
  3919. }
  3920. async function pollNATRuleStats() {
  3921. const id = document.getElementById('nat-modal-id')?.value;
  3922. if (!id) {
  3923. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  3924. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  3925. return;
  3926. }
  3927. try {
  3928. const res = await fetch(`${API_BASE}/firewall/nat`);
  3929. if (!res.ok) return;
  3930. const rules = await res.json();
  3931. const r = rules.find(x => x.id === id);
  3932. if (!r) return;
  3933. const now = Date.now();
  3934. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  3935. state.natLastTimestamp = now;
  3936. const curBytes = r.bytes || 0;
  3937. const curPackets = r.packets || 0;
  3938. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  3939. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  3940. state.natLastBytes = curBytes;
  3941. state.natLastPackets = curPackets;
  3942. const rateBps = Math.round((deltaBytes * 8) / dt);
  3943. const ratePkt = Math.round(deltaPkts / dt);
  3944. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  3945. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  3946. state.natStatRateHistory.push(rateBps);
  3947. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  3948. state.natStatPktHistory.push(ratePkt);
  3949. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  3950. const bEl = document.getElementById('nat-stat-bytes');
  3951. const pEl = document.getElementById('nat-stat-packets');
  3952. const rEl = document.getElementById('nat-stat-rate');
  3953. const prEl = document.getElementById('nat-stat-pktrate');
  3954. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3955. if (pEl) pEl.value = curPackets.toLocaleString();
  3956. if (rEl) rEl.value = formatBps(rateBps);
  3957. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3958. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3959. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3960. } catch (e) {
  3961. console.error('Error polling NAT rule stats', e);
  3962. }
  3963. }
  3964. async function moveNATRule(id, dir) {
  3965. try {
  3966. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  3967. method: 'POST',
  3968. headers: { 'Content-Type': 'application/json' },
  3969. body: JSON.stringify({ direction: dir })
  3970. });
  3971. if (res.ok) loadFirewall(false);
  3972. } catch (err) {
  3973. showToast('Error', err.message, 'error');
  3974. }
  3975. }
  3976. async function toggleNATRuleState(id, disabled) {
  3977. try {
  3978. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  3979. method: 'POST',
  3980. headers: { 'Content-Type': 'application/json' },
  3981. body: JSON.stringify({ disabled })
  3982. });
  3983. if (res.ok) loadFirewall(false);
  3984. } catch (err) {
  3985. showToast('Error', err.message, 'error');
  3986. }
  3987. }
  3988. async function deleteNATRule(id) {
  3989. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  3990. try {
  3991. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3992. if (res.ok) {
  3993. showToast('Deleted', 'NAT rule removed', 'success');
  3994. loadFirewall(false);
  3995. }
  3996. } catch (err) {
  3997. showToast('Error', err.message, 'error');
  3998. }
  3999. }
  4000. // ----------------- Mangle Rules -----------------
  4001. function renderMangleRules() {
  4002. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4003. const tbody = document.getElementById('mangle-table-body');
  4004. const empty = document.getElementById('mangle-empty');
  4005. if (!tbody) return;
  4006. tbody.innerHTML = '';
  4007. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4008. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4009. if (rules.length === 0) {
  4010. empty?.classList.remove('hidden');
  4011. return;
  4012. }
  4013. empty?.classList.add('hidden');
  4014. rules.forEach((r, idx) => {
  4015. const tr = document.createElement('tr');
  4016. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4017. let markVal = '<span class="text-slate-500">-</span>';
  4018. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4019. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4020. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4021. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4022. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4023. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4024. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4025. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4026. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4027. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4028. 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>`;
  4029. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4030. tr.innerHTML = `
  4031. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4032. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4033. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4034. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4035. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4036. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4037. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4038. <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>
  4039. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4040. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4041. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4042. </td>
  4043. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4044. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4045. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4046. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4047. <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>
  4048. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4049. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4050. </td>
  4051. `;
  4052. tbody.appendChild(tr);
  4053. });
  4054. }
  4055. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4056. function switchMangleRuleTab(tab) {
  4057. state.activeMangleRuleTab = tab;
  4058. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4059. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4060. btn.classList.add('text-slate-400', 'border-transparent');
  4061. });
  4062. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4063. if (activeBtn) {
  4064. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4065. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4066. }
  4067. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4068. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4069. if (activePane) activePane.classList.remove('hidden');
  4070. if (tab === 'statistics') {
  4071. startMangleStatPolling();
  4072. } else {
  4073. stopMangleStatPolling();
  4074. }
  4075. }
  4076. function toggleMangleField(fieldKey, expand) {
  4077. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4078. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4079. if (!plusBtn || !fieldBox) return;
  4080. if (expand) {
  4081. plusBtn.classList.add('hidden');
  4082. fieldBox.classList.remove('hidden');
  4083. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4084. if (valInput) valInput.focus();
  4085. } else {
  4086. fieldBox.classList.add('hidden');
  4087. plusBtn.classList.remove('hidden');
  4088. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4089. if (valInput) {
  4090. if (valInput.tagName === 'SELECT') {
  4091. valInput.selectedIndex = 0;
  4092. } else {
  4093. valInput.value = '';
  4094. }
  4095. }
  4096. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4097. if (invInput) invInput.checked = false;
  4098. if (fieldKey === 'cs') {
  4099. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4100. const el = document.getElementById(id);
  4101. if (el) el.checked = false;
  4102. });
  4103. }
  4104. if (fieldKey === 'natstate') {
  4105. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4106. const el = document.getElementById(id);
  4107. if (el) el.checked = false;
  4108. });
  4109. }
  4110. }
  4111. }
  4112. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4113. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4114. toggleMangleField(fieldKey, true);
  4115. let strVal = String(value);
  4116. if (hasInvert) {
  4117. const inv = strVal.startsWith('!');
  4118. if (inv) strVal = strVal.slice(1);
  4119. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4120. if (invEl) invEl.checked = inv;
  4121. }
  4122. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4123. if (valEl) valEl.value = strVal;
  4124. } else {
  4125. toggleMangleField(fieldKey, false);
  4126. }
  4127. }
  4128. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4129. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4130. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4131. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4132. let v = valEl ? valEl.value.trim() : '';
  4133. if (!v) return '';
  4134. if (hasInvert) {
  4135. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4136. if (invEl && invEl.checked) {
  4137. v = '!' + v.replace(/^!/, '');
  4138. }
  4139. }
  4140. return v;
  4141. }
  4142. function toggleMaximizeMangleModal() {
  4143. const win = document.getElementById('mangle-modal-window');
  4144. if (!win) return;
  4145. if (win.classList.contains('max-w-[720px]')) {
  4146. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4147. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4148. } else {
  4149. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4150. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4151. }
  4152. }
  4153. function toggleMangleActionFields() {
  4154. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4155. // Hide all dynamic rows first
  4156. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4157. const el = document.getElementById(`mangle-row-${id}`);
  4158. if (el) el.classList.add('hidden');
  4159. });
  4160. const jumpBox = document.getElementById('mangle-action-jump-box');
  4161. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4162. if (jumpBox) jumpBox.classList.add('hidden');
  4163. if (addrBox) addrBox.classList.add('hidden');
  4164. // Activate matching rows
  4165. if (act === 'mark-connection') {
  4166. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4167. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4168. } else if (act === 'mark-routing') {
  4169. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4170. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4171. } else if (act === 'mark-packet') {
  4172. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4173. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4174. } else if (act === 'change-mss') {
  4175. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4176. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4177. } else if (act === 'change-dscp') {
  4178. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4179. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4180. } else if (act === 'change-ttl') {
  4181. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4182. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4183. } else if (act === 'set-priority') {
  4184. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4185. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4186. } else if (act === 'route') {
  4187. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4188. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4189. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4190. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4191. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4192. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4193. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4194. } else if (act === 'jump') {
  4195. if (jumpBox) jumpBox.classList.remove('hidden');
  4196. } else if (act.includes('address-list') || act.includes('address list')) {
  4197. if (addrBox) addrBox.classList.remove('hidden');
  4198. }
  4199. if (act === 'log') {
  4200. const logEl = document.getElementById('mangle-modal-log');
  4201. if (logEl) logEl.checked = true;
  4202. toggleMangleField('logprefix', true);
  4203. }
  4204. }
  4205. function toggleMangleLogPrefix() {
  4206. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4207. toggleMangleField('logprefix', !!isLog);
  4208. }
  4209. const allMangleFieldKeys = [
  4210. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4211. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4212. 'routingmark', 'conntype', 'cs', 'natstate',
  4213. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4214. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4215. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4216. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4217. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4218. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4219. ];
  4220. function openAddMangleModal() {
  4221. switchMangleRuleTab('general');
  4222. const badge = document.getElementById('mangle-modal-badge');
  4223. if (badge) badge.innerText = 'New...';
  4224. document.getElementById('mangle-modal-id').value = '';
  4225. document.getElementById('mangle-modal-enabled').checked = true;
  4226. document.getElementById('mangle-modal-comment').value = '';
  4227. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4228. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4229. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4230. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4231. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4232. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4233. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4234. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4235. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4236. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4237. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4238. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4239. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4240. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4241. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4242. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4243. populateInterfaceSelect('mangle-val-iniface');
  4244. populateInterfaceSelect('mangle-val-outiface');
  4245. populateAddressListSelect('mangle-val-srclist');
  4246. populateAddressListSelect('mangle-val-dstlist');
  4247. populateGeoIPSelect('mangle-val-srcgeo');
  4248. populateGeoIPSelect('mangle-val-dstgeo');
  4249. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4250. resetCurrentMangleRuleCounters();
  4251. toggleMangleActionFields();
  4252. document.getElementById('mangle-modal').classList.remove('hidden');
  4253. }
  4254. function openEditMangleModal(id) {
  4255. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4256. if (!r) return;
  4257. switchMangleRuleTab('general');
  4258. const badge = document.getElementById('mangle-modal-badge');
  4259. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4260. document.getElementById('mangle-modal-id').value = r.id;
  4261. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4262. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4263. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4264. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4265. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4266. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4267. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4268. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4269. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4270. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4271. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4272. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4273. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4274. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4275. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4276. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4277. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4278. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4279. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4280. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4281. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4282. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4283. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4284. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4285. setMangleFieldVal('src', r.src_address, true);
  4286. setMangleFieldVal('dst', r.dst_address, true);
  4287. setMangleFieldVal('srclist', r.src_address_list, true);
  4288. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4289. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4290. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4291. if (r.protocol && r.protocol !== 'all') {
  4292. setMangleFieldVal('proto', r.protocol, true);
  4293. } else {
  4294. toggleMangleField('proto', false);
  4295. }
  4296. setMangleFieldVal('sport', r.src_port, true);
  4297. setMangleFieldVal('dport', r.dst_port, true);
  4298. setMangleFieldVal('anyport', r.any_port, true);
  4299. setMangleFieldVal('iniface', r.in_interface, true);
  4300. setMangleFieldVal('outiface', r.out_interface, true);
  4301. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4302. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4303. setMangleFieldVal('pktmark', r.packet_mark, true);
  4304. setMangleFieldVal('connmark', r.connection_mark, true);
  4305. setMangleFieldVal('routingmark', r.routing_mark, true);
  4306. setMangleFieldVal('conntype', r.connection_type, false);
  4307. // Connection State
  4308. const states = r.connection_state || [];
  4309. if (states.length > 0) {
  4310. toggleMangleField('cs', true);
  4311. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4312. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4313. if (el) el.checked = states.includes(s);
  4314. });
  4315. } else {
  4316. toggleMangleField('cs', false);
  4317. }
  4318. // Connection NAT State
  4319. const natStates = r.connection_nat_state || [];
  4320. if (natStates.length > 0) {
  4321. toggleMangleField('natstate', true);
  4322. ['srcnat', 'dstnat'].forEach(s => {
  4323. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4324. if (el) el.checked = natStates.includes(s);
  4325. });
  4326. } else {
  4327. toggleMangleField('natstate', false);
  4328. }
  4329. // Advanced tab fields
  4330. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4331. setMangleFieldVal('content', r.content, false);
  4332. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4333. setMangleFieldVal('connrate', r.connection_rate, false);
  4334. setMangleFieldVal('pcc', r.pcc, false);
  4335. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4336. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4337. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4338. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4339. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4340. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4341. setMangleFieldVal('tlshost', r.tls_host, false);
  4342. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4343. setMangleFieldVal('priority', r.priority, false);
  4344. setMangleFieldVal('dscp', r.dscp, false);
  4345. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4346. if (r.tos) {
  4347. const tosEl = document.getElementById('mangle-val-tos');
  4348. if (tosEl) tosEl.value = r.tos;
  4349. }
  4350. setMangleFieldVal('pktsize', r.packet_size, false);
  4351. setMangleFieldVal('random', r.random, false);
  4352. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4353. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4354. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4355. setMangleFieldVal('ttl', r.ttl, false);
  4356. // Extra tab fields
  4357. setMangleFieldVal('nth', r.nth, false);
  4358. setMangleFieldVal('connlimit', r.connection_limit, false);
  4359. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4360. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4361. setMangleFieldVal('hotspot', r.hotspot, false);
  4362. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4363. setMangleFieldVal('limit', r.limit, false);
  4364. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4365. setMangleFieldVal('time', r.time, false);
  4366. setMangleFieldVal('psd', r.psd, false);
  4367. // Action fields
  4368. if (r.jump_target) {
  4369. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4370. if (jtEl) jtEl.value = r.jump_target;
  4371. }
  4372. if (r.address_list) {
  4373. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4374. if (alEl) alEl.value = r.address_list;
  4375. }
  4376. if (r.address_list_timeout) {
  4377. const toEl = document.getElementById('mangle-modal-action-timeout');
  4378. if (toEl) toEl.value = r.address_list_timeout;
  4379. }
  4380. setMangleFieldVal('logprefix', r.log_prefix, false);
  4381. // Statistics
  4382. const bEl = document.getElementById('mangle-stat-bytes');
  4383. const pEl = document.getElementById('mangle-stat-packets');
  4384. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4385. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4386. state.mangleLastBytes = r.bytes || 0;
  4387. state.mangleLastPackets = r.packets || 0;
  4388. state.mangleLastTimestamp = Date.now();
  4389. state.mangleStatRateHistory = new Array(30).fill(0);
  4390. state.mangleStatPktHistory = new Array(30).fill(0);
  4391. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4392. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4393. toggleMangleActionFields();
  4394. document.getElementById('mangle-modal').classList.remove('hidden');
  4395. }
  4396. function closeMangleModal() {
  4397. stopMangleStatPolling();
  4398. document.getElementById('mangle-modal').classList.add('hidden');
  4399. }
  4400. function copyMangleRule() {
  4401. document.getElementById('mangle-modal-id').value = '';
  4402. const badge = document.getElementById('mangle-modal-badge');
  4403. if (badge) badge.innerText = 'New...';
  4404. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4405. }
  4406. function resetCurrentMangleRuleCounters() {
  4407. state.mangleStatRateHistory = new Array(30).fill(0);
  4408. state.mangleStatPktHistory = new Array(30).fill(0);
  4409. state.mangleLastBytes = 0;
  4410. state.mangleLastPackets = 0;
  4411. state.mangleLastTimestamp = Date.now();
  4412. const bEl = document.getElementById('mangle-stat-bytes');
  4413. const pEl = document.getElementById('mangle-stat-packets');
  4414. const rEl = document.getElementById('mangle-stat-rate');
  4415. const prEl = document.getElementById('mangle-stat-pktrate');
  4416. if (bEl) bEl.value = '0 B';
  4417. if (pEl) pEl.value = '0';
  4418. if (rEl) rEl.value = '0 bps';
  4419. if (prEl) prEl.value = '0 p/s';
  4420. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4421. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4422. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4423. }
  4424. async function applyMangleRule(closeAfter = false) {
  4425. const id = document.getElementById('mangle-modal-id').value;
  4426. const chain = document.getElementById('mangle-modal-chain').value;
  4427. const action = document.getElementById('mangle-modal-action').value;
  4428. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4429. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4430. const src = getMangleFieldVal('src', true);
  4431. const dst = getMangleFieldVal('dst', true);
  4432. const srclist = getMangleFieldVal('srclist', true);
  4433. const dstlist = getMangleFieldVal('dstlist', true);
  4434. const srcgeo = getMangleFieldVal('srcgeo', true);
  4435. const dstgeo = getMangleFieldVal('dstgeo', true);
  4436. const proto = getMangleFieldVal('proto', true);
  4437. const sport = getMangleFieldVal('sport', true);
  4438. const dport = getMangleFieldVal('dport', true);
  4439. const anyport = getMangleFieldVal('anyport', true);
  4440. const iniface = getMangleFieldVal('iniface', true);
  4441. const outiface = getMangleFieldVal('outiface', true);
  4442. const inifacelist = getMangleFieldVal('inifacelist', true);
  4443. const outifacelist = getMangleFieldVal('outifacelist', true);
  4444. const pktmark = getMangleFieldVal('pktmark', true);
  4445. const connmark = getMangleFieldVal('connmark', true);
  4446. const routingmark = getMangleFieldVal('routingmark', true);
  4447. const conntype = getMangleFieldVal('conntype', false);
  4448. const states = [];
  4449. const csBox = document.getElementById('mangle-field-cs');
  4450. if (csBox && !csBox.classList.contains('hidden')) {
  4451. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4452. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4453. });
  4454. }
  4455. const natStates = [];
  4456. const natBox = document.getElementById('mangle-field-natstate');
  4457. if (natBox && !natBox.classList.contains('hidden')) {
  4458. ['srcnat', 'dstnat'].forEach(s => {
  4459. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4460. });
  4461. }
  4462. const payload = {
  4463. id,
  4464. chain,
  4465. action,
  4466. protocol: proto || 'all',
  4467. src_address: src,
  4468. dst_address: dst,
  4469. src_port: sport,
  4470. dst_port: dport,
  4471. any_port: anyport,
  4472. in_interface: iniface,
  4473. out_interface: outiface,
  4474. in_interface_list: inifacelist,
  4475. out_interface_list: outifacelist,
  4476. packet_mark: pktmark,
  4477. connection_mark: connmark,
  4478. routing_mark: routingmark,
  4479. connection_type: conntype,
  4480. connection_state: states,
  4481. connection_nat_state: natStates,
  4482. src_address_list: srclist,
  4483. dst_address_list: dstlist,
  4484. src_geoip: srcgeo,
  4485. dst_geoip: dstgeo,
  4486. comment,
  4487. disabled: !enabled,
  4488. // Advanced tab
  4489. layer7_protocol: getMangleFieldVal('layer7', false),
  4490. content: getMangleFieldVal('content', false),
  4491. connection_bytes: getMangleFieldVal('connbytes', false),
  4492. connection_rate: getMangleFieldVal('connrate', false),
  4493. pcc: getMangleFieldVal('pcc', false),
  4494. src_mac_address: getMangleFieldVal('srcmac', true),
  4495. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4496. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4497. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4498. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4499. ipsec_policy: getMangleFieldVal('ipsec', false),
  4500. tls_host: getMangleFieldVal('tlshost', false),
  4501. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4502. priority: getMangleFieldVal('priority', false),
  4503. dscp: getMangleFieldVal('dscp', false),
  4504. tcp_mss: getMangleFieldVal('tcpmss', false),
  4505. tos: document.getElementById('mangle-val-tos')?.value || '',
  4506. packet_size: getMangleFieldVal('pktsize', false),
  4507. random: getMangleFieldVal('random', false),
  4508. tcp_flags: getMangleFieldVal('tcpflags', false),
  4509. icmp_options: getMangleFieldVal('icmpoptions', false),
  4510. ipv4_options: getMangleFieldVal('ipv4options', false),
  4511. ttl: getMangleFieldVal('ttl', false),
  4512. // Extra tab
  4513. nth: getMangleFieldVal('nth', false),
  4514. connection_limit: getMangleFieldVal('connlimit', false),
  4515. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4516. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4517. hotspot: getMangleFieldVal('hotspot', false),
  4518. ip_fragment: getMangleFieldVal('ipfragment', false),
  4519. limit: getMangleFieldVal('limit', false),
  4520. dst_limit: getMangleFieldVal('dstlimit', false),
  4521. time: getMangleFieldVal('time', false),
  4522. psd: getMangleFieldVal('psd', false),
  4523. // Action tab
  4524. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4525. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4526. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4527. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4528. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4529. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4530. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4531. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4532. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4533. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4534. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4535. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4536. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4537. log: document.getElementById('mangle-modal-log')?.checked || false,
  4538. log_prefix: getMangleFieldVal('logprefix', false)
  4539. };
  4540. try {
  4541. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4542. method: 'POST',
  4543. headers: { 'Content-Type': 'application/json' },
  4544. body: JSON.stringify(payload)
  4545. });
  4546. if (res.ok) {
  4547. const data = await res.json();
  4548. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4549. loadFirewall(false);
  4550. if (closeAfter) {
  4551. closeMangleModal();
  4552. } else {
  4553. if (data.id) {
  4554. document.getElementById('mangle-modal-id').value = data.id;
  4555. const badge = document.getElementById('mangle-modal-badge');
  4556. if (badge) badge.innerText = `#${data.id}`;
  4557. }
  4558. }
  4559. } else {
  4560. const err = await res.json();
  4561. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4562. }
  4563. } catch (err) {
  4564. showToast('Error', err.message, 'error');
  4565. }
  4566. }
  4567. function submitSaveMangleRule(e) {
  4568. if (e && e.preventDefault) e.preventDefault();
  4569. return applyMangleRule(true);
  4570. }
  4571. function startMangleStatPolling() {
  4572. stopMangleStatPolling();
  4573. pollMangleRuleStats();
  4574. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4575. }
  4576. function stopMangleStatPolling() {
  4577. if (state.mangleStatInterval) {
  4578. clearInterval(state.mangleStatInterval);
  4579. state.mangleStatInterval = null;
  4580. }
  4581. }
  4582. async function pollMangleRuleStats() {
  4583. const id = document.getElementById('mangle-modal-id')?.value;
  4584. if (!id) {
  4585. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4586. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4587. return;
  4588. }
  4589. try {
  4590. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4591. if (!res.ok) return;
  4592. const rules = await res.json();
  4593. const r = rules.find(x => x.id === id);
  4594. if (!r) return;
  4595. const now = Date.now();
  4596. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4597. state.mangleLastTimestamp = now;
  4598. const curBytes = r.bytes || 0;
  4599. const curPackets = r.packets || 0;
  4600. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4601. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4602. state.mangleLastBytes = curBytes;
  4603. state.mangleLastPackets = curPackets;
  4604. const rateBps = Math.round((deltaBytes * 8) / dt);
  4605. const ratePkt = Math.round(deltaPkts / dt);
  4606. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4607. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4608. state.mangleStatRateHistory.push(rateBps);
  4609. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4610. state.mangleStatPktHistory.push(ratePkt);
  4611. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4612. const bEl = document.getElementById('mangle-stat-bytes');
  4613. const pEl = document.getElementById('mangle-stat-packets');
  4614. const rEl = document.getElementById('mangle-stat-rate');
  4615. const prEl = document.getElementById('mangle-stat-pktrate');
  4616. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4617. if (pEl) pEl.value = curPackets.toLocaleString();
  4618. if (rEl) rEl.value = formatBps(rateBps);
  4619. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4620. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4621. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4622. } catch (e) {
  4623. console.error('Error polling Mangle rule stats', e);
  4624. }
  4625. }
  4626. async function moveMangleRule(id, dir) {
  4627. try {
  4628. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4629. method: 'POST',
  4630. headers: { 'Content-Type': 'application/json' },
  4631. body: JSON.stringify({ direction: dir })
  4632. });
  4633. if (res.ok) loadFirewall(false);
  4634. } catch (err) {
  4635. showToast('Error', err.message, 'error');
  4636. }
  4637. }
  4638. async function toggleMangleRuleState(id, disabled) {
  4639. try {
  4640. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4641. method: 'POST',
  4642. headers: { 'Content-Type': 'application/json' },
  4643. body: JSON.stringify({ disabled })
  4644. });
  4645. if (res.ok) loadFirewall(false);
  4646. } catch (err) {
  4647. showToast('Error', err.message, 'error');
  4648. }
  4649. }
  4650. async function deleteMangleRule(id) {
  4651. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4652. try {
  4653. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4654. if (res.ok) {
  4655. showToast('Deleted', 'Mangle rule removed', 'success');
  4656. loadFirewall(false);
  4657. }
  4658. } catch (err) {
  4659. showToast('Error', err.message, 'error');
  4660. }
  4661. }
  4662. // ----------------- Address Lists -----------------
  4663. function renderAddressLists() {
  4664. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4665. const tbody = document.getElementById('addrlist-table-body');
  4666. const empty = document.getElementById('addrlist-empty');
  4667. if (!tbody) return;
  4668. tbody.innerHTML = '';
  4669. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4670. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4671. // Update filter select
  4672. const sel = document.getElementById('addrlist-filter-name');
  4673. if (sel) {
  4674. const cur = sel.value;
  4675. sel.innerHTML = '<option value="">All Lists</option>';
  4676. const set = new Set((state.addressLists || []).map(a => a.name));
  4677. set.forEach(n => {
  4678. const opt = document.createElement('option');
  4679. opt.value = n;
  4680. opt.innerText = n;
  4681. if (n === cur) opt.selected = true;
  4682. sel.appendChild(opt);
  4683. });
  4684. }
  4685. if (entries.length === 0) {
  4686. empty?.classList.remove('hidden');
  4687. return;
  4688. }
  4689. empty?.classList.add('hidden');
  4690. entries.forEach((e, idx) => {
  4691. const tr = document.createElement('tr');
  4692. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4693. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4694. tr.innerHTML = `
  4695. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4696. <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>
  4697. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4698. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4699. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4700. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4701. <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>
  4702. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4703. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4704. </td>
  4705. `;
  4706. tbody.appendChild(tr);
  4707. });
  4708. populateCommonAddrListDatalist();
  4709. }
  4710. function openAddAddrListModal() {
  4711. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4712. document.getElementById('addrlist-modal-id').value = '';
  4713. document.getElementById('addrlist-modal-name').value = '';
  4714. document.getElementById('addrlist-modal-addr').value = '';
  4715. document.getElementById('addrlist-modal-comment').value = '';
  4716. document.getElementById('addrlist-modal-disabled').checked = false;
  4717. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4718. if (submitBtn) submitBtn.innerText = 'Add to List';
  4719. document.getElementById('addrlist-modal').classList.remove('hidden');
  4720. }
  4721. function openEditAddrListModal(id) {
  4722. const e = (state.addressLists || []).find(item => item.id === id);
  4723. if (!e) return;
  4724. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4725. document.getElementById('addrlist-modal-id').value = e.id;
  4726. document.getElementById('addrlist-modal-name').value = e.name;
  4727. document.getElementById('addrlist-modal-addr').value = e.address;
  4728. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4729. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4730. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4731. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4732. document.getElementById('addrlist-modal').classList.remove('hidden');
  4733. }
  4734. function closeAddrListModal() {
  4735. document.getElementById('addrlist-modal').classList.add('hidden');
  4736. }
  4737. async function submitSaveAddrList(e) {
  4738. e.preventDefault();
  4739. const id = document.getElementById('addrlist-modal-id').value;
  4740. const name = document.getElementById('addrlist-modal-name').value.trim();
  4741. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4742. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4743. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4744. try {
  4745. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4746. method: 'POST',
  4747. headers: { 'Content-Type': 'application/json' },
  4748. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4749. });
  4750. if (res.ok) {
  4751. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4752. closeAddrListModal();
  4753. loadFirewall(false);
  4754. } else {
  4755. const err = await res.json();
  4756. showToast('Error', err.message || 'Failed to save address list', 'error');
  4757. }
  4758. } catch (err) {
  4759. showToast('Error', err.message, 'error');
  4760. }
  4761. }
  4762. async function toggleAddrListState(id, disabled) {
  4763. try {
  4764. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4765. method: 'POST',
  4766. headers: { 'Content-Type': 'application/json' },
  4767. body: JSON.stringify({ disabled })
  4768. });
  4769. if (res.ok) {
  4770. loadFirewall(false);
  4771. }
  4772. } catch (err) {
  4773. showToast('Error', err.message, 'error');
  4774. }
  4775. }
  4776. async function deleteAddrList(id) {
  4777. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4778. try {
  4779. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4780. if (res.ok) {
  4781. showToast('Deleted', 'Address list item removed', 'info');
  4782. loadFirewall(false);
  4783. }
  4784. } catch (err) {
  4785. showToast('Error', err.message, 'error');
  4786. }
  4787. }
  4788. // ----------------- Geo-Location IP Management -----------------
  4789. async function loadGeoIP() {
  4790. try {
  4791. const [statusRes, countriesRes] = await Promise.all([
  4792. fetch(`${API_BASE}/firewall/geoip/status`),
  4793. fetch(`${API_BASE}/firewall/geoip/countries`)
  4794. ]);
  4795. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4796. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4797. updateGeoHeader();
  4798. renderGeoCountries();
  4799. } catch (err) {
  4800. console.error('Failed to load GeoIP:', err);
  4801. }
  4802. }
  4803. function getGeoUsageMap() {
  4804. const usage = {};
  4805. const checkRule = (r, type) => {
  4806. ['src_geoip', 'dst_geoip'].forEach(field => {
  4807. let val = (r && r[field]) || '';
  4808. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4809. if (code) {
  4810. if (!usage[code]) usage[code] = [];
  4811. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4812. if (!usage[code].includes(label)) usage[code].push(label);
  4813. }
  4814. });
  4815. };
  4816. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4817. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4818. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4819. return usage;
  4820. }
  4821. function updateGeoHeader() {
  4822. const s = state.geoStatus || {};
  4823. const statusBadge = document.getElementById('geo-status-badge');
  4824. if (statusBadge) {
  4825. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4826. statusBadge.className = s.auto_update
  4827. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4828. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4829. }
  4830. const intervalLabel = document.getElementById('geo-interval-label');
  4831. if (intervalLabel) {
  4832. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4833. }
  4834. const usageMap = getGeoUsageMap();
  4835. const inUseCount = Object.keys(usageMap).length;
  4836. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4837. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4838. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4839. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4840. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4841. if (lastSyncEl) {
  4842. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4843. const d = new Date(s.last_updated);
  4844. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4845. } else {
  4846. lastSyncEl.innerText = 'Never (Sync Pending)';
  4847. }
  4848. }
  4849. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4850. if (nextSyncEl) {
  4851. if (s.next_update && !s.next_update.startsWith('0001')) {
  4852. const d = new Date(s.next_update);
  4853. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4854. } else {
  4855. nextSyncEl.innerText = '-';
  4856. }
  4857. }
  4858. const badge = document.getElementById('fw-badge-geo');
  4859. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4860. }
  4861. function renderGeoCountries() {
  4862. const tbody = document.getElementById('geo-table-body');
  4863. const empty = document.getElementById('geo-empty');
  4864. if (!tbody) return;
  4865. tbody.innerHTML = '';
  4866. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4867. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4868. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4869. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4870. const usageMap = getGeoUsageMap();
  4871. const countries = (state.geoCountries || []).filter(c => {
  4872. const isUsed = !!usageMap[c.code];
  4873. if (inUseOnly && !isUsed) return false;
  4874. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4875. if (continent && c.continent !== continent) return false;
  4876. if (q) {
  4877. const matchCode = c.code.toLowerCase().includes(q);
  4878. const matchName = c.name.toLowerCase().includes(q);
  4879. if (!matchCode && !matchName) return false;
  4880. }
  4881. return true;
  4882. });
  4883. if (countries.length === 0) {
  4884. empty?.classList.remove('hidden');
  4885. return;
  4886. }
  4887. empty?.classList.add('hidden');
  4888. countries.forEach(c => {
  4889. const tr = document.createElement('tr');
  4890. const isUsed = !!usageMap[c.code];
  4891. const rulesUsing = usageMap[c.code] || [];
  4892. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4893. let statusHtml = '';
  4894. if (isUsed) {
  4895. 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>`;
  4896. } else if (c.subnet_count > 0) {
  4897. 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>';
  4898. } else {
  4899. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4900. }
  4901. tr.innerHTML = `
  4902. <td class="py-2.5 px-3 text-center">
  4903. <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'}">
  4904. ${c.code}
  4905. </span>
  4906. </td>
  4907. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4908. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4909. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4910. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4911. </td>
  4912. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4913. <td class="py-2.5 px-3">
  4914. ${statusHtml}
  4915. </td>
  4916. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4917. <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>
  4918. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4919. </td>
  4920. `;
  4921. tbody.appendChild(tr);
  4922. });
  4923. }
  4924. function quickFilterGeo(preset) {
  4925. const searchInput = document.getElementById('geo-search-input');
  4926. const continentSel = document.getElementById('geo-continent-filter');
  4927. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  4928. const cachedCheck = document.getElementById('geo-filter-cached-only');
  4929. if (searchInput) searchInput.value = '';
  4930. if (continentSel) continentSel.value = '';
  4931. if (inUseCheck) inUseCheck.checked = false;
  4932. if (cachedCheck) cachedCheck.checked = false;
  4933. if (preset === 'GR') {
  4934. if (searchInput) searchInput.value = 'Greece';
  4935. } else if (preset === 'Europe') {
  4936. if (continentSel) continentSel.value = 'Europe';
  4937. } else if (preset === 'HIGHRISK') {
  4938. if (searchInput) searchInput.value = 'China';
  4939. }
  4940. renderGeoCountries();
  4941. }
  4942. async function toggleGeoCountry(code, enabled) {
  4943. try {
  4944. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  4945. method: 'POST',
  4946. headers: { 'Content-Type': 'application/json' },
  4947. body: JSON.stringify({ enabled })
  4948. });
  4949. if (res.ok) {
  4950. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  4951. loadGeoIP();
  4952. } else {
  4953. const err = await res.json();
  4954. showToast('Error', err.message || 'Failed to toggle country', 'error');
  4955. }
  4956. } catch (err) {
  4957. showToast('Error', err.message, 'error');
  4958. }
  4959. }
  4960. async function updateGeoCountry(code) {
  4961. try {
  4962. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  4963. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  4964. if (res.ok) {
  4965. const data = await res.json();
  4966. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  4967. loadGeoIP();
  4968. } else {
  4969. const err = await res.json();
  4970. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  4971. }
  4972. } catch (err) {
  4973. showToast('Error', err.message, 'error');
  4974. }
  4975. }
  4976. async function triggerGeoUpdateNow() {
  4977. const spinner = document.getElementById('geo-update-spinner');
  4978. if (spinner) spinner.classList.remove('hidden');
  4979. try {
  4980. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  4981. if (res.ok) {
  4982. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  4983. setTimeout(() => {
  4984. loadGeoIP();
  4985. if (spinner) spinner.classList.add('hidden');
  4986. }, 2500);
  4987. } else {
  4988. const err = await res.json();
  4989. showToast('Notice', err.message || 'Update in progress', 'info');
  4990. if (spinner) spinner.classList.add('hidden');
  4991. }
  4992. } catch (err) {
  4993. showToast('Error', err.message, 'error');
  4994. if (spinner) spinner.classList.add('hidden');
  4995. }
  4996. }
  4997. async function applyGeoPreset(preset) {
  4998. try {
  4999. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5000. method: 'POST',
  5001. headers: { 'Content-Type': 'application/json' },
  5002. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5003. });
  5004. if (res.ok) {
  5005. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5006. loadGeoIP();
  5007. }
  5008. } catch (err) {
  5009. showToast('Error', err.message, 'error');
  5010. }
  5011. }
  5012. function openGeoIntervalModal() {
  5013. const s = state.geoStatus || {};
  5014. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5015. const sel = document.getElementById('geo-cfg-interval');
  5016. const customBox = document.getElementById('geo-cfg-custom-box');
  5017. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5018. const curHours = s.interval_hours || 24;
  5019. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5020. if (matchOption) {
  5021. sel.value = String(curHours);
  5022. customBox.classList.add('hidden');
  5023. } else {
  5024. sel.value = 'custom';
  5025. customHoursInput.value = curHours;
  5026. customBox.classList.remove('hidden');
  5027. }
  5028. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5029. }
  5030. function closeGeoIntervalModal() {
  5031. document.getElementById('geo-interval-modal').classList.add('hidden');
  5032. }
  5033. function toggleCustomGeoInterval() {
  5034. const val = document.getElementById('geo-cfg-interval').value;
  5035. const customBox = document.getElementById('geo-cfg-custom-box');
  5036. if (val === 'custom') {
  5037. customBox.classList.remove('hidden');
  5038. } else {
  5039. customBox.classList.add('hidden');
  5040. }
  5041. }
  5042. async function submitGeoIntervalSettings(e) {
  5043. e.preventDefault();
  5044. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5045. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5046. let hours = 24;
  5047. if (intervalVal === 'custom') {
  5048. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5049. } else {
  5050. hours = parseInt(intervalVal, 10) || 24;
  5051. }
  5052. try {
  5053. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5054. method: 'POST',
  5055. headers: { 'Content-Type': 'application/json' },
  5056. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5057. });
  5058. if (res.ok) {
  5059. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5060. closeGeoIntervalModal();
  5061. loadGeoIP();
  5062. } else {
  5063. const err = await res.json();
  5064. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5065. }
  5066. } catch (err) {
  5067. showToast('Error', err.message, 'error');
  5068. }
  5069. }
  5070. async function viewGeoSubnets(code, name) {
  5071. if (!name) {
  5072. const found = (state.geoCountries || []).find(x => x.code === code);
  5073. name = found ? found.name : code;
  5074. }
  5075. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5076. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5077. const listEl = document.getElementById('geo-subnets-list');
  5078. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5079. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5080. try {
  5081. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5082. if (res.ok) {
  5083. const data = await res.json();
  5084. const subnets = data.subnets || [];
  5085. if (subnets.length === 0) {
  5086. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5087. } else {
  5088. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5089. }
  5090. } else {
  5091. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5092. }
  5093. } catch (err) {
  5094. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5095. }
  5096. }
  5097. function closeGeoSubnetsModal() {
  5098. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5099. }
  5100. // ----------------- Active Connections Tracking -----------------
  5101. async function loadConnections() {
  5102. try {
  5103. const res = await fetch(`${API_BASE}/firewall/connections`);
  5104. const data = await res.json();
  5105. state.connections = Array.isArray(data) ? data : [];
  5106. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5107. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5108. renderConnections();
  5109. } catch (err) {
  5110. console.error('Failed to load connections:', err);
  5111. }
  5112. }
  5113. function renderConnections() {
  5114. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5115. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5116. const tbody = document.getElementById('conns-table-body');
  5117. const empty = document.getElementById('conns-empty');
  5118. if (!tbody) return;
  5119. tbody.innerHTML = '';
  5120. const conns = (state.connections || []).filter(c => {
  5121. if (protoFilter && c.protocol !== protoFilter) return false;
  5122. if (search) {
  5123. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5124. if (!line.includes(search)) return false;
  5125. }
  5126. return true;
  5127. });
  5128. if (conns.length === 0) {
  5129. empty?.classList.remove('hidden');
  5130. return;
  5131. }
  5132. empty?.classList.add('hidden');
  5133. conns.slice(0, 150).forEach(c => {
  5134. const tr = document.createElement('tr');
  5135. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5136. let stateColor = 'text-slate-400';
  5137. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5138. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5139. tr.innerHTML = `
  5140. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5141. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5142. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5143. <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>
  5144. <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>
  5145. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5146. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5147. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5148. <td class="py-2.5 px-3 text-right font-sans">
  5149. <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>
  5150. </td>
  5151. `;
  5152. tbody.appendChild(tr);
  5153. });
  5154. }
  5155. async function killConnection(protocol, src, sport, dst, dport) {
  5156. try {
  5157. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5158. method: 'POST',
  5159. headers: { 'Content-Type': 'application/json' },
  5160. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5161. });
  5162. if (res.ok) {
  5163. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5164. loadConnections();
  5165. }
  5166. } catch (err) {
  5167. showToast('Error', err.message, 'error');
  5168. }
  5169. }
  5170. async function resetFirewallCounters() {
  5171. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5172. try {
  5173. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5174. if (res.ok) {
  5175. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5176. loadFirewall(false);
  5177. }
  5178. } catch (err) {
  5179. showToast('Error', err.message, 'error');
  5180. }
  5181. }
  5182. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5183. function switchRoutesSubTab(tab) {
  5184. state.routesSubTab = tab;
  5185. const tabs = ['routes', 'rules', 'tables'];
  5186. tabs.forEach(t => {
  5187. const panel = document.getElementById(`routes-subtab-${t}`);
  5188. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5189. if (panel) {
  5190. if (t === tab) panel.classList.remove('hidden');
  5191. else panel.classList.add('hidden');
  5192. }
  5193. if (btn) {
  5194. if (t === tab) {
  5195. 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';
  5196. } else {
  5197. 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';
  5198. }
  5199. }
  5200. });
  5201. setTimeout(initTableSorting, 50);
  5202. }
  5203. async function loadRoutes() {
  5204. try {
  5205. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5206. fetch(`${API_BASE}/routes`),
  5207. fetch(`${API_BASE}/routing/rules`),
  5208. fetch(`${API_BASE}/routing/tables`)
  5209. ]);
  5210. if (routesRes.ok) state.routes = await routesRes.json();
  5211. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5212. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5213. const bRoutes = document.getElementById('routes-badge-routes');
  5214. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5215. const showSystem = document.getElementById('prule-show-system')?.checked;
  5216. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5217. const bRules = document.getElementById('routes-badge-rules');
  5218. if (bRules) bRules.innerText = userRules.length;
  5219. const bTables = document.getElementById('routes-badge-tables');
  5220. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5221. const bRoutesCount = document.getElementById('badge-routes-count');
  5222. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5223. renderRoutesList();
  5224. renderPolicyRules();
  5225. renderRoutingTables();
  5226. } catch (err) {
  5227. console.error('Failed to load routing:', err);
  5228. }
  5229. }
  5230. function renderRoutesList() {
  5231. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5232. const tbody = document.getElementById('routes-table-body');
  5233. const empty = document.getElementById('routes-empty');
  5234. if (!tbody) return;
  5235. tbody.innerHTML = '';
  5236. // Update table filter select
  5237. const sel = document.getElementById('routes-filter-table');
  5238. if (sel) {
  5239. const cur = sel.value;
  5240. sel.innerHTML = '<option value="">All Tables</option>';
  5241. (state.routingTables || []).forEach(t => {
  5242. const opt = document.createElement('option');
  5243. opt.value = t.name;
  5244. opt.innerText = t.name;
  5245. if (t.name === cur) opt.selected = true;
  5246. sel.appendChild(opt);
  5247. });
  5248. }
  5249. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5250. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5251. if (routes.length === 0) {
  5252. empty?.classList.remove('hidden');
  5253. return;
  5254. }
  5255. empty?.classList.add('hidden');
  5256. routes.forEach(r => {
  5257. const tr = document.createElement('tr');
  5258. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5259. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5260. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5261. let flags = '';
  5262. if (r.dynamic) flags += 'D';
  5263. if (r.active) flags += 'A';
  5264. if (r.connect) flags += 'C';
  5265. if (r.static) flags += 'S';
  5266. if (r.disabled) flags += 'X';
  5267. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5268. tr.innerHTML = `
  5269. <td class="py-2.5 px-3 text-center">
  5270. <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'}">
  5271. ${flags || '-'}
  5272. </span>
  5273. </td>
  5274. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5275. <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>
  5276. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5277. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5278. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5279. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5280. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5281. ${r.static ? `
  5282. <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>
  5283. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5284. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5285. ` : `
  5286. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5287. `}
  5288. </td>
  5289. `;
  5290. tbody.appendChild(tr);
  5291. });
  5292. }
  5293. function openAddRouteModal() {
  5294. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5295. document.getElementById('route-modal-id').value = '';
  5296. document.getElementById('route-modal-old-dst').value = '';
  5297. document.getElementById('route-modal-old-gw').value = '';
  5298. document.getElementById('route-modal-old-distance').value = '';
  5299. document.getElementById('route-modal-old-table').value = '';
  5300. document.getElementById('route-modal-old-iface').value = '';
  5301. const dstInput = document.getElementById('route-modal-dst');
  5302. const gwInput = document.getElementById('route-modal-gw');
  5303. const distInput = document.getElementById('route-modal-distance');
  5304. const ifaceSelect = document.getElementById('route-modal-iface');
  5305. const tableSelect = document.getElementById('route-modal-table');
  5306. const commentInput = document.getElementById('route-modal-comment');
  5307. const disCheck = document.getElementById('route-modal-disabled');
  5308. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5309. dstInput.disabled = false;
  5310. dstInput.value = '0.0.0.0/0';
  5311. gwInput.disabled = false;
  5312. gwInput.value = '';
  5313. distInput.disabled = false;
  5314. distInput.value = '1';
  5315. ifaceSelect.disabled = false;
  5316. tableSelect.disabled = false;
  5317. commentInput.disabled = false;
  5318. commentInput.value = '';
  5319. disCheck.disabled = false;
  5320. disCheck.checked = false;
  5321. if (saveBtn) saveBtn.classList.remove('hidden');
  5322. populateInterfaceSelect('route-modal-iface');
  5323. // Populate tables
  5324. tableSelect.innerHTML = '';
  5325. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5326. const opt = document.createElement('option');
  5327. opt.value = t.name;
  5328. opt.innerText = t.name;
  5329. if (t.name === 'main') opt.selected = true;
  5330. tableSelect.appendChild(opt);
  5331. });
  5332. document.getElementById('route-modal').classList.remove('hidden');
  5333. }
  5334. function openEditRouteModal(id) {
  5335. const r = (state.routes || []).find(route => route.id === id);
  5336. if (!r) return;
  5337. const isStatic = !!r.static;
  5338. document.getElementById('route-modal-title').innerText = isStatic
  5339. ? `Edit Route: ${r.dst_address}`
  5340. : `Route Properties (Read Only): ${r.dst_address}`;
  5341. document.getElementById('route-modal-id').value = r.id;
  5342. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5343. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5344. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5345. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5346. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5347. const dstInput = document.getElementById('route-modal-dst');
  5348. const gwInput = document.getElementById('route-modal-gw');
  5349. const distInput = document.getElementById('route-modal-distance');
  5350. const ifaceSelect = document.getElementById('route-modal-iface');
  5351. const tableSelect = document.getElementById('route-modal-table');
  5352. const commentInput = document.getElementById('route-modal-comment');
  5353. const disCheck = document.getElementById('route-modal-disabled');
  5354. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5355. dstInput.value = r.dst_address;
  5356. gwInput.value = r.gateway || '';
  5357. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5358. commentInput.value = r.comment || '';
  5359. disCheck.checked = !!r.disabled;
  5360. dstInput.disabled = !isStatic;
  5361. gwInput.disabled = !isStatic;
  5362. distInput.disabled = !isStatic;
  5363. ifaceSelect.disabled = !isStatic;
  5364. tableSelect.disabled = !isStatic;
  5365. commentInput.disabled = !isStatic;
  5366. disCheck.disabled = !isStatic;
  5367. if (saveBtn) {
  5368. if (isStatic) {
  5369. saveBtn.classList.remove('hidden');
  5370. } else {
  5371. saveBtn.classList.add('hidden');
  5372. }
  5373. }
  5374. populateInterfaceSelect('route-modal-iface', r.interface);
  5375. tableSelect.innerHTML = '';
  5376. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5377. const opt = document.createElement('option');
  5378. opt.value = t.name;
  5379. opt.innerText = t.name;
  5380. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5381. tableSelect.appendChild(opt);
  5382. });
  5383. document.getElementById('route-modal').classList.remove('hidden');
  5384. }
  5385. function closeRouteModal() {
  5386. document.getElementById('route-modal').classList.add('hidden');
  5387. }
  5388. async function submitSaveRoute(e) {
  5389. e.preventDefault();
  5390. const id = document.getElementById('route-modal-id').value;
  5391. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5392. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5393. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5394. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5395. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5396. const dst = document.getElementById('route-modal-dst').value.trim();
  5397. const gw = document.getElementById('route-modal-gw').value.trim();
  5398. const table = document.getElementById('route-modal-table').value;
  5399. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5400. const iface = document.getElementById('route-modal-iface').value;
  5401. const comment = document.getElementById('route-modal-comment').value.trim();
  5402. const disabled = document.getElementById('route-modal-disabled').checked;
  5403. if (!dst) {
  5404. showToast('Error', 'Destination address is required', 'error');
  5405. return;
  5406. }
  5407. if (!gw && !iface) {
  5408. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5409. return;
  5410. }
  5411. const payload = {
  5412. id,
  5413. old_dst_address: oldDst,
  5414. old_gateway: oldGw,
  5415. old_routing_table: oldTable,
  5416. old_interface: oldIface,
  5417. dst_address: dst,
  5418. gateway: gw || iface,
  5419. routing_table: table,
  5420. distance,
  5421. interface: iface,
  5422. comment,
  5423. disabled
  5424. };
  5425. if (oldDistStr !== undefined && oldDistStr !== '') {
  5426. payload.old_distance = parseInt(oldDistStr, 10);
  5427. }
  5428. try {
  5429. const res = await fetch(`${API_BASE}/routes`, {
  5430. method: 'POST',
  5431. headers: { 'Content-Type': 'application/json' },
  5432. body: JSON.stringify(payload)
  5433. });
  5434. if (res.ok) {
  5435. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5436. closeRouteModal();
  5437. loadRoutes();
  5438. } else {
  5439. const err = await res.json();
  5440. showToast('Error', err.message || 'Failed to save route', 'error');
  5441. }
  5442. } catch (err) {
  5443. showToast('Error', err.message, 'error');
  5444. }
  5445. }
  5446. async function toggleRouteState(id, disabled) {
  5447. try {
  5448. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5449. method: 'POST',
  5450. headers: { 'Content-Type': 'application/json' },
  5451. body: JSON.stringify({ disabled })
  5452. });
  5453. if (res.ok) loadRoutes();
  5454. } catch (err) {
  5455. showToast('Error', err.message, 'error');
  5456. }
  5457. }
  5458. async function deleteRoute(id) {
  5459. if (!confirm('Are you sure you want to delete this route?')) return;
  5460. try {
  5461. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5462. if (res.ok) {
  5463. showToast('Deleted', 'Route removed', 'success');
  5464. loadRoutes();
  5465. }
  5466. } catch (err) {
  5467. showToast('Error', err.message, 'error');
  5468. }
  5469. }
  5470. // ----------------- Policy Rules (/ip route rule) -----------------
  5471. function renderPolicyRules() {
  5472. const tbody = document.getElementById('rules-table-body');
  5473. const empty = document.getElementById('rules-empty');
  5474. if (!tbody) return;
  5475. tbody.innerHTML = '';
  5476. const showSystem = document.getElementById('prule-show-system')?.checked;
  5477. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5478. const countBadge = document.getElementById('rules-count-badge');
  5479. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5480. const bRules = document.getElementById('routes-badge-rules');
  5481. if (bRules) bRules.innerText = filtered.length;
  5482. if (filtered.length === 0) {
  5483. empty?.classList.remove('hidden');
  5484. return;
  5485. }
  5486. empty?.classList.add('hidden');
  5487. filtered.forEach(pr => {
  5488. const isSys = pr.is_default || pr.is_system;
  5489. const tr = document.createElement('tr');
  5490. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5491. tr.innerHTML = `
  5492. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5493. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5494. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5495. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5496. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5497. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5498. <td class="py-2.5 px-3 text-right font-sans">
  5499. ${!pr.is_default ? `
  5500. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5501. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5502. </td>
  5503. `;
  5504. tbody.appendChild(tr);
  5505. });
  5506. }
  5507. function openAddPolicyRuleModal() {
  5508. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5509. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5510. document.getElementById('prule-modal-mark').value = '';
  5511. document.getElementById('prule-modal-src').value = '';
  5512. document.getElementById('prule-modal-dst').value = '';
  5513. const sel = document.getElementById('prule-modal-table');
  5514. sel.innerHTML = '';
  5515. (state.routingTables || []).forEach(t => {
  5516. const opt = document.createElement('option');
  5517. opt.value = t.name;
  5518. opt.innerText = t.name;
  5519. sel.appendChild(opt);
  5520. });
  5521. document.getElementById('prule-modal').classList.remove('hidden');
  5522. }
  5523. function closePolicyRuleModal() {
  5524. document.getElementById('prule-modal').classList.add('hidden');
  5525. }
  5526. async function submitSavePolicyRule(e) {
  5527. e.preventDefault();
  5528. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5529. const mark = document.getElementById('prule-modal-mark').value.trim();
  5530. const src = document.getElementById('prule-modal-src').value.trim();
  5531. const dst = document.getElementById('prule-modal-dst').value.trim();
  5532. const table = document.getElementById('prule-modal-table').value;
  5533. const action = document.getElementById('prule-modal-action').value;
  5534. try {
  5535. const res = await fetch(`${API_BASE}/routing/rules`, {
  5536. method: 'POST',
  5537. headers: { 'Content-Type': 'application/json' },
  5538. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5539. });
  5540. if (res.ok) {
  5541. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5542. closePolicyRuleModal();
  5543. loadRoutes();
  5544. } else {
  5545. const err = await res.json();
  5546. showToast('Error', err.message, 'error');
  5547. }
  5548. } catch (err) {
  5549. showToast('Error', err.message, 'error');
  5550. }
  5551. }
  5552. async function deletePolicyRule(id) {
  5553. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5554. try {
  5555. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5556. if (res.ok) {
  5557. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5558. loadRoutes();
  5559. }
  5560. } catch (err) {
  5561. showToast('Error', err.message, 'error');
  5562. }
  5563. }
  5564. // ----------------- Routing Tables -----------------
  5565. function renderRoutingTables() {
  5566. const tbody = document.getElementById('tables-table-body');
  5567. if (!tbody) return;
  5568. tbody.innerHTML = '';
  5569. (state.routingTables || []).forEach(t => {
  5570. const tr = document.createElement('tr');
  5571. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5572. tr.innerHTML = `
  5573. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5574. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5575. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5576. `;
  5577. tbody.appendChild(tr);
  5578. });
  5579. }
  5580. function openAddTableModal() {
  5581. document.getElementById('table-modal-name').value = '';
  5582. document.getElementById('table-modal-id').value = '';
  5583. document.getElementById('table-modal-comment').value = '';
  5584. document.getElementById('table-modal').classList.remove('hidden');
  5585. }
  5586. function closeTableModal() {
  5587. document.getElementById('table-modal').classList.add('hidden');
  5588. }
  5589. async function submitSaveTable(e) {
  5590. e.preventDefault();
  5591. const name = document.getElementById('table-modal-name').value.trim();
  5592. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5593. const comment = document.getElementById('table-modal-comment').value.trim();
  5594. try {
  5595. const res = await fetch(`${API_BASE}/routing/tables`, {
  5596. method: 'POST',
  5597. headers: { 'Content-Type': 'application/json' },
  5598. body: JSON.stringify({ name, table_id: id, comment })
  5599. });
  5600. if (res.ok) {
  5601. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5602. closeTableModal();
  5603. loadRoutes();
  5604. } else {
  5605. const err = await res.json();
  5606. showToast('Error', err.message, 'error');
  5607. }
  5608. } catch (err) {
  5609. showToast('Error', err.message, 'error');
  5610. }
  5611. }
  5612. async function loadDebianConfig() {
  5613. const view = document.getElementById('debian-config-view');
  5614. view.innerText = 'Generating live configuration...';
  5615. try {
  5616. const res = await fetch(`${API_BASE}/debian/config`);
  5617. const data = await res.json();
  5618. view.innerText = data.content || '# Empty config';
  5619. } catch (err) {
  5620. view.innerText = 'Failed to generate Debian network config.';
  5621. }
  5622. }
  5623. async function saveDebianConfig() {
  5624. try {
  5625. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5626. const data = await res.json();
  5627. if (res.ok) {
  5628. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5629. loadDebianConfig();
  5630. }
  5631. } catch (err) {
  5632. showToast('Error', err.message, 'error');
  5633. }
  5634. }
  5635. function showToast(title, message, type = 'info') {
  5636. const container = document.getElementById('toast-container');
  5637. const toast = document.createElement('div');
  5638. const borderColors = {
  5639. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5640. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5641. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5642. };
  5643. 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}`;
  5644. toast.innerHTML = `
  5645. <div class="flex-1">
  5646. <div class="font-bold text-xs text-white">${title}</div>
  5647. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5648. </div>
  5649. `;
  5650. container.appendChild(toast);
  5651. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5652. setTimeout(() => {
  5653. toast.classList.add('opacity-0', 'translate-y-2');
  5654. setTimeout(() => toast.remove(), 300);
  5655. }, 4000);
  5656. }
  5657. function formatTraffic(bytesPerSec) {
  5658. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5659. const kb = bytesPerSec / 1024;
  5660. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5661. const mb = kb / 1024;
  5662. return `${mb.toFixed(2)} MB/s`;
  5663. }
  5664. function toggleSidebar() {
  5665. const sb = document.getElementById('sidebar');
  5666. sb.classList.toggle('-translate-x-full');
  5667. }
  5668. // ======================== EoIP (Ethernet over IP) ========================
  5669. async function loadEoIP(populate = true) {
  5670. try {
  5671. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5672. const data = await res.json();
  5673. state.eoipTunnels = Array.isArray(data) ? data : [];
  5674. const badge = document.getElementById('eoip-count-badge');
  5675. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5676. const sideBadge = document.getElementById('badge-eoip-count');
  5677. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5678. renderEoIPTunnels();
  5679. } catch (err) {
  5680. console.error('Failed to load EoIP:', err);
  5681. }
  5682. }
  5683. function renderEoIPTunnels() {
  5684. const tbody = document.getElementById('eoip-table-body');
  5685. const empty = document.getElementById('eoip-empty');
  5686. if (!tbody) return;
  5687. tbody.innerHTML = '';
  5688. const tunnels = state.eoipTunnels || [];
  5689. if (tunnels.length === 0) {
  5690. empty?.classList.remove('hidden');
  5691. return;
  5692. }
  5693. empty?.classList.add('hidden');
  5694. tunnels.forEach(t => {
  5695. const tr = document.createElement('tr');
  5696. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5697. tr.innerHTML = `
  5698. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5699. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5700. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5701. <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>
  5702. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5703. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5704. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5705. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5706. <td class="py-2.5 px-3 font-mono text-[11px]">
  5707. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5708. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5709. </td>
  5710. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5711. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5712. <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>
  5713. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5714. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5715. </td>
  5716. `;
  5717. tbody.appendChild(tr);
  5718. });
  5719. }
  5720. function openAddEoIPModal() {
  5721. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5722. document.getElementById('eoip-modal-id').value = '';
  5723. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5724. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5725. document.getElementById('eoip-modal-remote').value = '';
  5726. document.getElementById('eoip-modal-ip').value = '';
  5727. document.getElementById('eoip-modal-local').value = '';
  5728. document.getElementById('eoip-modal-mac').value = '';
  5729. document.getElementById('eoip-modal-mtu').value = '1500';
  5730. document.getElementById('eoip-modal-comment').value = '';
  5731. document.getElementById('eoip-modal-clampmss').checked = true;
  5732. document.getElementById('eoip-modal-disabled').checked = false;
  5733. document.getElementById('eoip-modal').classList.remove('hidden');
  5734. }
  5735. function openEditEoIPModal(id) {
  5736. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5737. if (!t) return;
  5738. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5739. document.getElementById('eoip-modal-id').value = t.id;
  5740. document.getElementById('eoip-modal-name').value = t.name;
  5741. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5742. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5743. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5744. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5745. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5746. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5747. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5748. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5749. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5750. document.getElementById('eoip-modal').classList.remove('hidden');
  5751. }
  5752. function closeEoIPModal() {
  5753. document.getElementById('eoip-modal').classList.add('hidden');
  5754. }
  5755. async function submitSaveEoIP(e) {
  5756. e.preventDefault();
  5757. const id = document.getElementById('eoip-modal-id').value;
  5758. const name = document.getElementById('eoip-modal-name').value.trim();
  5759. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5760. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5761. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5762. const local = document.getElementById('eoip-modal-local').value.trim();
  5763. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5764. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5765. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5766. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5767. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5768. try {
  5769. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5770. method: 'POST',
  5771. headers: { 'Content-Type': 'application/json' },
  5772. body: JSON.stringify({
  5773. id,
  5774. name,
  5775. tunnel_id: tunnelId,
  5776. remote_address: remote,
  5777. ip_address: ipAddress,
  5778. local_address: local,
  5779. mac_address: mac,
  5780. mtu,
  5781. clamp_mss: clampMss,
  5782. comment,
  5783. disabled
  5784. })
  5785. });
  5786. if (res.ok) {
  5787. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5788. closeEoIPModal();
  5789. loadEoIP(false);
  5790. fetchData(false);
  5791. } else {
  5792. const err = await res.json();
  5793. showToast('Error', err.message, 'error');
  5794. }
  5795. } catch (err) {
  5796. showToast('Error', err.message, 'error');
  5797. }
  5798. }
  5799. async function toggleEoIPState(id, disabled) {
  5800. try {
  5801. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5802. method: 'POST',
  5803. headers: { 'Content-Type': 'application/json' },
  5804. body: JSON.stringify({ disabled })
  5805. });
  5806. if (res.ok) {
  5807. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5808. loadEoIP(false);
  5809. fetchData(false);
  5810. }
  5811. } catch (err) {
  5812. showToast('Error', err.message, 'error');
  5813. }
  5814. }
  5815. async function deleteEoIP(id) {
  5816. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5817. try {
  5818. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5819. if (res.ok) {
  5820. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5821. loadEoIP(false);
  5822. fetchData(false);
  5823. }
  5824. } catch (err) {
  5825. showToast('Error', err.message, 'error');
  5826. }
  5827. }
  5828. // ======================== PPP Central Hub & Servers ========================
  5829. function switchPPPSubTab(tab) {
  5830. state.pppSubTab = tab;
  5831. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  5832. tabs.forEach(t => {
  5833. const panel = document.getElementById(`ppp-subtab-${t}`);
  5834. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  5835. if (panel) {
  5836. if (t === tab) panel.classList.remove('hidden');
  5837. else panel.classList.add('hidden');
  5838. }
  5839. if (btn) {
  5840. if (t === tab) {
  5841. 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';
  5842. } else {
  5843. 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';
  5844. }
  5845. }
  5846. });
  5847. const addBtn = document.getElementById('ppp-primary-add-btn');
  5848. if (addBtn) {
  5849. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  5850. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  5851. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  5852. else addBtn.innerHTML = '<span>Save Config</span>';
  5853. }
  5854. if (tab === 'active') loadPPPSessions();
  5855. }
  5856. function openCurrentPPPModal() {
  5857. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  5858. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  5859. else if (state.pppSubTab === 'active') loadPPPSessions();
  5860. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  5861. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  5862. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  5863. }
  5864. async function loadPPP(populateDropdowns = true) {
  5865. await Promise.all([
  5866. loadPPPSecrets(),
  5867. loadPPPProfiles(),
  5868. loadPPPServers(),
  5869. loadPPPSessions()
  5870. ]);
  5871. }
  5872. async function loadPPPSecrets() {
  5873. try {
  5874. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  5875. const data = await res.json();
  5876. state.pppSecrets = Array.isArray(data) ? data : [];
  5877. const b = document.getElementById('ppp-badge-secrets');
  5878. if (b) b.innerText = state.pppSecrets.length;
  5879. const b2 = document.getElementById('secrets-count-badge');
  5880. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  5881. renderPPPSecrets();
  5882. } catch (err) {
  5883. console.error('Failed to load PPP secrets:', err);
  5884. }
  5885. }
  5886. function renderPPPSecrets() {
  5887. const tbody = document.getElementById('secrets-table-body');
  5888. const empty = document.getElementById('secrets-empty');
  5889. if (!tbody) return;
  5890. tbody.innerHTML = '';
  5891. const secrets = state.pppSecrets || [];
  5892. if (secrets.length === 0) {
  5893. empty?.classList.remove('hidden');
  5894. return;
  5895. }
  5896. empty?.classList.add('hidden');
  5897. secrets.forEach(s => {
  5898. const tr = document.createElement('tr');
  5899. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  5900. tr.innerHTML = `
  5901. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  5902. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  5903. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  5904. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  5905. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  5906. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  5907. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  5908. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5909. <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>
  5910. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5911. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5912. </td>
  5913. `;
  5914. tbody.appendChild(tr);
  5915. });
  5916. }
  5917. async function loadPPPProfiles() {
  5918. try {
  5919. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  5920. const data = await res.json();
  5921. state.pppProfiles = Array.isArray(data) ? data : [];
  5922. const b = document.getElementById('ppp-badge-profiles');
  5923. if (b) b.innerText = state.pppProfiles.length;
  5924. const b2 = document.getElementById('profiles-count-badge');
  5925. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  5926. // Populate profile selects across modals
  5927. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  5928. selects.forEach(sid => {
  5929. const el = document.getElementById(sid);
  5930. if (!el) return;
  5931. const cur = el.value;
  5932. el.innerHTML = '';
  5933. state.pppProfiles.forEach(p => {
  5934. const opt = document.createElement('option');
  5935. opt.value = p.name;
  5936. opt.innerText = `${p.name} (${p.remote_address})`;
  5937. if (p.name === cur) opt.selected = true;
  5938. el.appendChild(opt);
  5939. });
  5940. });
  5941. renderPPPProfiles();
  5942. } catch (err) {
  5943. console.error('Failed to load PPP profiles:', err);
  5944. }
  5945. }
  5946. function renderPPPProfiles() {
  5947. const tbody = document.getElementById('profiles-table-body');
  5948. if (!tbody) return;
  5949. tbody.innerHTML = '';
  5950. (state.pppProfiles || []).forEach(p => {
  5951. const isDefault = p.name.startsWith('default');
  5952. const tr = document.createElement('tr');
  5953. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5954. tr.innerHTML = `
  5955. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  5956. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  5957. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  5958. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  5959. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  5960. <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>
  5961. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  5962. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  5963. ${!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>`}
  5964. </td>
  5965. `;
  5966. tbody.appendChild(tr);
  5967. });
  5968. }
  5969. async function loadPPPServers() {
  5970. try {
  5971. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  5972. fetch(`${API_BASE}/vpn/servers/pppoe`),
  5973. fetch(`${API_BASE}/vpn/servers/pptp`),
  5974. fetch(`${API_BASE}/vpn/servers/l2tp`),
  5975. fetch(`${API_BASE}/vpn/servers/ipsec`)
  5976. ]);
  5977. if (pppoeRes.ok) {
  5978. state.pppoeServer = await pppoeRes.json();
  5979. const s = state.pppoeServer;
  5980. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  5981. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  5982. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  5983. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  5984. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  5985. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  5986. const pill = document.getElementById('pppoe-server-status-pill');
  5987. if (pill) {
  5988. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  5989. 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';
  5990. }
  5991. setDotBadge('ppp-badge-pppoe-state', s.running);
  5992. }
  5993. if (pptpRes.ok) {
  5994. state.pptpServer = await pptpRes.json();
  5995. const s = state.pptpServer;
  5996. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  5997. document.getElementById('pptp-server-port').value = s.port || 1723;
  5998. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  5999. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6000. const pill = document.getElementById('pptp-server-status-pill');
  6001. if (pill) {
  6002. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6003. 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';
  6004. }
  6005. setDotBadge('ppp-badge-pptp-state', s.running);
  6006. }
  6007. if (l2tpRes.ok) {
  6008. state.l2tpServer = await l2tpRes.json();
  6009. const s = state.l2tpServer;
  6010. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6011. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6012. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6013. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6014. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6015. const pill = document.getElementById('l2tp-server-status-pill');
  6016. if (pill) {
  6017. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6018. 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';
  6019. }
  6020. setDotBadge('ppp-badge-l2tp-state', s.running);
  6021. }
  6022. if (ipsecRes.ok) {
  6023. state.ipsecServer = await ipsecRes.json();
  6024. const s = state.ipsecServer;
  6025. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6026. if (modalEn) modalEn.checked = !!s.enabled;
  6027. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6028. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6029. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6030. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6031. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6032. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6033. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6034. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6035. const pill = document.getElementById('modal-ipsec-server-status');
  6036. if (pill) {
  6037. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6038. 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';
  6039. }
  6040. }
  6041. } catch (err) {
  6042. console.error('Failed to load VPN servers:', err);
  6043. }
  6044. }
  6045. async function loadPPPSessions() {
  6046. try {
  6047. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6048. const data = await res.json();
  6049. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6050. const b = document.getElementById('ppp-badge-active');
  6051. if (b) b.innerText = state.pppActiveSessions.length;
  6052. const sideB = document.getElementById('badge-ppp-sessions');
  6053. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6054. renderPPPSessions();
  6055. } catch (err) {
  6056. console.error('Failed to load active PPP sessions:', err);
  6057. }
  6058. }
  6059. function renderPPPSessions() {
  6060. const tbody = document.getElementById('active-ppp-table-body');
  6061. const empty = document.getElementById('active-ppp-empty');
  6062. if (!tbody) return;
  6063. tbody.innerHTML = '';
  6064. const list = state.pppActiveSessions || [];
  6065. if (list.length === 0) {
  6066. empty?.classList.remove('hidden');
  6067. return;
  6068. }
  6069. empty?.classList.add('hidden');
  6070. list.forEach(s => {
  6071. const tr = document.createElement('tr');
  6072. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6073. tr.innerHTML = `
  6074. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6075. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6076. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6077. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6078. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6079. <td class="py-2.5 px-3 text-[11px]">
  6080. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6081. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6082. </td>
  6083. <td class="py-2.5 px-3 text-right font-sans">
  6084. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6085. </td>
  6086. `;
  6087. tbody.appendChild(tr);
  6088. });
  6089. }
  6090. async function disconnectPPPSession(iface) {
  6091. if (!confirm(`Disconnect session ${iface}?`)) return;
  6092. try {
  6093. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6094. if (res.ok) {
  6095. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6096. loadPPPSessions();
  6097. }
  6098. } catch (err) {
  6099. showToast('Error', err.message, 'error');
  6100. }
  6101. }
  6102. // PPP Secret Modal handlers
  6103. function openAddPPPSecretModal() {
  6104. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6105. document.getElementById('secret-modal-id').value = '';
  6106. document.getElementById('secret-modal-name').value = '';
  6107. document.getElementById('secret-modal-password').value = '';
  6108. document.getElementById('secret-modal-service').value = 'any';
  6109. document.getElementById('secret-modal-profile').value = 'default';
  6110. document.getElementById('secret-modal-local').value = '';
  6111. document.getElementById('secret-modal-remote').value = '';
  6112. document.getElementById('secret-modal-comment').value = '';
  6113. document.getElementById('secret-modal-disabled').checked = false;
  6114. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6115. }
  6116. function openEditPPPSecretModal(id) {
  6117. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6118. if (!s) return;
  6119. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6120. document.getElementById('secret-modal-id').value = s.id;
  6121. document.getElementById('secret-modal-name').value = s.name;
  6122. document.getElementById('secret-modal-password').value = s.password;
  6123. document.getElementById('secret-modal-service').value = s.service || 'any';
  6124. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6125. document.getElementById('secret-modal-local').value = s.local_address || '';
  6126. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6127. document.getElementById('secret-modal-comment').value = s.comment || '';
  6128. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6129. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6130. }
  6131. function closePPPSecretModal() {
  6132. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6133. }
  6134. async function submitSavePPPSecret(e) {
  6135. e.preventDefault();
  6136. const id = document.getElementById('secret-modal-id').value;
  6137. const name = document.getElementById('secret-modal-name').value.trim();
  6138. const password = document.getElementById('secret-modal-password').value.trim();
  6139. const service = document.getElementById('secret-modal-service').value;
  6140. const profile = document.getElementById('secret-modal-profile').value;
  6141. const local = document.getElementById('secret-modal-local').value.trim();
  6142. const remote = document.getElementById('secret-modal-remote').value.trim();
  6143. const comment = document.getElementById('secret-modal-comment').value.trim();
  6144. const disabled = document.getElementById('secret-modal-disabled').checked;
  6145. try {
  6146. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6147. method: 'POST',
  6148. headers: { 'Content-Type': 'application/json' },
  6149. body: JSON.stringify({
  6150. id,
  6151. name,
  6152. password,
  6153. service,
  6154. profile,
  6155. local_address: local,
  6156. remote_address: remote,
  6157. comment,
  6158. disabled
  6159. })
  6160. });
  6161. if (res.ok) {
  6162. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6163. closePPPSecretModal();
  6164. loadPPPSecrets();
  6165. } else {
  6166. const err = await res.json();
  6167. showToast('Error', err.message, 'error');
  6168. }
  6169. } catch (err) {
  6170. showToast('Error', err.message, 'error');
  6171. }
  6172. }
  6173. async function togglePPPSecretState(id, disabled) {
  6174. try {
  6175. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6176. method: 'POST',
  6177. headers: { 'Content-Type': 'application/json' },
  6178. body: JSON.stringify({ disabled })
  6179. });
  6180. if (res.ok) {
  6181. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6182. loadPPPSecrets();
  6183. }
  6184. } catch (err) {
  6185. showToast('Error', err.message, 'error');
  6186. }
  6187. }
  6188. async function deletePPPSecret(id) {
  6189. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6190. try {
  6191. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6192. if (res.ok) {
  6193. showToast('Deleted', 'Secret account removed', 'success');
  6194. loadPPPSecrets();
  6195. }
  6196. } catch (err) {
  6197. showToast('Error', err.message, 'error');
  6198. }
  6199. }
  6200. // PPP Profile Modal handlers
  6201. function openAddPPPProfileModal() {
  6202. document.getElementById('profile-modal-name').value = '';
  6203. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6204. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6205. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6206. document.getElementById('profile-modal-encryption').value = 'required';
  6207. document.getElementById('profile-modal-onlyone').checked = true;
  6208. document.getElementById('profile-modal-comment').value = '';
  6209. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6210. }
  6211. function closePPPProfileModal() {
  6212. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6213. }
  6214. async function submitSavePPPProfile(e) {
  6215. e.preventDefault();
  6216. const name = document.getElementById('profile-modal-name').value.trim();
  6217. const local = document.getElementById('profile-modal-local').value.trim();
  6218. const remote = document.getElementById('profile-modal-remote').value.trim();
  6219. const dns = document.getElementById('profile-modal-dns').value.trim();
  6220. const enc = document.getElementById('profile-modal-encryption').value;
  6221. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6222. const comment = document.getElementById('profile-modal-comment').value.trim();
  6223. try {
  6224. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6225. method: 'POST',
  6226. headers: { 'Content-Type': 'application/json' },
  6227. body: JSON.stringify({
  6228. id: name,
  6229. name,
  6230. local_address: local,
  6231. remote_address: remote,
  6232. dns_servers: dns,
  6233. use_encryption: enc,
  6234. only_one: onlyone,
  6235. comment
  6236. })
  6237. });
  6238. if (res.ok) {
  6239. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6240. closePPPProfileModal();
  6241. loadPPPProfiles();
  6242. } else {
  6243. const err = await res.json();
  6244. showToast('Error', err.message, 'error');
  6245. }
  6246. } catch (err) {
  6247. showToast('Error', err.message, 'error');
  6248. }
  6249. }
  6250. async function deletePPPProfile(name) {
  6251. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6252. try {
  6253. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6254. if (res.ok) {
  6255. showToast('Deleted', 'Profile removed', 'success');
  6256. loadPPPProfiles();
  6257. } else {
  6258. const err = await res.json();
  6259. showToast('Error', err.message, 'error');
  6260. }
  6261. } catch (err) {
  6262. showToast('Error', err.message, 'error');
  6263. }
  6264. }
  6265. // Server Config submissions
  6266. async function savePPPoEServerConfig(e) {
  6267. e.preventDefault();
  6268. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6269. const name = document.getElementById('pppoe-server-name').value.trim();
  6270. const iface = document.getElementById('pppoe-server-iface').value;
  6271. const profile = document.getElementById('pppoe-server-profile').value;
  6272. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6273. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6274. try {
  6275. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6276. method: 'POST',
  6277. headers: { 'Content-Type': 'application/json' },
  6278. body: JSON.stringify({
  6279. enabled,
  6280. service_name: name,
  6281. interface: iface,
  6282. default_profile: profile,
  6283. max_mtu: mtu,
  6284. max_mru: mtu,
  6285. one_session_per_host: onesession
  6286. })
  6287. });
  6288. if (res.ok) {
  6289. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6290. loadPPPServers();
  6291. fetchData(false);
  6292. } else {
  6293. const err = await res.json();
  6294. showToast('Error', err.message, 'error');
  6295. }
  6296. } catch (err) {
  6297. showToast('Error', err.message, 'error');
  6298. }
  6299. }
  6300. async function savePPTPServerConfig(e) {
  6301. e.preventDefault();
  6302. const enabled = document.getElementById('pptp-server-enabled').checked;
  6303. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6304. const profile = document.getElementById('pptp-server-profile').value;
  6305. const mppe = document.getElementById('pptp-server-mppe').checked;
  6306. try {
  6307. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6308. method: 'POST',
  6309. headers: { 'Content-Type': 'application/json' },
  6310. body: JSON.stringify({
  6311. enabled,
  6312. port,
  6313. default_profile: profile,
  6314. require_mppe: mppe
  6315. })
  6316. });
  6317. if (res.ok) {
  6318. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6319. loadPPPServers();
  6320. fetchData(false);
  6321. } else {
  6322. const err = await res.json();
  6323. showToast('Error', err.message, 'error');
  6324. }
  6325. } catch (err) {
  6326. showToast('Error', err.message, 'error');
  6327. }
  6328. }
  6329. async function saveL2TPServerConfig(e) {
  6330. e.preventDefault();
  6331. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6332. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6333. const profile = document.getElementById('l2tp-server-profile').value;
  6334. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6335. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6336. try {
  6337. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6338. method: 'POST',
  6339. headers: { 'Content-Type': 'application/json' },
  6340. body: JSON.stringify({
  6341. enabled,
  6342. port,
  6343. default_profile: profile,
  6344. use_ipsec: useipsec,
  6345. ipsec_secret: psk
  6346. })
  6347. });
  6348. if (res.ok) {
  6349. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6350. loadPPPServers();
  6351. fetchData(false);
  6352. } else {
  6353. const err = await res.json();
  6354. showToast('Error', err.message, 'error');
  6355. }
  6356. } catch (err) {
  6357. showToast('Error', err.message, 'error');
  6358. }
  6359. }
  6360. // IPSec Server Modal
  6361. function openIPSecServerModal() {
  6362. loadPPPServers();
  6363. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6364. }
  6365. function closeIPSecServerModal() {
  6366. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6367. }
  6368. async function submitSaveIPSecServer(e) {
  6369. e.preventDefault();
  6370. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6371. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6372. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6373. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6374. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6375. try {
  6376. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6377. method: 'POST',
  6378. headers: { 'Content-Type': 'application/json' },
  6379. body: JSON.stringify({
  6380. enabled,
  6381. preshared_key: psk,
  6382. pool_address: pool,
  6383. dns_servers: dns,
  6384. local_subnet: subnet
  6385. })
  6386. });
  6387. if (res.ok) {
  6388. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6389. closeIPSecServerModal();
  6390. loadPPPServers();
  6391. fetchData(false);
  6392. } else {
  6393. const err = await res.json();
  6394. showToast('Error', err.message, 'error');
  6395. }
  6396. } catch (err) {
  6397. showToast('Error', err.message, 'error');
  6398. }
  6399. }
  6400. // WireGuard Client Config Viewer
  6401. let currentWGClientConf = '';
  6402. async function openWGClientConfModal(iface, clientIP) {
  6403. try {
  6404. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6405. method: 'POST',
  6406. headers: { 'Content-Type': 'application/json' },
  6407. body: JSON.stringify({
  6408. interface: iface,
  6409. address: clientIP || '10.10.0.2/32',
  6410. dns: '1.1.1.1, 8.8.8.8'
  6411. })
  6412. });
  6413. if (res.ok) {
  6414. const data = await res.json();
  6415. currentWGClientConf = data.config;
  6416. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6417. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6418. } else {
  6419. const err = await res.json();
  6420. showToast('Error', err.message, 'error');
  6421. }
  6422. } catch (err) {
  6423. showToast('Error', err.message, 'error');
  6424. }
  6425. }
  6426. function closeWGClientConfModal() {
  6427. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6428. }
  6429. function copyWGClientConf() {
  6430. if (!currentWGClientConf) return;
  6431. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6432. }
  6433. function downloadWGClientConf() {
  6434. if (!currentWGClientConf) return;
  6435. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6436. const a = document.createElement('a');
  6437. a.href = URL.createObjectURL(blob);
  6438. a.download = 'wireguard-client.conf';
  6439. document.body.appendChild(a);
  6440. a.click();
  6441. document.body.removeChild(a);
  6442. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6443. }
  6444. // =========================================================================
  6445. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6446. // =========================================================================
  6447. state.activeDynSubTab = 'bgp-peers';
  6448. state.activeBgpSubTab = 'bgp-peers';
  6449. state.activeOspfTab = 'instances';
  6450. state.bgpInstance = null;
  6451. state.bgpPeers = [];
  6452. state.bgpNets = [];
  6453. state.bgpRoutes = [];
  6454. state.ospfInstance = null;
  6455. state.ospfInstances = [];
  6456. state.ospfAreas = [];
  6457. state.ospfAreaRanges = [];
  6458. state.ospfTemplates = [];
  6459. state.ospfLiveInterfaces = [];
  6460. state.ospfStaticNbrs = [];
  6461. state.ospfNeighbors = [];
  6462. state.ospfLSA = [];
  6463. state.ospfRoutes = [];
  6464. state.selectedOspfRow = {
  6465. instances: null,
  6466. areas: null,
  6467. 'area-ranges': null,
  6468. templates: null,
  6469. interfaces: null,
  6470. 'static-nbrs': null,
  6471. neighbors: null,
  6472. lsa: null,
  6473. };
  6474. state.ospfSort = {
  6475. instances: { col: 'name', asc: true },
  6476. areas: { col: 'name', asc: true },
  6477. ranges: { col: 'area', asc: true },
  6478. templates: { col: 'interfaces', asc: true },
  6479. live_ifaces: { col: 'interface', asc: true },
  6480. snbrs: { col: 'address', asc: true },
  6481. neighbors: { col: 'address', asc: true },
  6482. lsa: { col: 'instance', asc: true },
  6483. };
  6484. function switchBgpSubTab(subTab) {
  6485. state.activeBgpSubTab = subTab;
  6486. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6487. tabs.forEach(t => {
  6488. const el = document.getElementById(`dyn-subtab-${t}`);
  6489. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6490. if (el) el.classList.toggle('hidden', t !== subTab);
  6491. if (btn) {
  6492. if (t === subTab) {
  6493. 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';
  6494. } else {
  6495. 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';
  6496. }
  6497. }
  6498. });
  6499. }
  6500. function switchOspfTab(tabName) {
  6501. state.activeOspfTab = tabName;
  6502. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6503. tabs.forEach(t => {
  6504. const pane = document.getElementById(`ospf-pane-${t}`);
  6505. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6506. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6507. if (btn) {
  6508. if (t === tabName) {
  6509. 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';
  6510. } else {
  6511. 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';
  6512. }
  6513. }
  6514. });
  6515. }
  6516. function switchOspfSubTab(tab) {
  6517. // Legacy alias
  6518. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6519. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6520. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6521. else switchOspfTab('instances');
  6522. }
  6523. function switchDynSubTab(subTab) {
  6524. if (subTab.startsWith('bgp')) {
  6525. if (state.activeTab !== 'bgp') navigate('bgp');
  6526. switchBgpSubTab(subTab);
  6527. } else if (subTab.startsWith('ospf')) {
  6528. if (state.activeTab !== 'ospf') navigate('ospf');
  6529. switchOspfTab('instances');
  6530. }
  6531. }
  6532. async function loadDynamicRouting(showToastMsg = false) {
  6533. try {
  6534. const fetchSafeJson = async (url) => {
  6535. try {
  6536. const r = await fetch(url);
  6537. return r.ok ? await r.json() : null;
  6538. } catch (e) {
  6539. return null;
  6540. }
  6541. };
  6542. const [
  6543. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6544. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6545. selectRules, commLists, asLists
  6546. ] = await Promise.all([
  6547. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6548. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6549. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6550. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6551. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6552. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6553. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6554. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6555. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6556. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6557. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6558. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6559. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6560. fetchSafeJson(`${API_BASE}/routing/filters`),
  6561. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6562. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6563. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6564. ]);
  6565. if (sum) state.dynSummary = sum;
  6566. if (bgpInst) state.bgpInstance = bgpInst;
  6567. if (bgpPeers) state.bgpPeers = bgpPeers;
  6568. if (bgpNets) state.bgpNets = bgpNets;
  6569. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6570. if (ospfInsts) state.ospfInstances = ospfInsts;
  6571. if (ospfAreas) state.ospfAreas = ospfAreas;
  6572. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6573. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6574. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6575. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6576. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6577. if (ospfLsa) state.ospfLSA = ospfLsa;
  6578. if (filters) state.routingFilters = filters;
  6579. if (selectRules) state.routingSelectRules = selectRules;
  6580. if (commLists) state.routingCommunityLists = commLists;
  6581. if (asLists) state.routingASLists = asLists;
  6582. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6583. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6584. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6585. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6586. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6587. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6588. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6589. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6590. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6591. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6592. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6593. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6594. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6595. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6596. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6597. } catch (err) {
  6598. console.error('Failed to load dynamic routing:', err);
  6599. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6600. }
  6601. }
  6602. async function loadOspfAll() {
  6603. await loadDynamicRouting(true);
  6604. }
  6605. function renderBgpStatusPill() {
  6606. const pill = document.getElementById('bgp-live-status-pill');
  6607. if (!pill) return;
  6608. const inst = state.bgpInstance;
  6609. if (!inst || !inst.enabled) {
  6610. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6611. pill.innerText = 'BGP DISABLED';
  6612. } else if (inst.running) {
  6613. 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';
  6614. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6615. } else {
  6616. 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';
  6617. pill.innerText = 'BGP STARTING...';
  6618. }
  6619. }
  6620. function renderBgpPeers() {
  6621. const tbody = document.getElementById('bgp-peers-table-body');
  6622. if (!tbody) return;
  6623. const empty = document.getElementById('bgp-peers-empty');
  6624. const countBadge = document.getElementById('bgp-peers-count-badge');
  6625. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6626. const peers = state.bgpPeers || [];
  6627. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6628. if (navBadge) navBadge.innerText = peers.length;
  6629. if (peers.length === 0) {
  6630. tbody.innerHTML = '';
  6631. if (empty) empty.classList.remove('hidden');
  6632. return;
  6633. }
  6634. if (empty) empty.classList.add('hidden');
  6635. tbody.innerHTML = peers.map(p => {
  6636. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  6637. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  6638. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  6639. let stateBadge = '';
  6640. if (p.disabled) {
  6641. 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>';
  6642. } else if (p.state === 'Established') {
  6643. 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>';
  6644. } else if (p.state === 'Connect' || p.state === 'Active') {
  6645. 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>`;
  6646. } else {
  6647. 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>`;
  6648. }
  6649. return `
  6650. <tr class="hover:bg-slate-800/40 transition">
  6651. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  6652. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  6653. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  6654. <td class="py-2.5 px-3">
  6655. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  6656. ${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>`}
  6657. </td>
  6658. <td class="py-2.5 px-3">${stateBadge}</td>
  6659. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  6660. <td class="py-2.5 px-3 text-slate-300">
  6661. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  6662. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  6663. </td>
  6664. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  6665. ${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> ` : ''}
  6666. ${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>` : ''}
  6667. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  6668. </td>
  6669. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  6670. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  6671. <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'}">
  6672. ${p.disabled ? 'Enable' : 'Disable'}
  6673. </button>
  6674. <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">
  6675. Edit
  6676. </button>
  6677. <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">
  6678. Delete
  6679. </button>
  6680. </td>
  6681. </tr>
  6682. `;
  6683. }).join('');
  6684. }
  6685. function renderBgpNetworks() {
  6686. const tbody = document.getElementById('bgp-nets-table-body');
  6687. if (!tbody) return;
  6688. const empty = document.getElementById('bgp-nets-empty');
  6689. const countBadge = document.getElementById('bgp-nets-count-badge');
  6690. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  6691. const nets = state.bgpNets || [];
  6692. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  6693. if (navBadge) navBadge.innerText = nets.length;
  6694. if (nets.length === 0) {
  6695. tbody.innerHTML = '';
  6696. if (empty) empty.classList.remove('hidden');
  6697. return;
  6698. }
  6699. if (empty) empty.classList.add('hidden');
  6700. tbody.innerHTML = nets.map(n => `
  6701. <tr class="hover:bg-slate-800/40 transition">
  6702. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  6703. <td class="py-2.5 px-3">
  6704. ${n.disabled
  6705. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  6706. : '<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>'}
  6707. </td>
  6708. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  6709. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  6710. <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">
  6711. Delete
  6712. </button>
  6713. </td>
  6714. </tr>
  6715. `).join('');
  6716. }
  6717. function renderBgpRoutes() {
  6718. const tbody = document.getElementById('bgp-routes-table-body');
  6719. if (!tbody) return;
  6720. const empty = document.getElementById('bgp-routes-empty');
  6721. const countBadge = document.getElementById('bgp-routes-count-badge');
  6722. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  6723. const routes = state.bgpRoutes || [];
  6724. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  6725. if (navBadge) navBadge.innerText = routes.length;
  6726. if (routes.length === 0) {
  6727. tbody.innerHTML = '';
  6728. if (empty) empty.classList.remove('hidden');
  6729. return;
  6730. }
  6731. if (empty) empty.classList.add('hidden');
  6732. tbody.innerHTML = routes.map(r => `
  6733. <tr class="hover:bg-slate-800/40 transition">
  6734. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  6735. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  6736. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  6737. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  6738. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  6739. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  6740. </tr>
  6741. `).join('');
  6742. }
  6743. // =========================================================================
  6744. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  6745. // =========================================================================
  6746. function sortOspfTable(tab, col) {
  6747. if (!state.ospfSort) state.ospfSort = {};
  6748. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  6749. if (state.ospfSort[tab].col === col) {
  6750. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  6751. } else {
  6752. state.ospfSort[tab].col = col;
  6753. state.ospfSort[tab].asc = true;
  6754. }
  6755. const asc = state.ospfSort[tab].asc;
  6756. let list = [];
  6757. if (tab === 'instances') list = state.ospfInstances || [];
  6758. else if (tab === 'areas') list = state.ospfAreas || [];
  6759. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  6760. else if (tab === 'templates') list = state.ospfTemplates || [];
  6761. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  6762. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  6763. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  6764. else if (tab === 'lsa') list = state.ospfLSA || [];
  6765. list.sort((a, b) => {
  6766. let valA = a[col] ?? '';
  6767. let valB = b[col] ?? '';
  6768. if (typeof valA === 'number' && typeof valB === 'number') {
  6769. return asc ? valA - valB : valB - valA;
  6770. }
  6771. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  6772. });
  6773. if (tab === 'instances') renderOspfInstances();
  6774. else if (tab === 'areas') renderOspfAreas();
  6775. else if (tab === 'ranges') renderOspfAreaRanges();
  6776. else if (tab === 'templates') renderOspfTemplates();
  6777. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  6778. else if (tab === 'snbrs') renderOspfStaticNbrs();
  6779. else if (tab === 'neighbors') renderOspfNeighbors();
  6780. else if (tab === 'lsa') renderOspfLSA();
  6781. }
  6782. function selectOspfRow(tab, id) {
  6783. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  6784. state.selectedOspfRow[tab] = id;
  6785. if (tab === 'instances') {
  6786. renderOspfInstances();
  6787. const btnEn = document.getElementById('btn-ospf-inst-enable');
  6788. const btnDis = document.getElementById('btn-ospf-inst-disable');
  6789. const btnRem = document.getElementById('btn-ospf-inst-remove');
  6790. const btnCom = document.getElementById('btn-ospf-inst-comment');
  6791. if (btnEn) btnEn.disabled = false;
  6792. if (btnDis) btnDis.disabled = false;
  6793. if (btnRem) btnRem.disabled = false;
  6794. if (btnCom) btnCom.disabled = false;
  6795. } else if (tab === 'areas') {
  6796. renderOspfAreas();
  6797. const btnEn = document.getElementById('btn-ospf-area-enable');
  6798. const btnDis = document.getElementById('btn-ospf-area-disable');
  6799. const btnRem = document.getElementById('btn-ospf-area-remove');
  6800. const btnCom = document.getElementById('btn-ospf-area-comment');
  6801. if (btnEn) btnEn.disabled = false;
  6802. if (btnDis) btnDis.disabled = false;
  6803. if (btnRem) btnRem.disabled = false;
  6804. if (btnCom) btnCom.disabled = false;
  6805. } else if (tab === 'ranges') {
  6806. renderOspfAreaRanges();
  6807. const btnEn = document.getElementById('btn-ospf-range-enable');
  6808. const btnDis = document.getElementById('btn-ospf-range-disable');
  6809. const btnRem = document.getElementById('btn-ospf-range-remove');
  6810. const btnCom = document.getElementById('btn-ospf-range-comment');
  6811. if (btnEn) btnEn.disabled = false;
  6812. if (btnDis) btnDis.disabled = false;
  6813. if (btnRem) btnRem.disabled = false;
  6814. if (btnCom) btnCom.disabled = false;
  6815. } else if (tab === 'templates') {
  6816. renderOspfTemplates();
  6817. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  6818. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  6819. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  6820. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  6821. if (btnEn) btnEn.disabled = false;
  6822. if (btnDis) btnDis.disabled = false;
  6823. if (btnRem) btnRem.disabled = false;
  6824. if (btnCom) btnCom.disabled = false;
  6825. } else if (tab === 'snbrs') {
  6826. renderOspfStaticNbrs();
  6827. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  6828. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  6829. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  6830. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  6831. if (btnEn) btnEn.disabled = false;
  6832. if (btnDis) btnDis.disabled = false;
  6833. if (btnRem) btnRem.disabled = false;
  6834. if (btnCom) btnCom.disabled = false;
  6835. }
  6836. }
  6837. // TAB 1: INSTANCES
  6838. function renderOspfInstances() {
  6839. const tbody = document.getElementById('ospf-instances-table-body');
  6840. if (!tbody) return;
  6841. const countEl = document.getElementById('ospf-instances-footer-count');
  6842. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  6843. let list = state.ospfInstances || [];
  6844. if (filter) {
  6845. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  6846. }
  6847. if (countEl) countEl.innerText = list.length;
  6848. const selId = state.selectedOspfRow?.instances;
  6849. tbody.innerHTML = list.map((inst, idx) => {
  6850. const isSel = inst.id === selId;
  6851. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6852. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6853. return `
  6854. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  6855. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6856. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6857. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  6858. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6859. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  6860. </td>
  6861. <td class="py-1.5 px-3">${inst.version || 2}</td>
  6862. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  6863. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  6864. </tr>
  6865. `;
  6866. }).join('');
  6867. }
  6868. // TAB 2: AREAS
  6869. function renderOspfAreas() {
  6870. const tbody = document.getElementById('ospf-areas-table-body');
  6871. if (!tbody) return;
  6872. const countEl = document.getElementById('ospf-areas-footer-count');
  6873. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  6874. let list = state.ospfAreas || [];
  6875. if (filter) {
  6876. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  6877. }
  6878. if (countEl) countEl.innerText = list.length;
  6879. const selId = state.selectedOspfRow?.areas;
  6880. tbody.innerHTML = list.map((a, idx) => {
  6881. const isSel = a.id === selId;
  6882. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6883. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6884. return `
  6885. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  6886. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6887. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  6888. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  6889. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6890. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  6891. </td>
  6892. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  6893. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  6894. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  6895. </tr>
  6896. `;
  6897. }).join('');
  6898. }
  6899. // TAB 3: AREA RANGES
  6900. function renderOspfAreaRanges() {
  6901. const tbody = document.getElementById('ospf-ranges-table-body');
  6902. if (!tbody) return;
  6903. const countEl = document.getElementById('ospf-ranges-footer-count');
  6904. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  6905. let list = state.ospfAreaRanges || [];
  6906. if (filter) {
  6907. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  6908. }
  6909. if (countEl) countEl.innerText = list.length;
  6910. const selId = state.selectedOspfRow?.['area-ranges'];
  6911. tbody.innerHTML = list.map((r, idx) => {
  6912. const isSel = r.id === selId;
  6913. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6914. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6915. return `
  6916. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  6917. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  6918. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  6919. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  6920. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  6921. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  6922. <td class="py-1.5 px-3">${r.cost || 1}</td>
  6923. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  6924. </tr>
  6925. `;
  6926. }).join('');
  6927. }
  6928. // TAB 4: INTERFACE TEMPLATES
  6929. function renderOspfTemplates() {
  6930. const tbody = document.getElementById('ospf-templates-table-body');
  6931. if (!tbody) return;
  6932. const countEl = document.getElementById('ospf-templates-footer-count');
  6933. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  6934. let list = state.ospfTemplates || [];
  6935. if (filter) {
  6936. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  6937. }
  6938. if (countEl) countEl.innerText = list.length;
  6939. const selId = state.selectedOspfRow?.templates;
  6940. tbody.innerHTML = list.map((t, idx) => {
  6941. const isSel = t.id === selId;
  6942. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  6943. const ifaces = t.interfaces || t.interface || 'all';
  6944. const nets = t.networks || t.network || '';
  6945. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  6946. return `
  6947. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  6948. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  6949. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  6950. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  6951. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  6952. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  6953. </td>
  6954. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  6955. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  6956. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  6957. <td class="py-1.5 px-3">${t.cost || 1}</td>
  6958. <td class="py-1.5 px-3">${t.priority || 128}</td>
  6959. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  6960. </tr>
  6961. `;
  6962. }).join('');
  6963. }
  6964. // TAB 5: LIVE INTERFACES
  6965. function renderOspfLiveInterfaces() {
  6966. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  6967. if (!tbody) return;
  6968. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  6969. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  6970. let list = state.ospfLiveInterfaces || [];
  6971. if (filter) {
  6972. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  6973. }
  6974. if (countEl) countEl.innerText = list.length;
  6975. tbody.innerHTML = list.map(i => `
  6976. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  6977. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  6978. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  6979. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  6980. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  6981. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  6982. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  6983. <td class="py-1.5 px-3">${i.cost || 1}</td>
  6984. <td class="py-1.5 px-3">${i.priority || 128}</td>
  6985. </tr>
  6986. `).join('');
  6987. }
  6988. // TAB 6: STATIC NEIGHBORS
  6989. function renderOspfStaticNbrs() {
  6990. const tbody = document.getElementById('ospf-snbrs-table-body');
  6991. if (!tbody) return;
  6992. const countEl = document.getElementById('ospf-snbrs-footer-count');
  6993. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  6994. let list = state.ospfStaticNbrs || [];
  6995. if (filter) {
  6996. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  6997. }
  6998. if (countEl) countEl.innerText = list.length;
  6999. const selId = state.selectedOspfRow?.['static-nbrs'];
  7000. tbody.innerHTML = list.map((n, idx) => {
  7001. const isSel = n.id === selId;
  7002. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7003. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7004. return `
  7005. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7006. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7007. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7008. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7009. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7010. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7011. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7012. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7013. </tr>
  7014. `;
  7015. }).join('');
  7016. }
  7017. // TAB 7: LIVE NEIGHBORS
  7018. function renderOspfNeighbors() {
  7019. const tbody = document.getElementById('ospf-neighbors-table-body');
  7020. if (!tbody) return;
  7021. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7022. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7023. let list = state.ospfNeighbors || [];
  7024. if (filter) {
  7025. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7026. }
  7027. if (countEl) countEl.innerText = list.length;
  7028. tbody.innerHTML = list.map(n => `
  7029. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7030. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7031. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7032. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7033. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7034. </td>
  7035. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7036. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7037. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7038. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7039. </tr>
  7040. `).join('');
  7041. }
  7042. // TAB 8: LINK-STATE DATABASE (LSA)
  7043. function renderOspfLSA() {
  7044. const tbody = document.getElementById('ospf-lsa-table-body');
  7045. if (!tbody) return;
  7046. const countEl = document.getElementById('ospf-lsa-footer-count');
  7047. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7048. let list = state.ospfLSA || [];
  7049. if (filter) {
  7050. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7051. }
  7052. if (countEl) countEl.innerText = list.length;
  7053. tbody.innerHTML = list.map(l => `
  7054. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7055. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7056. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7057. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7058. </td>
  7059. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7060. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7061. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7062. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7063. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7064. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7065. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7066. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7067. </tr>
  7068. `).join('');
  7069. }
  7070. function renderOspfStatusPill() {
  7071. // Maintained for backward compatibility
  7072. const pill = document.getElementById('ospf-live-status-pill');
  7073. if (!pill) return;
  7074. 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';
  7075. pill.innerText = 'OSPF ACTIVE';
  7076. }
  7077. function renderOspfInterfaces() {
  7078. renderOspfTemplates();
  7079. }
  7080. function renderOspfRoutes() {
  7081. // Routes retained in background
  7082. }
  7083. // BGP Modals & Actions
  7084. function openBgpInstanceModal() {
  7085. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7086. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7087. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7088. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7089. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7090. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7091. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7092. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7093. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7094. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7095. }
  7096. function closeBgpInstanceModal() {
  7097. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7098. }
  7099. async function submitBgpInstance(e) {
  7100. e.preventDefault();
  7101. const payload = {
  7102. enabled: document.getElementById('modal-bgp-enabled').checked,
  7103. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7104. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7105. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7106. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7107. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7108. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7109. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7110. };
  7111. try {
  7112. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7113. method: 'POST',
  7114. headers: { 'Content-Type': 'application/json' },
  7115. body: JSON.stringify(payload)
  7116. });
  7117. if (res.ok) {
  7118. closeBgpInstanceModal();
  7119. showToast('Success', 'BGP instance configuration updated', 'success');
  7120. loadDynamicRouting();
  7121. } else {
  7122. const err = await res.json();
  7123. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7124. }
  7125. } catch (err) {
  7126. showToast('Error', err.message, 'error');
  7127. }
  7128. }
  7129. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7130. function switchBgpPeerModalTab(tab) {
  7131. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7132. tabs.forEach(t => {
  7133. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7134. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7135. if (t === tab) {
  7136. if (pane) pane.classList.remove('hidden');
  7137. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7138. } else {
  7139. if (pane) pane.classList.add('hidden');
  7140. 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';
  7141. }
  7142. });
  7143. }
  7144. function addOutputNetworkRow(val = '') {
  7145. const container = document.getElementById('modal-bgp-output-networks-container');
  7146. if (!container) return;
  7147. const row = document.createElement('div');
  7148. row.className = 'flex items-center gap-2 output-net-row';
  7149. row.innerHTML = `
  7150. <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">
  7151. <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>
  7152. `;
  7153. container.appendChild(row);
  7154. }
  7155. function parseBgpTime(val) {
  7156. if (!val) return 0;
  7157. val = String(val).trim();
  7158. if (val.includes(':')) {
  7159. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7160. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7161. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7162. }
  7163. return parseInt(val, 10) || 0;
  7164. }
  7165. function formatBgpTime(secs) {
  7166. if (!secs || secs <= 0) return '00:00:00';
  7167. const h = Math.floor(secs / 3600);
  7168. const m = Math.floor((secs % 3600) / 60);
  7169. const s = secs % 60;
  7170. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7171. }
  7172. function populateBgpRoutingTables() {
  7173. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7174. if (!sel) return;
  7175. const cur = sel.value || 'main';
  7176. sel.innerHTML = '<option value="main">main</option>';
  7177. (state.routingTables || []).forEach(t => {
  7178. if (t.name !== 'main') {
  7179. const opt = document.createElement('option');
  7180. opt.value = t.name;
  7181. opt.innerText = t.name;
  7182. sel.appendChild(opt);
  7183. }
  7184. });
  7185. sel.value = cur;
  7186. }
  7187. function openAddBgpPeerModal() {
  7188. document.getElementById('bgp-peer-form').reset();
  7189. document.getElementById('modal-bgp-peer-id').value = '';
  7190. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7191. // General Tab
  7192. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7193. document.getElementById('modal-bgp-peer-comment').value = '';
  7194. document.getElementById('modal-bgp-peer-name').value = '';
  7195. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7196. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7197. document.getElementById('modal-bgp-peer-local-as').value = '';
  7198. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7199. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7200. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7201. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7202. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7203. document.getElementById('modal-bgp-peer-router-id').value = '';
  7204. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7205. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7206. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7207. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7208. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7209. document.getElementById('modal-bgp-peer-local-port').value = '';
  7210. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7211. document.getElementById('modal-bgp-peer-password').value = '';
  7212. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7213. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7214. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7215. document.getElementById('modal-bgp-peer-connect').checked = true;
  7216. document.getElementById('modal-bgp-peer-listen').checked = true;
  7217. // Extra Tab
  7218. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7219. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7220. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7221. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7222. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7223. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7224. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7225. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7226. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7227. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7228. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7229. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7230. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7231. // Attributes Tab
  7232. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7233. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7234. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7235. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7236. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7237. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7238. // Filter Tab
  7239. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7240. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7241. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7242. populateBgpRoutingTables();
  7243. const container = document.getElementById('modal-bgp-output-networks-container');
  7244. if (container) {
  7245. container.innerHTML = '';
  7246. addOutputNetworkRow('');
  7247. }
  7248. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7249. if (removeBtn) removeBtn.classList.add('hidden');
  7250. switchBgpPeerModalTab('general');
  7251. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7252. }
  7253. function openEditBgpPeerModal(id) {
  7254. const p = (state.bgpPeers || []).find(item => item.id === id);
  7255. if (!p) return;
  7256. populateBgpRoutingTables();
  7257. document.getElementById('modal-bgp-peer-id').value = p.id;
  7258. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7259. // General Tab
  7260. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7261. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7262. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7263. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7264. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7265. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7266. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7267. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7268. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7269. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7270. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7271. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7272. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7273. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7274. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7275. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7276. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7277. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7278. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7279. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7280. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7281. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7282. // Extra Tab
  7283. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7284. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7285. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7286. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7287. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7288. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7289. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7290. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7291. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7292. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7293. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7294. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7295. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7296. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7297. // Attributes Tab
  7298. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7299. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7300. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7301. 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;
  7302. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7303. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7304. // Filter Tab
  7305. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7306. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7307. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7308. // Output Networks
  7309. const container = document.getElementById('modal-bgp-output-networks-container');
  7310. if (container) {
  7311. container.innerHTML = '';
  7312. if (p.output_networks && p.output_networks.length > 0) {
  7313. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7314. } else {
  7315. addOutputNetworkRow('');
  7316. }
  7317. }
  7318. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7319. if (removeBtn) removeBtn.classList.remove('hidden');
  7320. switchBgpPeerModalTab('general');
  7321. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7322. }
  7323. function copyCurrentBgpPeer() {
  7324. document.getElementById('modal-bgp-peer-id').value = '';
  7325. const nameEl = document.getElementById('modal-bgp-peer-name');
  7326. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7327. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7328. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7329. if (removeBtn) removeBtn.classList.add('hidden');
  7330. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7331. }
  7332. function removeCurrentBgpPeer() {
  7333. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7334. if (!id) return;
  7335. deleteBgpPeer(id);
  7336. closeBgpPeerModal();
  7337. }
  7338. function closeBgpPeerModal() {
  7339. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7340. }
  7341. function getBgpPeerFormData() {
  7342. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7343. const outputNetworks = [];
  7344. netInputs.forEach(inp => {
  7345. const v = inp.value.trim();
  7346. if (v) outputNetworks.push(v);
  7347. });
  7348. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7349. return {
  7350. id: document.getElementById('modal-bgp-peer-id').value,
  7351. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7352. enabled: enabled,
  7353. disabled: !enabled,
  7354. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7355. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7356. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7357. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7358. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7359. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7360. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7361. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7362. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7363. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7364. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7365. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7366. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7367. password: document.getElementById('modal-bgp-peer-password').value,
  7368. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7369. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7370. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7371. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7372. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7373. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7374. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7375. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7376. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7377. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7378. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7379. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7380. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7381. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7382. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7383. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7384. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7385. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7386. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7387. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7388. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7389. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7390. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7391. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7392. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7393. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7394. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7395. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7396. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7397. output_networks: outputNetworks
  7398. };
  7399. }
  7400. async function submitBgpPeer(e) {
  7401. if (e) e.preventDefault();
  7402. const payload = getBgpPeerFormData();
  7403. try {
  7404. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7405. method: 'POST',
  7406. headers: { 'Content-Type': 'application/json' },
  7407. body: JSON.stringify(payload)
  7408. });
  7409. if (res.ok) {
  7410. closeBgpPeerModal();
  7411. showToast('Success', 'BGP Connection saved', 'success');
  7412. loadDynamicRouting();
  7413. } else {
  7414. const err = await res.json();
  7415. showToast('Error', err.error || 'Failed to save peer', 'error');
  7416. }
  7417. } catch (err) {
  7418. showToast('Error', err.message, 'error');
  7419. }
  7420. }
  7421. async function applyBgpPeerModal(e) {
  7422. if (e) e.preventDefault();
  7423. const payload = getBgpPeerFormData();
  7424. try {
  7425. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7426. method: 'POST',
  7427. headers: { 'Content-Type': 'application/json' },
  7428. body: JSON.stringify(payload)
  7429. });
  7430. if (res.ok) {
  7431. const data = await res.json();
  7432. if (data.peer && data.peer.id) {
  7433. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7434. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7435. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7436. }
  7437. showToast('Applied', 'BGP Connection applied', 'success');
  7438. loadDynamicRouting();
  7439. } else {
  7440. const err = await res.json();
  7441. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7442. }
  7443. } catch (err) {
  7444. showToast('Error', err.message, 'error');
  7445. }
  7446. }
  7447. async function deleteBgpPeer(id) {
  7448. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7449. try {
  7450. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7451. if (res.ok) {
  7452. showToast('Deleted', 'BGP peer removed', 'success');
  7453. loadDynamicRouting();
  7454. }
  7455. } catch (err) {
  7456. showToast('Error', err.message, 'error');
  7457. }
  7458. }
  7459. async function toggleBgpPeerState(id, disabled) {
  7460. try {
  7461. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7462. method: 'POST',
  7463. headers: { 'Content-Type': 'application/json' },
  7464. body: JSON.stringify({ disabled })
  7465. });
  7466. if (res.ok) {
  7467. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7468. loadDynamicRouting();
  7469. }
  7470. } catch (err) {
  7471. showToast('Error', err.message, 'error');
  7472. }
  7473. }
  7474. function openAddBgpNetworkModal() {
  7475. document.getElementById('bgp-network-form').reset();
  7476. document.getElementById('modal-bgp-net-id').value = '';
  7477. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7478. }
  7479. function closeBgpNetworkModal() {
  7480. document.getElementById('bgp-network-modal').classList.add('hidden');
  7481. }
  7482. async function submitBgpNetwork(e) {
  7483. e.preventDefault();
  7484. const payload = {
  7485. id: document.getElementById('modal-bgp-net-id').value,
  7486. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7487. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7488. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7489. };
  7490. try {
  7491. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7492. method: 'POST',
  7493. headers: { 'Content-Type': 'application/json' },
  7494. body: JSON.stringify(payload)
  7495. });
  7496. if (res.ok) {
  7497. closeBgpNetworkModal();
  7498. showToast('Success', 'BGP network advertisement saved', 'success');
  7499. loadDynamicRouting();
  7500. } else {
  7501. const err = await res.json();
  7502. showToast('Error', err.error || 'Failed to save network', 'error');
  7503. }
  7504. } catch (err) {
  7505. showToast('Error', err.message, 'error');
  7506. }
  7507. }
  7508. async function deleteBgpNetwork(id) {
  7509. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7510. try {
  7511. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7512. if (res.ok) {
  7513. showToast('Deleted', 'Network advertisement removed', 'success');
  7514. loadDynamicRouting();
  7515. }
  7516. } catch (err) {
  7517. showToast('Error', err.message, 'error');
  7518. }
  7519. }
  7520. // =========================================================================
  7521. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7522. // =========================================================================
  7523. // --- 1. OSPF INSTANCE ---
  7524. function openOspfInstanceModal(id = null) {
  7525. const isEdit = !!id;
  7526. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7527. id: '',
  7528. name: 'Default',
  7529. version: 2,
  7530. vrf: 'main',
  7531. router_id: '192.168.131.56',
  7532. routing_table: 'main',
  7533. enabled: true,
  7534. redistribute_connected: false,
  7535. redistribute_static: true,
  7536. redistribute_bgp: false,
  7537. comment: ''
  7538. };
  7539. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7540. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7541. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7542. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7543. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7544. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7545. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7546. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7547. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7548. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7549. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7550. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7551. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7552. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7553. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7554. }
  7555. function openEditOspfInstanceModal(id) {
  7556. openOspfInstanceModal(id);
  7557. }
  7558. function closeOspfInstanceModal() {
  7559. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7560. }
  7561. async function submitOspfInstance(e) {
  7562. if (e) e.preventDefault();
  7563. const payload = {
  7564. id: document.getElementById('modal-ospf-inst-id').value,
  7565. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  7566. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  7567. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  7568. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  7569. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  7570. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  7571. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  7572. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  7573. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  7574. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  7575. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  7576. };
  7577. try {
  7578. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  7579. method: 'POST',
  7580. headers: { 'Content-Type': 'application/json' },
  7581. body: JSON.stringify(payload)
  7582. });
  7583. if (res.ok) {
  7584. closeOspfInstanceModal();
  7585. showToast('Saved', 'OSPF instance updated', 'success');
  7586. loadDynamicRouting();
  7587. } else {
  7588. const err = await res.json();
  7589. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  7590. }
  7591. } catch (err) {
  7592. showToast('Error', err.message, 'error');
  7593. }
  7594. }
  7595. function applyOspfInstanceForm() {
  7596. submitOspfInstance(null);
  7597. }
  7598. function copyOspfInstance() {
  7599. document.getElementById('modal-ospf-inst-id').value = '';
  7600. document.getElementById('modal-ospf-inst-name').value += '-copy';
  7601. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  7602. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  7603. }
  7604. async function deleteCurrentOspfInstance() {
  7605. const id = document.getElementById('modal-ospf-inst-id').value;
  7606. if (!id) return;
  7607. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  7608. try {
  7609. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7610. if (res.ok) {
  7611. closeOspfInstanceModal();
  7612. showToast('Removed', 'OSPF instance deleted', 'success');
  7613. loadDynamicRouting();
  7614. }
  7615. } catch (err) {
  7616. showToast('Error', err.message, 'error');
  7617. }
  7618. }
  7619. async function enableSelectedOspfInstance() {
  7620. const id = state.selectedOspfRow?.instances;
  7621. if (!id) return;
  7622. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7623. method: 'POST',
  7624. headers: { 'Content-Type': 'application/json' },
  7625. body: JSON.stringify({ disabled: false })
  7626. });
  7627. loadDynamicRouting();
  7628. }
  7629. async function disableSelectedOspfInstance() {
  7630. const id = state.selectedOspfRow?.instances;
  7631. if (!id) return;
  7632. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  7633. method: 'POST',
  7634. headers: { 'Content-Type': 'application/json' },
  7635. body: JSON.stringify({ disabled: true })
  7636. });
  7637. loadDynamicRouting();
  7638. }
  7639. async function removeSelectedOspfInstance() {
  7640. const id = state.selectedOspfRow?.instances;
  7641. if (!id) return;
  7642. if (!confirm('Delete selected OSPF instance?')) return;
  7643. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7644. loadDynamicRouting();
  7645. }
  7646. async function promptCommentOspfInstance() {
  7647. const id = state.selectedOspfRow?.instances;
  7648. if (!id) return;
  7649. const inst = (state.ospfInstances || []).find(i => i.id === id);
  7650. if (!inst) return;
  7651. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  7652. if (comment === null) return;
  7653. inst.comment = comment;
  7654. await fetch(`${API_BASE}/routing/ospf/instances`, {
  7655. method: 'POST',
  7656. headers: { 'Content-Type': 'application/json' },
  7657. body: JSON.stringify(inst)
  7658. });
  7659. loadDynamicRouting();
  7660. }
  7661. // --- 2. OSPF AREA ---
  7662. function populateOspfAreaDropdowns() {
  7663. const instSelect = document.getElementById('modal-ospf-area-instance');
  7664. if (instSelect) {
  7665. const cur = instSelect.value;
  7666. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  7667. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  7668. if (cur) instSelect.value = cur;
  7669. }
  7670. }
  7671. function openOspfAreaModal(id = null) {
  7672. const isEdit = !!id;
  7673. populateOspfAreaDropdowns();
  7674. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  7675. id: '',
  7676. name: 'Default',
  7677. instance: 'Default',
  7678. area_id: '0.0.0.0',
  7679. area_type: 'default',
  7680. default_cost: 1,
  7681. no_summaries: false,
  7682. disabled: false,
  7683. comment: ''
  7684. };
  7685. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  7686. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  7687. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  7688. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  7689. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  7690. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  7691. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  7692. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  7693. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  7694. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  7695. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  7696. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7697. document.getElementById('ospf-area-modal').classList.remove('hidden');
  7698. }
  7699. function openEditOspfAreaModal(id) {
  7700. openOspfAreaModal(id);
  7701. }
  7702. function closeOspfAreaModal() {
  7703. document.getElementById('ospf-area-modal').classList.add('hidden');
  7704. }
  7705. async function submitOspfArea(e) {
  7706. if (e) e.preventDefault();
  7707. const payload = {
  7708. id: document.getElementById('modal-ospf-area-id').value,
  7709. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  7710. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  7711. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  7712. area_type: document.getElementById('modal-ospf-area-type').value,
  7713. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  7714. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  7715. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  7716. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  7717. };
  7718. try {
  7719. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  7720. method: 'POST',
  7721. headers: { 'Content-Type': 'application/json' },
  7722. body: JSON.stringify(payload)
  7723. });
  7724. if (res.ok) {
  7725. closeOspfAreaModal();
  7726. showToast('Saved', 'OSPF area saved', 'success');
  7727. loadDynamicRouting();
  7728. } else {
  7729. const err = await res.json();
  7730. showToast('Error', err.error || 'Failed to save area', 'error');
  7731. }
  7732. } catch (err) {
  7733. showToast('Error', err.message, 'error');
  7734. }
  7735. }
  7736. function applyOspfAreaForm() {
  7737. submitOspfArea(null);
  7738. }
  7739. function copyOspfArea() {
  7740. document.getElementById('modal-ospf-area-id').value = '';
  7741. document.getElementById('modal-ospf-area-name').value += '-copy';
  7742. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  7743. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  7744. }
  7745. async function deleteCurrentOspfArea() {
  7746. const id = document.getElementById('modal-ospf-area-id').value;
  7747. if (!id) return;
  7748. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  7749. try {
  7750. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7751. if (res.ok) {
  7752. closeOspfAreaModal();
  7753. showToast('Removed', 'OSPF area deleted', 'success');
  7754. loadDynamicRouting();
  7755. }
  7756. } catch (err) {
  7757. showToast('Error', err.message, 'error');
  7758. }
  7759. }
  7760. async function enableSelectedOspfArea() {
  7761. const id = state.selectedOspfRow?.areas;
  7762. if (!id) return;
  7763. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7764. method: 'POST',
  7765. headers: { 'Content-Type': 'application/json' },
  7766. body: JSON.stringify({ disabled: false })
  7767. });
  7768. loadDynamicRouting();
  7769. }
  7770. async function disableSelectedOspfArea() {
  7771. const id = state.selectedOspfRow?.areas;
  7772. if (!id) return;
  7773. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  7774. method: 'POST',
  7775. headers: { 'Content-Type': 'application/json' },
  7776. body: JSON.stringify({ disabled: true })
  7777. });
  7778. loadDynamicRouting();
  7779. }
  7780. async function removeSelectedOspfArea() {
  7781. const id = state.selectedOspfRow?.areas;
  7782. if (!id) return;
  7783. if (!confirm('Delete selected OSPF area?')) return;
  7784. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7785. loadDynamicRouting();
  7786. }
  7787. async function promptCommentOspfArea() {
  7788. const id = state.selectedOspfRow?.areas;
  7789. if (!id) return;
  7790. const area = (state.ospfAreas || []).find(a => a.id === id);
  7791. if (!area) return;
  7792. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  7793. if (comment === null) return;
  7794. area.comment = comment;
  7795. await fetch(`${API_BASE}/routing/ospf/areas`, {
  7796. method: 'POST',
  7797. headers: { 'Content-Type': 'application/json' },
  7798. body: JSON.stringify(area)
  7799. });
  7800. loadDynamicRouting();
  7801. }
  7802. // --- 3. OSPF AREA RANGE ---
  7803. function populateAreaRangeDropdowns() {
  7804. const select = document.getElementById('modal-ospf-range-area');
  7805. if (select) {
  7806. const cur = select.value;
  7807. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7808. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7809. if (cur) select.value = cur;
  7810. }
  7811. }
  7812. function openOspfAreaRangeModal(id = null) {
  7813. const isEdit = !!id;
  7814. populateAreaRangeDropdowns();
  7815. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  7816. id: '',
  7817. area: 'Default',
  7818. prefix: '',
  7819. cost: 1,
  7820. advertise: true,
  7821. disabled: false,
  7822. comment: ''
  7823. };
  7824. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  7825. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  7826. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  7827. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  7828. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  7829. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  7830. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  7831. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  7832. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  7833. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7834. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  7835. }
  7836. function openEditOspfAreaRangeModal(id) {
  7837. openOspfAreaRangeModal(id);
  7838. }
  7839. function closeOspfAreaRangeModal() {
  7840. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  7841. }
  7842. async function submitOspfAreaRange(e) {
  7843. if (e) e.preventDefault();
  7844. const payload = {
  7845. id: document.getElementById('modal-ospf-range-id').value,
  7846. area: document.getElementById('modal-ospf-range-area').value,
  7847. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  7848. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  7849. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  7850. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  7851. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  7852. };
  7853. try {
  7854. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  7855. method: 'POST',
  7856. headers: { 'Content-Type': 'application/json' },
  7857. body: JSON.stringify(payload)
  7858. });
  7859. if (res.ok) {
  7860. closeOspfAreaRangeModal();
  7861. showToast('Saved', 'Area range saved', 'success');
  7862. loadDynamicRouting();
  7863. } else {
  7864. const err = await res.json();
  7865. showToast('Error', err.error || 'Failed to save area range', 'error');
  7866. }
  7867. } catch (err) {
  7868. showToast('Error', err.message, 'error');
  7869. }
  7870. }
  7871. function applyOspfAreaRangeForm() {
  7872. submitOspfAreaRange(null);
  7873. }
  7874. async function deleteCurrentOspfAreaRange() {
  7875. const id = document.getElementById('modal-ospf-range-id').value;
  7876. if (!id) return;
  7877. if (!confirm('Delete this area range?')) return;
  7878. try {
  7879. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7880. closeOspfAreaRangeModal();
  7881. showToast('Removed', 'Area range removed', 'success');
  7882. loadDynamicRouting();
  7883. } catch (err) {
  7884. showToast('Error', err.message, 'error');
  7885. }
  7886. }
  7887. async function enableSelectedOspfAreaRange() {
  7888. const id = state.selectedOspfRow?.['area-ranges'];
  7889. if (!id) return;
  7890. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7891. if (!r) return;
  7892. r.disabled = false;
  7893. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7894. loadDynamicRouting();
  7895. }
  7896. async function disableSelectedOspfAreaRange() {
  7897. const id = state.selectedOspfRow?.['area-ranges'];
  7898. if (!id) return;
  7899. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7900. if (!r) return;
  7901. r.disabled = true;
  7902. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7903. loadDynamicRouting();
  7904. }
  7905. async function removeSelectedOspfAreaRange() {
  7906. const id = state.selectedOspfRow?.['area-ranges'];
  7907. if (!id) return;
  7908. if (!confirm('Delete selected area range?')) return;
  7909. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7910. loadDynamicRouting();
  7911. }
  7912. async function promptCommentOspfAreaRange() {
  7913. const id = state.selectedOspfRow?.['area-ranges'];
  7914. if (!id) return;
  7915. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  7916. if (!r) return;
  7917. const comment = prompt('Enter comment for area range:', r.comment || '');
  7918. if (comment === null) return;
  7919. r.comment = comment;
  7920. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  7921. loadDynamicRouting();
  7922. }
  7923. // --- 4. OSPF INTERFACE TEMPLATE ---
  7924. function switchOspfTemplateTab(tab) {
  7925. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  7926. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  7927. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  7928. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  7929. if (tab === 'general') {
  7930. if (tabGen) tabGen.classList.remove('hidden');
  7931. if (tabAuth) tabAuth.classList.add('hidden');
  7932. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7933. 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';
  7934. } else {
  7935. if (tabGen) tabGen.classList.add('hidden');
  7936. if (tabAuth) tabAuth.classList.remove('hidden');
  7937. 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';
  7938. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  7939. }
  7940. }
  7941. function populateTemplateAreaDropdowns() {
  7942. const select = document.getElementById('modal-ospf-tmpl-area');
  7943. if (select) {
  7944. const cur = select.value;
  7945. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  7946. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  7947. if (cur) select.value = cur;
  7948. }
  7949. }
  7950. function openOspfTemplateModal(id = null) {
  7951. const isEdit = !!id;
  7952. populateTemplateAreaDropdowns();
  7953. switchOspfTemplateTab('general');
  7954. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  7955. id: '',
  7956. interfaces: '',
  7957. area: 'Default',
  7958. networks: '',
  7959. network_type: 'broadcast',
  7960. cost: 1,
  7961. priority: 128,
  7962. passive: false,
  7963. hello_interval: 10,
  7964. dead_interval: 40,
  7965. auth: 'none',
  7966. auth_key: '',
  7967. disabled: false,
  7968. comment: ''
  7969. };
  7970. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  7971. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  7972. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  7973. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  7974. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  7975. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  7976. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  7977. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  7978. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  7979. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  7980. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  7981. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  7982. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  7983. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  7984. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  7985. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  7986. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7987. document.getElementById('ospf-template-modal').classList.remove('hidden');
  7988. }
  7989. function openEditOspfTemplateModal(id) {
  7990. openOspfTemplateModal(id);
  7991. }
  7992. function closeOspfTemplateModal() {
  7993. document.getElementById('ospf-template-modal').classList.add('hidden');
  7994. }
  7995. async function submitOspfTemplate(e) {
  7996. if (e) e.preventDefault();
  7997. const payload = {
  7998. id: document.getElementById('modal-ospf-tmpl-id').value,
  7999. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8000. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8001. area: document.getElementById('modal-ospf-tmpl-area').value,
  8002. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8003. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8004. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8005. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8006. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8007. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8008. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8009. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8010. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8011. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8012. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8013. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8014. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8015. };
  8016. try {
  8017. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8018. method: 'POST',
  8019. headers: { 'Content-Type': 'application/json' },
  8020. body: JSON.stringify(payload)
  8021. });
  8022. if (res.ok) {
  8023. closeOspfTemplateModal();
  8024. showToast('Saved', 'Interface template saved', 'success');
  8025. loadDynamicRouting();
  8026. } else {
  8027. const err = await res.json();
  8028. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8029. }
  8030. } catch (err) {
  8031. showToast('Error', err.message, 'error');
  8032. }
  8033. }
  8034. function applyOspfTemplateForm() {
  8035. submitOspfTemplate(null);
  8036. }
  8037. function copyOspfTemplate() {
  8038. document.getElementById('modal-ospf-tmpl-id').value = '';
  8039. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8040. showToast('Copied', 'Duplicated as new template', 'info');
  8041. }
  8042. async function deleteCurrentOspfTemplate() {
  8043. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8044. if (!id) return;
  8045. if (!confirm('Delete this interface template?')) return;
  8046. try {
  8047. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8048. closeOspfTemplateModal();
  8049. showToast('Removed', 'Interface template deleted', 'success');
  8050. loadDynamicRouting();
  8051. } catch (err) {
  8052. showToast('Error', err.message, 'error');
  8053. }
  8054. }
  8055. async function enableSelectedOspfTemplate() {
  8056. const id = state.selectedOspfRow?.templates;
  8057. if (!id) return;
  8058. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8059. method: 'POST',
  8060. headers: { 'Content-Type': 'application/json' },
  8061. body: JSON.stringify({ disabled: false })
  8062. });
  8063. loadDynamicRouting();
  8064. }
  8065. async function disableSelectedOspfTemplate() {
  8066. const id = state.selectedOspfRow?.templates;
  8067. if (!id) return;
  8068. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8069. method: 'POST',
  8070. headers: { 'Content-Type': 'application/json' },
  8071. body: JSON.stringify({ disabled: true })
  8072. });
  8073. loadDynamicRouting();
  8074. }
  8075. async function removeSelectedOspfTemplate() {
  8076. const id = state.selectedOspfRow?.templates;
  8077. if (!id) return;
  8078. if (!confirm('Delete selected interface template?')) return;
  8079. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8080. loadDynamicRouting();
  8081. }
  8082. async function promptCommentOspfTemplate() {
  8083. const id = state.selectedOspfRow?.templates;
  8084. if (!id) return;
  8085. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8086. if (!tmpl) return;
  8087. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8088. if (comment === null) return;
  8089. tmpl.comment = comment;
  8090. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8091. method: 'POST',
  8092. headers: { 'Content-Type': 'application/json' },
  8093. body: JSON.stringify(tmpl)
  8094. });
  8095. loadDynamicRouting();
  8096. }
  8097. // --- 5. OSPF STATIC NEIGHBOR ---
  8098. function populateStaticNbrAreaDropdowns() {
  8099. const select = document.getElementById('modal-ospf-snbr-area');
  8100. if (select) {
  8101. const cur = select.value;
  8102. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8103. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8104. if (cur) select.value = cur;
  8105. }
  8106. }
  8107. function openOspfStaticNbrModal(id = null) {
  8108. const isEdit = !!id;
  8109. populateStaticNbrAreaDropdowns();
  8110. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8111. id: '',
  8112. address: '',
  8113. area: 'Default',
  8114. poll_interval: 120,
  8115. cost: 1,
  8116. disabled: false,
  8117. comment: ''
  8118. };
  8119. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8120. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8121. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8122. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8123. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8124. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8125. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8126. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8127. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8128. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8129. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8130. }
  8131. function openEditOspfStaticNbrModal(id) {
  8132. openOspfStaticNbrModal(id);
  8133. }
  8134. function closeOspfStaticNbrModal() {
  8135. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8136. }
  8137. async function submitOspfStaticNbr(e) {
  8138. if (e) e.preventDefault();
  8139. const payload = {
  8140. id: document.getElementById('modal-ospf-snbr-id').value,
  8141. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8142. area: document.getElementById('modal-ospf-snbr-area').value,
  8143. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8144. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8145. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8146. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8147. };
  8148. try {
  8149. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8150. method: 'POST',
  8151. headers: { 'Content-Type': 'application/json' },
  8152. body: JSON.stringify(payload)
  8153. });
  8154. if (res.ok) {
  8155. closeOspfStaticNbrModal();
  8156. showToast('Saved', 'Static neighbor saved', 'success');
  8157. loadDynamicRouting();
  8158. } else {
  8159. const err = await res.json();
  8160. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8161. }
  8162. } catch (err) {
  8163. showToast('Error', err.message, 'error');
  8164. }
  8165. }
  8166. function applyOspfStaticNbrForm() {
  8167. submitOspfStaticNbr(null);
  8168. }
  8169. async function deleteCurrentOspfStaticNbr() {
  8170. const id = document.getElementById('modal-ospf-snbr-id').value;
  8171. if (!id) return;
  8172. if (!confirm('Delete this static neighbor?')) return;
  8173. try {
  8174. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8175. closeOspfStaticNbrModal();
  8176. showToast('Removed', 'Static neighbor removed', 'success');
  8177. loadDynamicRouting();
  8178. } catch (err) {
  8179. showToast('Error', err.message, 'error');
  8180. }
  8181. }
  8182. async function enableSelectedOspfStaticNbr() {
  8183. const id = state.selectedOspfRow?.['static-nbrs'];
  8184. if (!id) return;
  8185. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8186. if (!n) return;
  8187. n.disabled = false;
  8188. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8189. loadDynamicRouting();
  8190. }
  8191. async function disableSelectedOspfStaticNbr() {
  8192. const id = state.selectedOspfRow?.['static-nbrs'];
  8193. if (!id) return;
  8194. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8195. if (!n) return;
  8196. n.disabled = true;
  8197. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8198. loadDynamicRouting();
  8199. }
  8200. async function removeSelectedOspfStaticNbr() {
  8201. const id = state.selectedOspfRow?.['static-nbrs'];
  8202. if (!id) return;
  8203. if (!confirm('Delete selected static neighbor?')) return;
  8204. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8205. loadDynamicRouting();
  8206. }
  8207. async function promptCommentOspfStaticNbr() {
  8208. const id = state.selectedOspfRow?.['static-nbrs'];
  8209. if (!id) return;
  8210. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8211. if (!n) return;
  8212. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8213. if (comment === null) return;
  8214. n.comment = comment;
  8215. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8216. loadDynamicRouting();
  8217. }
  8218. // Backward-compat aliases
  8219. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8220. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8221. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8222. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8223. function deleteOspfInterface(id) {
  8224. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8225. }
  8226. function toggleOspfInterfaceState(id, disabled) {
  8227. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8228. method: 'POST',
  8229. headers: { 'Content-Type': 'application/json' },
  8230. body: JSON.stringify({ disabled })
  8231. }).then(() => loadDynamicRouting());
  8232. }
  8233. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8234. function deleteOspfArea(id) {
  8235. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8236. }
  8237. // ============================================================================
  8238. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8239. // ============================================================================
  8240. function switchBridgeSubTab(tab) {
  8241. state.bridgeSubTab = tab;
  8242. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8243. tabs.forEach(t => {
  8244. const panel = document.getElementById(`bridge-subtab-${t}`);
  8245. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8246. if (panel) {
  8247. if (t === tab) panel.classList.remove('hidden');
  8248. else panel.classList.add('hidden');
  8249. }
  8250. if (btn) {
  8251. if (t === tab) {
  8252. 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';
  8253. } else {
  8254. 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';
  8255. }
  8256. }
  8257. });
  8258. const addBtn = document.getElementById('bridge-top-action-btn');
  8259. if (addBtn) {
  8260. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8261. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8262. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8263. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8264. }
  8265. if (tab === 'hosts') loadBridgeHosts();
  8266. setTimeout(initTableSorting, 50);
  8267. }
  8268. function openCurrentBridgeModal() {
  8269. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8270. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8271. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8272. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8273. }
  8274. async function loadBridge() {
  8275. try {
  8276. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8277. fetch(`${API_BASE}/bridge/bridges`),
  8278. fetch(`${API_BASE}/bridge/ports`),
  8279. fetch(`${API_BASE}/bridge/vlans`),
  8280. fetch(`${API_BASE}/bridge/summary`),
  8281. fetch(`${API_BASE}/vpn/eoip`),
  8282. fetch(`${API_BASE}/vlans`)
  8283. ]);
  8284. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8285. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8286. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8287. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8288. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8289. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8290. // Badges & Stats
  8291. const bBridges = document.getElementById('bridge-badge-bridges');
  8292. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8293. const bPorts = document.getElementById('bridge-badge-ports');
  8294. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8295. const bVlans = document.getElementById('bridge-badge-vlans');
  8296. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8297. const bHosts = document.getElementById('bridge-badge-hosts');
  8298. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8299. const sBr = document.getElementById('bridge-stat-bridges');
  8300. if (sBr) sBr.innerText = (state.bridges || []).length;
  8301. const sPorts = document.getElementById('bridge-stat-ports');
  8302. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8303. const sHosts = document.getElementById('bridge-stat-hosts');
  8304. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8305. renderBridges();
  8306. renderBridgePorts();
  8307. renderBridgeVLANs();
  8308. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8309. } catch (err) {
  8310. console.error('Failed to load bridge subsystem:', err);
  8311. }
  8312. }
  8313. // ----------------- Bridges -----------------
  8314. function renderBridges() {
  8315. const tbody = document.getElementById('bridge-table-body');
  8316. const empty = document.getElementById('bridge-empty-bridges');
  8317. const countBadge = document.getElementById('bridge-count-badge');
  8318. if (!tbody) return;
  8319. tbody.innerHTML = '';
  8320. const bridges = state.bridges || [];
  8321. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8322. if (bridges.length === 0) {
  8323. empty?.classList.remove('hidden');
  8324. return;
  8325. }
  8326. empty?.classList.add('hidden');
  8327. bridges.forEach((b, idx) => {
  8328. const tr = document.createElement('tr');
  8329. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8330. // Format IP addresses pill list
  8331. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8332. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8333. ipsHtml = b.ip_addresses.map(ip => `
  8334. <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">
  8335. <span>${ip}</span>
  8336. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8337. </span>
  8338. `).join(' ');
  8339. }
  8340. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8341. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8342. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8343. tr.innerHTML = `
  8344. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8345. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8346. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8347. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8348. </td>
  8349. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8350. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8351. <td class="py-2.5 px-3">
  8352. <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>
  8353. </td>
  8354. <td class="py-2.5 px-3 text-center">
  8355. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8356. </td>
  8357. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8358. <td class="py-2.5 px-3">
  8359. <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>
  8360. </td>
  8361. <td class="py-2.5 px-3">
  8362. <div class="flex items-center gap-1.5 flex-wrap">
  8363. ${ipsHtml}
  8364. <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>
  8365. </div>
  8366. </td>
  8367. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8368. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8369. </td>
  8370. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8371. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8372. <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>
  8373. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8374. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8375. </td>
  8376. `;
  8377. tbody.appendChild(tr);
  8378. });
  8379. }
  8380. function openAddBridgeModal() {
  8381. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8382. document.getElementById('bridge-modal-id').value = '';
  8383. document.getElementById('bridge-modal-name').value = 'bridge1';
  8384. document.getElementById('bridge-modal-name').disabled = false;
  8385. document.getElementById('bridge-modal-mtu').value = '1500';
  8386. document.getElementById('bridge-modal-mac').value = '';
  8387. document.getElementById('bridge-modal-stp').value = 'rstp';
  8388. document.getElementById('bridge-modal-priority').value = '32768';
  8389. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8390. document.getElementById('bridge-modal-pvid').value = '1';
  8391. document.getElementById('bridge-modal-fastforward').checked = true;
  8392. document.getElementById('bridge-modal-comment').value = '';
  8393. document.getElementById('bridge-modal-disabled').checked = false;
  8394. toggleBridgeModalVlanFiltering();
  8395. document.getElementById('bridge-modal').classList.remove('hidden');
  8396. }
  8397. function openEditBridgeModal(id) {
  8398. const b = (state.bridges || []).find(x => x.id === id);
  8399. if (!b) return;
  8400. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8401. document.getElementById('bridge-modal-id').value = b.id;
  8402. document.getElementById('bridge-modal-name').value = b.name;
  8403. document.getElementById('bridge-modal-name').disabled = true;
  8404. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8405. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8406. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8407. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8408. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8409. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8410. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8411. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8412. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8413. toggleBridgeModalVlanFiltering();
  8414. document.getElementById('bridge-modal').classList.remove('hidden');
  8415. }
  8416. function closeBridgeModal() {
  8417. document.getElementById('bridge-modal').classList.add('hidden');
  8418. }
  8419. function toggleBridgeModalVlanFiltering() {
  8420. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8421. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8422. if (pvidBox) {
  8423. if (chk) pvidBox.classList.remove('opacity-40');
  8424. else pvidBox.classList.add('opacity-40');
  8425. }
  8426. }
  8427. async function submitSaveBridge(e) {
  8428. e.preventDefault();
  8429. const id = document.getElementById('bridge-modal-id').value;
  8430. const name = document.getElementById('bridge-modal-name').value.trim();
  8431. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8432. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8433. const stp = document.getElementById('bridge-modal-stp').value;
  8434. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8435. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8436. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8437. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8438. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8439. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8440. try {
  8441. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8442. method: 'POST',
  8443. headers: { 'Content-Type': 'application/json' },
  8444. body: JSON.stringify({
  8445. id,
  8446. name,
  8447. mtu,
  8448. mac_address: mac,
  8449. stp,
  8450. priority,
  8451. vlan_filtering: vlanFiltering,
  8452. pvid,
  8453. fast_forward: fastForward,
  8454. comment,
  8455. disabled
  8456. })
  8457. });
  8458. if (res.ok) {
  8459. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8460. closeBridgeModal();
  8461. loadBridge();
  8462. fetchData(false);
  8463. } else {
  8464. const err = await res.json();
  8465. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8466. }
  8467. } catch (err) {
  8468. showToast('Error', err.message, 'error');
  8469. }
  8470. }
  8471. async function toggleBridgeState(id, disabled) {
  8472. try {
  8473. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8474. method: 'POST',
  8475. headers: { 'Content-Type': 'application/json' },
  8476. body: JSON.stringify({ disabled })
  8477. });
  8478. if (res.ok) {
  8479. loadBridge();
  8480. fetchData(false);
  8481. }
  8482. } catch (err) {
  8483. showToast('Error', err.message, 'error');
  8484. }
  8485. }
  8486. async function deleteBridge(id) {
  8487. const b = (state.bridges || []).find(x => x.id === id);
  8488. const name = b ? b.name : id;
  8489. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8490. try {
  8491. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8492. if (res.ok) {
  8493. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8494. loadBridge();
  8495. fetchData(false);
  8496. } else {
  8497. const err = await res.json();
  8498. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8499. }
  8500. } catch (err) {
  8501. showToast('Error', err.message, 'error');
  8502. }
  8503. }
  8504. // ----------------- Bridge IP Assignments -----------------
  8505. function openAddBridgeIPModal(id, name) {
  8506. document.getElementById('bridge-ip-modal-id').value = id;
  8507. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8508. document.getElementById('bridge-ip-modal-cidr').value = '';
  8509. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8510. }
  8511. function closeBridgeIPModal() {
  8512. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8513. }
  8514. async function submitAddBridgeIP(e) {
  8515. e.preventDefault();
  8516. const id = document.getElementById('bridge-ip-modal-id').value;
  8517. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8518. try {
  8519. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8520. method: 'POST',
  8521. headers: { 'Content-Type': 'application/json' },
  8522. body: JSON.stringify({ ip })
  8523. });
  8524. if (res.ok) {
  8525. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8526. closeBridgeIPModal();
  8527. loadBridge();
  8528. fetchData(false);
  8529. } else {
  8530. const err = await res.json();
  8531. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8532. }
  8533. } catch (err) {
  8534. showToast('Error', err.message, 'error');
  8535. }
  8536. }
  8537. async function deleteBridgeIP(id, ip) {
  8538. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8539. try {
  8540. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8541. method: 'DELETE',
  8542. headers: { 'Content-Type': 'application/json' },
  8543. body: JSON.stringify({ ip })
  8544. });
  8545. if (res.ok) {
  8546. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8547. loadBridge();
  8548. fetchData(false);
  8549. }
  8550. } catch (err) {
  8551. showToast('Error', err.message, 'error');
  8552. }
  8553. }
  8554. // ----------------- Bridge Ports -----------------
  8555. function renderBridgePorts() {
  8556. const tbody = document.getElementById('bridge-ports-table-body');
  8557. const empty = document.getElementById('bridge-empty-ports');
  8558. const countBadge = document.getElementById('bridge-ports-count-badge');
  8559. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8560. if (!tbody) return;
  8561. tbody.innerHTML = '';
  8562. // Update filter select
  8563. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  8564. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  8565. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  8566. if (ports.length === 0) {
  8567. empty?.classList.remove('hidden');
  8568. return;
  8569. }
  8570. empty?.classList.add('hidden');
  8571. ports.forEach((p, idx) => {
  8572. const tr = document.createElement('tr');
  8573. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  8574. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8575. tr.innerHTML = `
  8576. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8577. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8578. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8579. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  8580. </td>
  8581. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  8582. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  8583. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  8584. <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>
  8585. <td class="py-2.5 px-3">
  8586. ${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>'}
  8587. </td>
  8588. <td class="py-2.5 px-3">
  8589. <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>
  8590. </td>
  8591. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  8592. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8593. <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>
  8594. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8595. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8596. </td>
  8597. `;
  8598. tbody.appendChild(tr);
  8599. });
  8600. }
  8601. function openAddBridgePortModal() {
  8602. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  8603. document.getElementById('bridge-port-modal-id').value = '';
  8604. populateBridgeSelect('bridge-port-modal-bridge');
  8605. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  8606. document.getElementById('bridge-port-modal-pvid').value = '1';
  8607. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  8608. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  8609. document.getElementById('bridge-port-modal-horizon').value = '0';
  8610. document.getElementById('bridge-port-modal-pathcost').value = '10';
  8611. document.getElementById('bridge-port-modal-priority').value = '128';
  8612. document.getElementById('bridge-port-modal-learn').checked = true;
  8613. document.getElementById('bridge-port-modal-comment').value = '';
  8614. document.getElementById('bridge-port-modal-disabled').checked = false;
  8615. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8616. }
  8617. function openEditBridgePortModal(id) {
  8618. const p = (state.bridgePorts || []).find(x => x.id === id);
  8619. if (!p) return;
  8620. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  8621. document.getElementById('bridge-port-modal-id').value = p.id;
  8622. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  8623. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  8624. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  8625. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  8626. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  8627. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  8628. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  8629. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  8630. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  8631. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  8632. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  8633. document.getElementById('bridge-port-modal').classList.remove('hidden');
  8634. }
  8635. function closeBridgePortModal() {
  8636. document.getElementById('bridge-port-modal').classList.add('hidden');
  8637. }
  8638. async function submitSaveBridgePort(e) {
  8639. e.preventDefault();
  8640. const id = document.getElementById('bridge-port-modal-id').value;
  8641. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  8642. const iface = document.getElementById('bridge-port-modal-interface').value;
  8643. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  8644. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  8645. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  8646. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  8647. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  8648. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  8649. const learn = document.getElementById('bridge-port-modal-learn').checked;
  8650. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  8651. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  8652. try {
  8653. const res = await fetch(`${API_BASE}/bridge/ports`, {
  8654. method: 'POST',
  8655. headers: { 'Content-Type': 'application/json' },
  8656. body: JSON.stringify({
  8657. id,
  8658. bridge,
  8659. interface: iface,
  8660. pvid,
  8661. frame_types: frameTypes,
  8662. ingress_filtering: ingressFiltering,
  8663. horizon,
  8664. path_cost: pathCost,
  8665. priority,
  8666. learn,
  8667. comment,
  8668. disabled
  8669. })
  8670. });
  8671. if (res.ok) {
  8672. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  8673. closeBridgePortModal();
  8674. loadBridge();
  8675. fetchData(false);
  8676. } else {
  8677. const err = await res.json();
  8678. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  8679. }
  8680. } catch (err) {
  8681. showToast('Error', err.message, 'error');
  8682. }
  8683. }
  8684. async function toggleBridgePortState(id, disabled) {
  8685. try {
  8686. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  8687. method: 'POST',
  8688. headers: { 'Content-Type': 'application/json' },
  8689. body: JSON.stringify({ disabled })
  8690. });
  8691. if (res.ok) {
  8692. loadBridge();
  8693. fetchData(false);
  8694. }
  8695. } catch (err) {
  8696. showToast('Error', err.message, 'error');
  8697. }
  8698. }
  8699. async function deleteBridgePort(id) {
  8700. const p = (state.bridgePorts || []).find(x => x.id === id);
  8701. const iface = p ? p.interface : id;
  8702. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  8703. try {
  8704. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8705. if (res.ok) {
  8706. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  8707. loadBridge();
  8708. fetchData(false);
  8709. }
  8710. } catch (err) {
  8711. showToast('Error', err.message, 'error');
  8712. }
  8713. }
  8714. // ----------------- Bridge VLANs -----------------
  8715. function renderBridgeVLANs() {
  8716. const tbody = document.getElementById('bridge-vlans-table-body');
  8717. const empty = document.getElementById('bridge-empty-vlans');
  8718. const countBadge = document.getElementById('bridge-vlans-count-badge');
  8719. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  8720. if (!tbody) return;
  8721. tbody.innerHTML = '';
  8722. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  8723. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  8724. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  8725. if (vlans.length === 0) {
  8726. empty?.classList.remove('hidden');
  8727. return;
  8728. }
  8729. empty?.classList.add('hidden');
  8730. vlans.forEach((v, idx) => {
  8731. const tr = document.createElement('tr');
  8732. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  8733. const taggedHtml = (v.tagged && v.tagged.length > 0)
  8734. ? 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(' ')
  8735. : '<span class="text-slate-600">none</span>';
  8736. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  8737. ? 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(' ')
  8738. : '<span class="text-slate-600">none</span>';
  8739. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  8740. tr.innerHTML = `
  8741. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8742. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  8743. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  8744. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  8745. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  8746. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  8747. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  8748. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8749. <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>
  8750. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8751. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8752. </td>
  8753. `;
  8754. tbody.appendChild(tr);
  8755. });
  8756. }
  8757. function openAddBridgeVLANModal() {
  8758. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  8759. document.getElementById('bridge-vlan-modal-id').value = '';
  8760. populateBridgeSelect('bridge-vlan-modal-bridge');
  8761. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  8762. document.getElementById('bridge-vlan-modal-comment').value = '';
  8763. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  8764. updateBridgeVlanPortCheckboxes();
  8765. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8766. }
  8767. function openEditBridgeVLANModal(id) {
  8768. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  8769. if (!v) return;
  8770. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  8771. document.getElementById('bridge-vlan-modal-id').value = v.id;
  8772. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  8773. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  8774. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  8775. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  8776. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  8777. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  8778. }
  8779. function closeBridgeVlanModal() {
  8780. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  8781. }
  8782. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  8783. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  8784. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  8785. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  8786. if (!taggedBox || !untaggedBox) return;
  8787. // Ports belonging to the selected bridge
  8788. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  8789. if (memberPorts.length === 0) {
  8790. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8791. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  8792. return;
  8793. }
  8794. taggedBox.innerHTML = memberPorts.map(p => `
  8795. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8796. <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">
  8797. <span>${p.interface}</span>
  8798. </label>
  8799. `).join('');
  8800. untaggedBox.innerHTML = memberPorts.map(p => `
  8801. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  8802. <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">
  8803. <span>${p.interface}</span>
  8804. </label>
  8805. `).join('');
  8806. }
  8807. async function submitSaveBridgeVLAN(e) {
  8808. e.preventDefault();
  8809. const id = document.getElementById('bridge-vlan-modal-id').value;
  8810. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  8811. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  8812. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  8813. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  8814. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  8815. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  8816. try {
  8817. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  8818. method: 'POST',
  8819. headers: { 'Content-Type': 'application/json' },
  8820. body: JSON.stringify({
  8821. id,
  8822. bridge,
  8823. vlan_ids: vlanIDs,
  8824. tagged,
  8825. untagged,
  8826. comment,
  8827. disabled
  8828. })
  8829. });
  8830. if (res.ok) {
  8831. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  8832. closeBridgeVlanModal();
  8833. loadBridge();
  8834. } else {
  8835. const err = await res.json();
  8836. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  8837. }
  8838. } catch (err) {
  8839. showToast('Error', err.message, 'error');
  8840. }
  8841. }
  8842. async function toggleBridgeVLANState(id, disabled) {
  8843. try {
  8844. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  8845. method: 'POST',
  8846. headers: { 'Content-Type': 'application/json' },
  8847. body: JSON.stringify({ disabled })
  8848. });
  8849. if (res.ok) loadBridge();
  8850. } catch (err) {
  8851. showToast('Error', err.message, 'error');
  8852. }
  8853. }
  8854. async function deleteBridgeVLAN(id) {
  8855. if (!confirm('Delete this bridge VLAN entry?')) return;
  8856. try {
  8857. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8858. if (res.ok) {
  8859. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  8860. loadBridge();
  8861. }
  8862. } catch (err) {
  8863. showToast('Error', err.message, 'error');
  8864. }
  8865. }
  8866. // ----------------- Hosts / MAC Table -----------------
  8867. async function loadBridgeHosts() {
  8868. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  8869. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  8870. try {
  8871. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  8872. const res = await fetch(url);
  8873. if (res.ok) {
  8874. state.bridgeHosts = await res.json();
  8875. renderBridgeHosts();
  8876. }
  8877. } catch (err) {
  8878. console.error('Failed to load bridge hosts:', err);
  8879. }
  8880. }
  8881. function renderBridgeHosts() {
  8882. const tbody = document.getElementById('bridge-hosts-table-body');
  8883. const empty = document.getElementById('bridge-empty-hosts');
  8884. const countBadge = document.getElementById('bridge-hosts-count-badge');
  8885. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  8886. if (!tbody) return;
  8887. tbody.innerHTML = '';
  8888. const hosts = (state.bridgeHosts || []).filter(h => {
  8889. if (!search) return true;
  8890. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  8891. });
  8892. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  8893. if (hosts.length === 0) {
  8894. empty?.classList.remove('hidden');
  8895. return;
  8896. }
  8897. empty?.classList.add('hidden');
  8898. hosts.forEach(h => {
  8899. const tr = document.createElement('tr');
  8900. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  8901. let flagBadges = '';
  8902. 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>';
  8903. 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>';
  8904. 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>';
  8905. tr.innerHTML = `
  8906. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  8907. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  8908. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  8909. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  8910. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  8911. <td class="py-2.5 px-3">${flagBadges}</td>
  8912. `;
  8913. tbody.appendChild(tr);
  8914. });
  8915. }
  8916. async function flushBridgeHosts() {
  8917. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  8918. if (!selBridge) {
  8919. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  8920. return;
  8921. }
  8922. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  8923. try {
  8924. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  8925. method: 'POST',
  8926. headers: { 'Content-Type': 'application/json' },
  8927. body: JSON.stringify({ bridge: selBridge })
  8928. });
  8929. if (res.ok) {
  8930. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  8931. loadBridgeHosts();
  8932. }
  8933. } catch (err) {
  8934. showToast('Error', err.message, 'error');
  8935. }
  8936. }
  8937. // ----------------- Helpers -----------------
  8938. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  8939. const sel = document.getElementById(selectId);
  8940. if (!sel) return;
  8941. const prevVal = currentVal || sel.value;
  8942. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  8943. (state.bridges || []).forEach(b => {
  8944. const opt = document.createElement('option');
  8945. opt.value = b.name;
  8946. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  8947. if (b.name === prevVal) opt.selected = true;
  8948. sel.appendChild(opt);
  8949. });
  8950. }
  8951. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  8952. const sel = document.getElementById(selectId);
  8953. if (!sel) return;
  8954. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  8955. // 1. Physical Interfaces
  8956. const grpPhys = document.createElement('optgroup');
  8957. grpPhys.label = 'Physical Interfaces';
  8958. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  8959. const opt = document.createElement('option');
  8960. opt.value = i.name;
  8961. opt.innerText = `${i.name} (${i.role || i.type})`;
  8962. if (i.name === currentVal) opt.selected = true;
  8963. grpPhys.appendChild(opt);
  8964. });
  8965. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  8966. // 2. VLAN Sub-interfaces
  8967. const grpVlans = document.createElement('optgroup');
  8968. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  8969. (state.vlans || []).forEach(v => {
  8970. const opt = document.createElement('option');
  8971. opt.value = v.name;
  8972. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  8973. if (v.name === currentVal) opt.selected = true;
  8974. grpVlans.appendChild(opt);
  8975. });
  8976. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  8977. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  8978. const grpEoip = document.createElement('optgroup');
  8979. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  8980. (state.eoipTunnels || []).forEach(t => {
  8981. const opt = document.createElement('option');
  8982. opt.value = t.name;
  8983. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  8984. if (t.name === currentVal) opt.selected = true;
  8985. grpEoip.appendChild(opt);
  8986. });
  8987. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  8988. }
  8989. // -------------------------------------------------------------
  8990. // RouterOS v7 Routing Filters Management (/routing filter)
  8991. // -------------------------------------------------------------
  8992. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  8993. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  8994. if (!state.rfSort) state.rfSort = {};
  8995. function switchRoutingFilterTab(tab) {
  8996. state.activeRoutingFilterTab = tab;
  8997. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  8998. tabs.forEach(t => {
  8999. const btn = document.getElementById(`tab-rf-${t}`);
  9000. const content = document.getElementById(`tab-content-rf-${t}`);
  9001. if (btn) {
  9002. if (t === tab) {
  9003. 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';
  9004. } else {
  9005. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9006. }
  9007. }
  9008. if (content) {
  9009. if (t === tab) content.classList.remove('hidden');
  9010. else content.classList.add('hidden');
  9011. }
  9012. });
  9013. const chainContainer = document.getElementById('rf-chain-filter-container');
  9014. if (chainContainer) {
  9015. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9016. else chainContainer.classList.add('hidden');
  9017. }
  9018. renderRoutingFilters();
  9019. }
  9020. function selectFilterRow(tab, id) {
  9021. if (state.selectedFilterRow[tab] === id) {
  9022. delete state.selectedFilterRow[tab];
  9023. } else {
  9024. state.selectedFilterRow[tab] = id;
  9025. }
  9026. if (tab === 'rules') renderRoutingFilterRules();
  9027. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9028. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9029. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9030. }
  9031. function openRoutingFilterNewModal() {
  9032. const tab = state.activeRoutingFilterTab || 'rules';
  9033. if (tab === 'rules') openAddRoutingFilterModal();
  9034. else if (tab === 'select-rules') openAddSelectRuleModal();
  9035. else if (tab === 'community-lists') openAddCommunityListModal();
  9036. else if (tab === 'as-lists') openAddASListModal();
  9037. }
  9038. function toggleSelectedRoutingFilter(disabled) {
  9039. const tab = state.activeRoutingFilterTab || 'rules';
  9040. const id = state.selectedFilterRow[tab];
  9041. if (!id) {
  9042. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9043. return;
  9044. }
  9045. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9046. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9047. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9048. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9049. }
  9050. function removeSelectedRoutingFilter() {
  9051. const tab = state.activeRoutingFilterTab || 'rules';
  9052. const id = state.selectedFilterRow[tab];
  9053. if (!id) {
  9054. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9055. return;
  9056. }
  9057. if (tab === 'rules') deleteRoutingFilter(id);
  9058. else if (tab === 'select-rules') deleteSelectRule(id);
  9059. else if (tab === 'community-lists') deleteCommunityList(id);
  9060. else if (tab === 'as-lists') deleteASList(id);
  9061. }
  9062. function searchRoutingFilters(q) {
  9063. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9064. renderRoutingFilters();
  9065. }
  9066. function sortFilterTable(tab, col) {
  9067. if (!state.rfSort) state.rfSort = {};
  9068. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9069. if (state.rfSort[tab].col === col) {
  9070. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9071. } else {
  9072. state.rfSort[tab].col = col;
  9073. state.rfSort[tab].asc = true;
  9074. }
  9075. const asc = state.rfSort[tab].asc;
  9076. let list = [];
  9077. if (tab === 'rules') list = state.routingFilters || [];
  9078. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9079. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9080. else if (tab === 'as-lists') list = state.routingASLists || [];
  9081. list.sort((a, b) => {
  9082. let valA = a[col] ?? '';
  9083. let valB = b[col] ?? '';
  9084. if (col === 'flags') {
  9085. valA = a.disabled ? 'X' : 'A';
  9086. valB = b.disabled ? 'X' : 'A';
  9087. }
  9088. if (typeof valA === 'number' && typeof valB === 'number') {
  9089. return asc ? valA - valB : valB - valA;
  9090. }
  9091. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9092. });
  9093. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9094. allCols.forEach(c => {
  9095. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9096. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9097. });
  9098. if (tab === 'rules') renderRoutingFilterRules();
  9099. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9100. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9101. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9102. }
  9103. function renderRoutingFilters() {
  9104. const navBadge = document.getElementById('badge-filters-count');
  9105. const allRules = state.routingFilters || [];
  9106. if (navBadge) navBadge.innerText = allRules.length;
  9107. // Populate chain filter select options and datalist
  9108. const chainSelect = document.getElementById('routing-filter-chain-select');
  9109. const chainDatalist = document.getElementById('dl-routing-chains');
  9110. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9111. if (chainSelect) {
  9112. const currentVal = state.filterChainSelected || 'all';
  9113. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9114. uniqueChains.map(ch => {
  9115. const count = allRules.filter(r => r.chain === ch).length;
  9116. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9117. }).join('');
  9118. chainSelect.value = currentVal;
  9119. }
  9120. if (chainDatalist) {
  9121. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9122. }
  9123. renderRoutingFilterRules();
  9124. renderRoutingFilterSelectRules();
  9125. renderRoutingFilterCommunityLists();
  9126. renderRoutingFilterASLists();
  9127. }
  9128. function filterRoutingFiltersByChain(chain) {
  9129. state.filterChainSelected = chain;
  9130. renderRoutingFilters();
  9131. }
  9132. // -------------------------------------------------------------
  9133. // TAB 1: RULES (/routing filter rule)
  9134. // -------------------------------------------------------------
  9135. function renderRoutingFilterRules() {
  9136. const tbody = document.getElementById('routing-filter-rules-tbody');
  9137. if (!tbody) return;
  9138. const empty = document.getElementById('rf-rules-empty');
  9139. const statusCount = document.getElementById('rf-status-count');
  9140. let list = (state.routingFilters || []).slice();
  9141. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9142. list = list.filter(r => r.chain === state.filterChainSelected);
  9143. }
  9144. const q = state.rfSearchQuery;
  9145. if (q) {
  9146. list = list.filter(r =>
  9147. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9148. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9149. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9150. (r.comment && r.comment.toLowerCase().includes(q))
  9151. );
  9152. }
  9153. if (!state.rfSort?.['rules']) {
  9154. list.sort((a, b) => {
  9155. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9156. return (a.rule_order || 0) - (b.rule_order || 0);
  9157. });
  9158. }
  9159. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9160. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9161. }
  9162. if (list.length === 0) {
  9163. tbody.innerHTML = '';
  9164. if (empty) empty.classList.remove('hidden');
  9165. return;
  9166. }
  9167. if (empty) empty.classList.add('hidden');
  9168. tbody.innerHTML = list.map(r => {
  9169. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9170. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9171. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9172. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9173. let ruleDisplay = '';
  9174. if (r.rule && r.rule.trim() !== '') {
  9175. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9176. } else {
  9177. let conds = [];
  9178. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9179. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9180. let act = r.action || 'accept';
  9181. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9182. }
  9183. return `
  9184. <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'}">
  9185. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9186. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9187. <td class="py-2 px-3">
  9188. <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>
  9189. </td>
  9190. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9191. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9192. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9193. <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>
  9194. <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>
  9195. <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'}">
  9196. ${r.disabled ? 'Enable' : 'Disable'}
  9197. </button>
  9198. <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">
  9199. Edit
  9200. </button>
  9201. <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">
  9202. ✕
  9203. </button>
  9204. </td>
  9205. </tr>
  9206. `;
  9207. }).join('');
  9208. }
  9209. // -------------------------------------------------------------
  9210. // TAB 2: SELECT RULES (/routing filter select-rule)
  9211. // -------------------------------------------------------------
  9212. function renderRoutingFilterSelectRules() {
  9213. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9214. if (!tbody) return;
  9215. const empty = document.getElementById('rf-select-rules-empty');
  9216. const statusCount = document.getElementById('rf-status-count');
  9217. let list = (state.routingSelectRules || []).slice();
  9218. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9219. list = list.filter(r => r.chain === state.filterChainSelected);
  9220. }
  9221. const q = state.rfSearchQuery;
  9222. if (q) {
  9223. list = list.filter(r =>
  9224. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9225. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9226. (r.comment && r.comment.toLowerCase().includes(q))
  9227. );
  9228. }
  9229. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9230. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9231. }
  9232. if (list.length === 0) {
  9233. tbody.innerHTML = '';
  9234. if (empty) empty.classList.remove('hidden');
  9235. return;
  9236. }
  9237. if (empty) empty.classList.add('hidden');
  9238. tbody.innerHTML = list.map(r => {
  9239. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9240. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9241. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9242. return `
  9243. <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'}">
  9244. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9245. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9246. <td class="py-2 px-3">
  9247. <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>
  9248. </td>
  9249. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9250. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9251. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9252. <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'}">
  9253. ${r.disabled ? 'Enable' : 'Disable'}
  9254. </button>
  9255. <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">
  9256. Edit
  9257. </button>
  9258. <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">
  9259. ✕
  9260. </button>
  9261. </td>
  9262. </tr>
  9263. `;
  9264. }).join('');
  9265. }
  9266. // -------------------------------------------------------------
  9267. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9268. // -------------------------------------------------------------
  9269. function renderRoutingFilterCommunityLists() {
  9270. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9271. if (!tbody) return;
  9272. const empty = document.getElementById('rf-comm-lists-empty');
  9273. const statusCount = document.getElementById('rf-status-count');
  9274. let list = (state.routingCommunityLists || []).slice();
  9275. const q = state.rfSearchQuery;
  9276. if (q) {
  9277. list = list.filter(cl =>
  9278. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9279. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9280. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9281. );
  9282. }
  9283. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9284. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9285. }
  9286. if (list.length === 0) {
  9287. tbody.innerHTML = '';
  9288. if (empty) empty.classList.remove('hidden');
  9289. return;
  9290. }
  9291. if (empty) empty.classList.add('hidden');
  9292. tbody.innerHTML = list.map(cl => {
  9293. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9294. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9295. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9296. const commBadges = (cl.communities || []).map(c =>
  9297. `<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>`
  9298. ).join(' ');
  9299. return `
  9300. <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'}">
  9301. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9302. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9303. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9304. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9305. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9306. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9307. <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'}">
  9308. ${cl.disabled ? 'Enable' : 'Disable'}
  9309. </button>
  9310. <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">
  9311. Edit
  9312. </button>
  9313. <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">
  9314. ✕
  9315. </button>
  9316. </td>
  9317. </tr>
  9318. `;
  9319. }).join('');
  9320. }
  9321. // -------------------------------------------------------------
  9322. // TAB 4: AS LISTS (/routing filter num-list)
  9323. // -------------------------------------------------------------
  9324. function renderRoutingFilterASLists() {
  9325. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9326. if (!tbody) return;
  9327. const empty = document.getElementById('rf-as-lists-empty');
  9328. const statusCount = document.getElementById('rf-status-count');
  9329. let list = (state.routingASLists || []).slice();
  9330. const q = state.rfSearchQuery;
  9331. if (q) {
  9332. list = list.filter(al =>
  9333. (al.name && al.name.toLowerCase().includes(q)) ||
  9334. (al.range && al.range.toLowerCase().includes(q)) ||
  9335. (al.comment && al.comment.toLowerCase().includes(q))
  9336. );
  9337. }
  9338. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9339. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9340. }
  9341. if (list.length === 0) {
  9342. tbody.innerHTML = '';
  9343. if (empty) empty.classList.remove('hidden');
  9344. return;
  9345. }
  9346. if (empty) empty.classList.add('hidden');
  9347. tbody.innerHTML = list.map(al => {
  9348. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9349. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9350. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9351. return `
  9352. <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'}">
  9353. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9354. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9355. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9356. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9357. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9358. <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'}">
  9359. ${al.disabled ? 'Enable' : 'Disable'}
  9360. </button>
  9361. <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">
  9362. Edit
  9363. </button>
  9364. <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">
  9365. ✕
  9366. </button>
  9367. </td>
  9368. </tr>
  9369. `;
  9370. }).join('');
  9371. }
  9372. // -------------------------------------------------------------
  9373. // SNIPPETS & WIZARD HELPERS
  9374. // -------------------------------------------------------------
  9375. function insertRuleSnippet(type) {
  9376. const textarea = document.getElementById('modal-rf-rule');
  9377. if (!textarea) return;
  9378. let snippet = '';
  9379. switch (type) {
  9380. case 'accept-default':
  9381. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9382. break;
  9383. case 'drop-rfc1918':
  9384. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9385. break;
  9386. case 'len-24':
  9387. snippet = 'if (dst-len > 24) { reject; }';
  9388. break;
  9389. case 'local-pref-150':
  9390. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9391. break;
  9392. case 'as-prepend-2':
  9393. snippet = 'set bgp-path-prepend 2; accept;';
  9394. break;
  9395. case 'set-comm':
  9396. snippet = 'set bgp-communities.add 65000:100; accept;';
  9397. break;
  9398. case 'match-comm':
  9399. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9400. break;
  9401. case 'reject-all':
  9402. snippet = 'reject;';
  9403. break;
  9404. }
  9405. if (!snippet) return;
  9406. if (!textarea.value.trim()) {
  9407. textarea.value = snippet;
  9408. } else {
  9409. textarea.value = textarea.value.trim() + '\n' + snippet;
  9410. }
  9411. }
  9412. function generateScriptFromWizard() {
  9413. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9414. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9415. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9416. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9417. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9418. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9419. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9420. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9421. const conds = [];
  9422. if (pfx) {
  9423. if (pfxLen) {
  9424. if (pfxLen.includes('-')) {
  9425. const parts = pfxLen.split('-');
  9426. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9427. } else {
  9428. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9429. }
  9430. } else {
  9431. conds.push(`dst in ${pfx}`);
  9432. }
  9433. }
  9434. if (proto && proto !== 'any') {
  9435. conds.push(`protocol ${proto}`);
  9436. }
  9437. if (asp) {
  9438. conds.push(`bgp-as-path "${asp}"`);
  9439. }
  9440. if (comm) {
  9441. conds.push(`bgp-communities includes ${comm}`);
  9442. }
  9443. const actions = [];
  9444. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9445. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9446. actions.push(`${act};`);
  9447. let code = '';
  9448. if (conds.length > 0) {
  9449. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9450. } else {
  9451. code = actions.join(' ');
  9452. }
  9453. const textarea = document.getElementById('modal-rf-rule');
  9454. if (textarea) textarea.value = code;
  9455. }
  9456. // -------------------------------------------------------------
  9457. // MODAL CRUD: RULES (/routing filter rule)
  9458. // -------------------------------------------------------------
  9459. function openAddRoutingFilterModal(defaultChain = '') {
  9460. const form = document.getElementById('routing-filter-form');
  9461. if (form) form.reset();
  9462. const idEl = document.getElementById('modal-rf-id');
  9463. if (idEl) idEl.value = '';
  9464. const titleEl = document.getElementById('modal-rf-title');
  9465. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9466. const chainEl = document.getElementById('modal-rf-chain');
  9467. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9468. const orderEl = document.getElementById('modal-rf-order');
  9469. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9470. const ruleEl = document.getElementById('modal-rf-rule');
  9471. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9472. const disEl = document.getElementById('modal-rf-disabled');
  9473. if (disEl) disEl.checked = false;
  9474. const modal = document.getElementById('modal-routing-filter');
  9475. if (modal) modal.classList.remove('hidden');
  9476. }
  9477. function openEditRoutingFilterModal(id) {
  9478. const r = (state.routingFilters || []).find(item => item.id === id);
  9479. if (!r) return;
  9480. const idEl = document.getElementById('modal-rf-id');
  9481. if (idEl) idEl.value = r.id;
  9482. const titleEl = document.getElementById('modal-rf-title');
  9483. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9484. const chainEl = document.getElementById('modal-rf-chain');
  9485. if (chainEl) chainEl.value = r.chain || '';
  9486. const orderEl = document.getElementById('modal-rf-order');
  9487. if (orderEl) orderEl.value = r.rule_order || 10;
  9488. const ruleEl = document.getElementById('modal-rf-rule');
  9489. if (ruleEl) {
  9490. if (r.rule) {
  9491. ruleEl.value = r.rule;
  9492. } else {
  9493. let conds = [];
  9494. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9495. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9496. let act = r.action || 'accept';
  9497. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9498. }
  9499. }
  9500. const comEl = document.getElementById('modal-rf-comment');
  9501. if (comEl) comEl.value = r.comment || '';
  9502. const disEl = document.getElementById('modal-rf-disabled');
  9503. if (disEl) disEl.checked = !!r.disabled;
  9504. const modal = document.getElementById('modal-routing-filter');
  9505. if (modal) modal.classList.remove('hidden');
  9506. }
  9507. function closeRoutingFilterModal() {
  9508. const modal = document.getElementById('modal-routing-filter');
  9509. if (modal) modal.classList.add('hidden');
  9510. }
  9511. async function submitRoutingFilter(e) {
  9512. if (e) e.preventDefault();
  9513. const payload = {
  9514. id: document.getElementById('modal-rf-id').value,
  9515. chain: document.getElementById('modal-rf-chain').value.trim(),
  9516. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9517. rule: document.getElementById('modal-rf-rule').value.trim(),
  9518. comment: document.getElementById('modal-rf-comment').value.trim(),
  9519. disabled: document.getElementById('modal-rf-disabled').checked
  9520. };
  9521. try {
  9522. const res = await fetch(`${API_BASE}/routing/filters`, {
  9523. method: 'POST',
  9524. headers: { 'Content-Type': 'application/json' },
  9525. body: JSON.stringify(payload)
  9526. });
  9527. if (res.ok) {
  9528. closeRoutingFilterModal();
  9529. showToast('Success', 'Routing filter rule saved', 'success');
  9530. loadDynamicRouting();
  9531. } else {
  9532. const err = await res.json();
  9533. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9534. }
  9535. } catch (err) {
  9536. showToast('Error', err.message, 'error');
  9537. }
  9538. }
  9539. async function applyRoutingFilterForm() {
  9540. const payload = {
  9541. id: document.getElementById('modal-rf-id').value,
  9542. chain: document.getElementById('modal-rf-chain').value.trim(),
  9543. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9544. rule: document.getElementById('modal-rf-rule').value.trim(),
  9545. comment: document.getElementById('modal-rf-comment').value.trim(),
  9546. disabled: document.getElementById('modal-rf-disabled').checked
  9547. };
  9548. try {
  9549. const res = await fetch(`${API_BASE}/routing/filters`, {
  9550. method: 'POST',
  9551. headers: { 'Content-Type': 'application/json' },
  9552. body: JSON.stringify(payload)
  9553. });
  9554. if (res.ok) {
  9555. const data = await res.json();
  9556. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  9557. showToast('Applied', 'Routing filter configuration applied', 'success');
  9558. loadDynamicRouting();
  9559. } else {
  9560. const err = await res.json();
  9561. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  9562. }
  9563. } catch (err) {
  9564. showToast('Error', err.message, 'error');
  9565. }
  9566. }
  9567. async function moveRoutingFilterOrder(id, delta) {
  9568. const list = state.routingFilters || [];
  9569. const idx = list.findIndex(r => r.id === id);
  9570. if (idx < 0) return;
  9571. const targetIdx = idx + delta;
  9572. if (targetIdx < 0 || targetIdx >= list.length) return;
  9573. const currentOrder = list[idx].rule_order || 10;
  9574. const targetOrder = list[targetIdx].rule_order || 20;
  9575. list[idx].rule_order = targetOrder;
  9576. list[targetIdx].rule_order = currentOrder;
  9577. try {
  9578. await fetch(`${API_BASE}/routing/filters`, {
  9579. method: 'POST',
  9580. headers: { 'Content-Type': 'application/json' },
  9581. body: JSON.stringify(list[idx])
  9582. });
  9583. await fetch(`${API_BASE}/routing/filters`, {
  9584. method: 'POST',
  9585. headers: { 'Content-Type': 'application/json' },
  9586. body: JSON.stringify(list[targetIdx])
  9587. });
  9588. loadDynamicRouting();
  9589. } catch (e) {
  9590. console.error('Reorder error:', e);
  9591. }
  9592. }
  9593. async function deleteRoutingFilter(id) {
  9594. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  9595. try {
  9596. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9597. if (res.ok) {
  9598. showToast('Deleted', 'Routing filter rule removed', 'info');
  9599. loadDynamicRouting();
  9600. } else {
  9601. const err = await res.json();
  9602. showToast('Error', err.error || 'Failed to delete rule', 'error');
  9603. }
  9604. } catch (err) {
  9605. showToast('Error', err.message, 'error');
  9606. }
  9607. }
  9608. async function toggleRoutingFilterState(id, disabled) {
  9609. try {
  9610. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  9611. method: 'POST',
  9612. headers: { 'Content-Type': 'application/json' },
  9613. body: JSON.stringify({ disabled })
  9614. });
  9615. if (res.ok) {
  9616. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9617. loadDynamicRouting();
  9618. } else {
  9619. const err = await res.json();
  9620. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  9621. }
  9622. } catch (err) {
  9623. showToast('Error', err.message, 'error');
  9624. }
  9625. }
  9626. // -------------------------------------------------------------
  9627. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  9628. // -------------------------------------------------------------
  9629. function openAddSelectRuleModal() {
  9630. document.getElementById('modal-rf-sr-id').value = '';
  9631. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  9632. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  9633. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  9634. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  9635. document.getElementById('modal-rf-sr-comment').value = '';
  9636. document.getElementById('modal-rf-sr-disabled').checked = false;
  9637. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9638. }
  9639. function openEditSelectRuleModal(id) {
  9640. const r = (state.routingSelectRules || []).find(item => item.id === id);
  9641. if (!r) return;
  9642. document.getElementById('modal-rf-sr-id').value = r.id;
  9643. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  9644. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  9645. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  9646. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  9647. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  9648. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  9649. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  9650. }
  9651. function closeSelectRuleModal() {
  9652. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  9653. }
  9654. async function submitSelectRule(e) {
  9655. e.preventDefault();
  9656. const payload = {
  9657. id: document.getElementById('modal-rf-sr-id').value,
  9658. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  9659. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  9660. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  9661. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  9662. disabled: document.getElementById('modal-rf-sr-disabled').checked
  9663. };
  9664. try {
  9665. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  9666. method: 'POST',
  9667. headers: { 'Content-Type': 'application/json' },
  9668. body: JSON.stringify(payload)
  9669. });
  9670. if (res.ok) {
  9671. closeSelectRuleModal();
  9672. showToast('Success', 'Select rule saved', 'success');
  9673. loadDynamicRouting();
  9674. } else {
  9675. const err = await res.json();
  9676. showToast('Error', err.error || 'Failed to save select rule', 'error');
  9677. }
  9678. } catch (err) {
  9679. showToast('Error', err.message, 'error');
  9680. }
  9681. }
  9682. async function deleteSelectRule(id) {
  9683. if (!confirm('Are you sure you want to delete this select rule?')) return;
  9684. try {
  9685. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9686. if (res.ok) {
  9687. showToast('Deleted', 'Select rule removed', 'info');
  9688. loadDynamicRouting();
  9689. } else {
  9690. const err = await res.json();
  9691. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  9692. }
  9693. } catch (err) {
  9694. showToast('Error', err.message, 'error');
  9695. }
  9696. }
  9697. async function toggleSelectRuleState(id, disabled) {
  9698. try {
  9699. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  9700. method: 'POST',
  9701. headers: { 'Content-Type': 'application/json' },
  9702. body: JSON.stringify({ disabled })
  9703. });
  9704. if (res.ok) {
  9705. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9706. loadDynamicRouting();
  9707. } else {
  9708. const err = await res.json();
  9709. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  9710. }
  9711. } catch (err) {
  9712. showToast('Error', err.message, 'error');
  9713. }
  9714. }
  9715. // -------------------------------------------------------------
  9716. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  9717. // -------------------------------------------------------------
  9718. function openAddCommunityListModal() {
  9719. document.getElementById('modal-rf-cl-id').value = '';
  9720. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  9721. document.getElementById('modal-rf-cl-name').value = '';
  9722. document.getElementById('modal-rf-cl-communities').value = '';
  9723. document.getElementById('modal-rf-cl-regexp').value = '';
  9724. document.getElementById('modal-rf-cl-comment').value = '';
  9725. document.getElementById('modal-rf-cl-disabled').checked = false;
  9726. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9727. }
  9728. function openEditCommunityListModal(id) {
  9729. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  9730. if (!cl) return;
  9731. document.getElementById('modal-rf-cl-id').value = cl.id;
  9732. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  9733. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  9734. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  9735. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  9736. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  9737. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  9738. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  9739. }
  9740. function closeCommunityListModal() {
  9741. document.getElementById('modal-rf-community-list').classList.add('hidden');
  9742. }
  9743. async function submitCommunityList(e) {
  9744. e.preventDefault();
  9745. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  9746. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  9747. const payload = {
  9748. id: document.getElementById('modal-rf-cl-id').value,
  9749. name: document.getElementById('modal-rf-cl-name').value.trim(),
  9750. communities: comms,
  9751. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  9752. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  9753. disabled: document.getElementById('modal-rf-cl-disabled').checked
  9754. };
  9755. try {
  9756. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  9757. method: 'POST',
  9758. headers: { 'Content-Type': 'application/json' },
  9759. body: JSON.stringify(payload)
  9760. });
  9761. if (res.ok) {
  9762. closeCommunityListModal();
  9763. showToast('Success', 'Community list saved', 'success');
  9764. loadDynamicRouting();
  9765. } else {
  9766. const err = await res.json();
  9767. showToast('Error', err.error || 'Failed to save community list', 'error');
  9768. }
  9769. } catch (err) {
  9770. showToast('Error', err.message, 'error');
  9771. }
  9772. }
  9773. async function deleteCommunityList(id) {
  9774. if (!confirm('Are you sure you want to delete this community list?')) return;
  9775. try {
  9776. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9777. if (res.ok) {
  9778. showToast('Deleted', 'Community list removed', 'info');
  9779. loadDynamicRouting();
  9780. } else {
  9781. const err = await res.json();
  9782. showToast('Error', err.error || 'Failed to delete community list', 'error');
  9783. }
  9784. } catch (err) {
  9785. showToast('Error', err.message, 'error');
  9786. }
  9787. }
  9788. async function toggleCommunityListState(id, disabled) {
  9789. try {
  9790. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  9791. method: 'POST',
  9792. headers: { 'Content-Type': 'application/json' },
  9793. body: JSON.stringify({ disabled })
  9794. });
  9795. if (res.ok) {
  9796. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9797. loadDynamicRouting();
  9798. } else {
  9799. const err = await res.json();
  9800. showToast('Error', err.error || 'Failed to update community list state', 'error');
  9801. }
  9802. } catch (err) {
  9803. showToast('Error', err.message, 'error');
  9804. }
  9805. }
  9806. // -------------------------------------------------------------
  9807. // MODAL CRUD: AS LISTS (/routing filter num-list)
  9808. // -------------------------------------------------------------
  9809. function openAddASListModal() {
  9810. document.getElementById('modal-rf-al-id').value = '';
  9811. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  9812. document.getElementById('modal-rf-al-name').value = '';
  9813. document.getElementById('modal-rf-al-range').value = '';
  9814. document.getElementById('modal-rf-al-comment').value = '';
  9815. document.getElementById('modal-rf-al-disabled').checked = false;
  9816. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9817. }
  9818. function openEditASListModal(id) {
  9819. const al = (state.routingASLists || []).find(item => item.id === id);
  9820. if (!al) return;
  9821. document.getElementById('modal-rf-al-id').value = al.id;
  9822. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  9823. document.getElementById('modal-rf-al-name').value = al.name || '';
  9824. document.getElementById('modal-rf-al-range').value = al.range || '';
  9825. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  9826. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  9827. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  9828. }
  9829. function closeASListModal() {
  9830. document.getElementById('modal-rf-as-list').classList.add('hidden');
  9831. }
  9832. async function submitASList(e) {
  9833. e.preventDefault();
  9834. const payload = {
  9835. id: document.getElementById('modal-rf-al-id').value,
  9836. name: document.getElementById('modal-rf-al-name').value.trim(),
  9837. range: document.getElementById('modal-rf-al-range').value.trim(),
  9838. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  9839. disabled: document.getElementById('modal-rf-al-disabled').checked
  9840. };
  9841. try {
  9842. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  9843. method: 'POST',
  9844. headers: { 'Content-Type': 'application/json' },
  9845. body: JSON.stringify(payload)
  9846. });
  9847. if (res.ok) {
  9848. closeASListModal();
  9849. showToast('Success', 'AS number list saved', 'success');
  9850. loadDynamicRouting();
  9851. } else {
  9852. const err = await res.json();
  9853. showToast('Error', err.error || 'Failed to save AS list', 'error');
  9854. }
  9855. } catch (err) {
  9856. showToast('Error', err.message, 'error');
  9857. }
  9858. }
  9859. async function deleteASList(id) {
  9860. if (!confirm('Are you sure you want to delete this AS list?')) return;
  9861. try {
  9862. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9863. if (res.ok) {
  9864. showToast('Deleted', 'AS list removed', 'info');
  9865. loadDynamicRouting();
  9866. } else {
  9867. const err = await res.json();
  9868. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  9869. }
  9870. } catch (err) {
  9871. showToast('Error', err.message, 'error');
  9872. }
  9873. }
  9874. async function toggleASListState(id, disabled) {
  9875. try {
  9876. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  9877. method: 'POST',
  9878. headers: { 'Content-Type': 'application/json' },
  9879. body: JSON.stringify({ disabled })
  9880. });
  9881. if (res.ok) {
  9882. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  9883. loadDynamicRouting();
  9884. } else {
  9885. const err = await res.json();
  9886. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  9887. }
  9888. } catch (err) {
  9889. showToast('Error', err.message, 'error');
  9890. }
  9891. }
  9892. // ==========================================
  9893. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  9894. // ==========================================
  9895. function loadToolsView() {
  9896. populateToolsInterfaces();
  9897. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  9898. }
  9899. function populateToolsInterfaces() {
  9900. const pingSel = document.getElementById('tools-ping-iface');
  9901. const traceSel = document.getElementById('tools-tr-iface');
  9902. let opts = '<option value="">Auto (Default Route)</option>';
  9903. if (Array.isArray(state.interfaces)) {
  9904. state.interfaces.forEach(iface => {
  9905. if (iface.name) {
  9906. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  9907. }
  9908. });
  9909. }
  9910. if (pingSel) {
  9911. const cur = pingSel.value;
  9912. pingSel.innerHTML = opts;
  9913. if (cur) pingSel.value = cur;
  9914. }
  9915. if (traceSel) {
  9916. const cur = traceSel.value;
  9917. traceSel.innerHTML = opts;
  9918. if (cur) traceSel.value = cur;
  9919. }
  9920. }
  9921. function switchToolsSubTab(subTab) {
  9922. state.activeToolsSubTab = subTab;
  9923. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  9924. tabs.forEach(t => {
  9925. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  9926. const view = document.getElementById(`tools-view-${t}`);
  9927. if (btn) {
  9928. if (t === subTab) {
  9929. 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';
  9930. } else {
  9931. 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';
  9932. }
  9933. }
  9934. if (view) {
  9935. if (t === subTab) {
  9936. view.classList.remove('hidden');
  9937. } else {
  9938. view.classList.add('hidden');
  9939. }
  9940. }
  9941. });
  9942. }
  9943. function setPortPreset(port) {
  9944. const input = document.getElementById('tools-port-num');
  9945. if (input) input.value = port;
  9946. }
  9947. let pingAbortController = null;
  9948. let tracerouteAbortController = null;
  9949. function clearPingTable() {
  9950. const tbody = document.getElementById('tools-ping-tbody');
  9951. if (tbody) tbody.innerHTML = '';
  9952. const rawEl = document.getElementById('tools-ping-raw');
  9953. if (rawEl) rawEl.innerText = '';
  9954. const sentEl = document.getElementById('tools-ping-stat-sent');
  9955. if (sentEl) sentEl.innerText = '0';
  9956. const recvEl = document.getElementById('tools-ping-stat-recv');
  9957. if (recvEl) recvEl.innerText = '0';
  9958. const lossEl = document.getElementById('tools-ping-stat-loss');
  9959. if (lossEl) lossEl.innerText = '0%';
  9960. const avgEl = document.getElementById('tools-ping-stat-avg');
  9961. if (avgEl) avgEl.innerText = '0 ms';
  9962. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  9963. if (minMaxEl) minMaxEl.innerText = '-';
  9964. const badge = document.getElementById('tools-ping-status-badge');
  9965. if (badge) {
  9966. badge.className = '';
  9967. badge.innerText = '';
  9968. }
  9969. }
  9970. function clearTracerouteTable() {
  9971. const tbody = document.getElementById('tools-tr-tbody');
  9972. if (tbody) tbody.innerHTML = '';
  9973. const rawEl = document.getElementById('tools-tr-raw');
  9974. if (rawEl) rawEl.innerText = '';
  9975. const statHops = document.getElementById('tools-tr-hops-count');
  9976. if (statHops) statHops.innerText = '0 Hops';
  9977. }
  9978. function resetPingButton() {
  9979. const btn = document.getElementById('tools-ping-btn');
  9980. const btnText = document.getElementById('tools-ping-btn-text');
  9981. const spinner = document.getElementById('tools-ping-spinner');
  9982. if (btn) {
  9983. btn.disabled = false;
  9984. 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';
  9985. }
  9986. if (btnText) btnText.innerText = 'Start Ping';
  9987. if (spinner) spinner.classList.add('hidden');
  9988. }
  9989. function setPingRunningButton() {
  9990. const btn = document.getElementById('tools-ping-btn');
  9991. const btnText = document.getElementById('tools-ping-btn-text');
  9992. const spinner = document.getElementById('tools-ping-spinner');
  9993. if (btn) {
  9994. btn.disabled = false;
  9995. 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';
  9996. }
  9997. if (btnText) btnText.innerText = 'Stop Ping';
  9998. if (spinner) spinner.classList.remove('hidden');
  9999. }
  10000. function resetTracerouteButton() {
  10001. const btn = document.getElementById('tools-tr-btn');
  10002. const btnText = document.getElementById('tools-tr-btn-text');
  10003. const spinner = document.getElementById('tools-tr-spinner');
  10004. if (btn) {
  10005. btn.disabled = false;
  10006. 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';
  10007. }
  10008. if (btnText) btnText.innerText = 'Start Traceroute';
  10009. if (spinner) spinner.classList.add('hidden');
  10010. }
  10011. function setTracerouteRunningButton() {
  10012. const btn = document.getElementById('tools-tr-btn');
  10013. const btnText = document.getElementById('tools-tr-btn-text');
  10014. const spinner = document.getElementById('tools-tr-spinner');
  10015. if (btn) {
  10016. btn.disabled = false;
  10017. 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';
  10018. }
  10019. if (btnText) btnText.innerText = 'Stop Traceroute';
  10020. if (spinner) spinner.classList.remove('hidden');
  10021. }
  10022. async function executePing(e) {
  10023. if (e) e.preventDefault();
  10024. // If already running, clicking the button stops the stream!
  10025. if (pingAbortController) {
  10026. pingAbortController.abort();
  10027. pingAbortController = null;
  10028. resetPingButton();
  10029. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10030. return;
  10031. }
  10032. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10033. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10034. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10035. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10036. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10037. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10038. if (!target) {
  10039. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10040. return;
  10041. }
  10042. clearPingTable();
  10043. const resCard = document.getElementById('tools-ping-results');
  10044. if (resCard) resCard.classList.remove('hidden');
  10045. pingAbortController = new AbortController();
  10046. setPingRunningButton();
  10047. try {
  10048. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10049. method: 'POST',
  10050. headers: { 'Content-Type': 'application/json' },
  10051. body: JSON.stringify({
  10052. target,
  10053. count,
  10054. size,
  10055. timeout,
  10056. interface: iface,
  10057. dont_frag: dontFrag
  10058. }),
  10059. signal: pingAbortController.signal
  10060. });
  10061. if (!res.ok) {
  10062. const errText = await res.text();
  10063. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10064. resetPingButton();
  10065. pingAbortController = null;
  10066. return;
  10067. }
  10068. const reader = res.body.getReader();
  10069. const decoder = new TextDecoder('utf-8');
  10070. let buffer = '';
  10071. while (true) {
  10072. const { done, value } = await reader.read();
  10073. if (done) break;
  10074. buffer += decoder.decode(value, { stream: true });
  10075. const blocks = buffer.split('\n\n');
  10076. buffer = blocks.pop() || '';
  10077. for (const block of blocks) {
  10078. const trimmed = block.trim();
  10079. if (!trimmed) continue;
  10080. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10081. try {
  10082. const evt = JSON.parse(line);
  10083. handleLivePingEvent(evt);
  10084. } catch (parseErr) {
  10085. console.warn('Ping SSE parse error:', parseErr, line);
  10086. }
  10087. }
  10088. }
  10089. } catch (err) {
  10090. if (err.name === 'AbortError') {
  10091. // User aborted normally
  10092. } else {
  10093. showToast('Ping Error', err.message, 'error');
  10094. }
  10095. } finally {
  10096. pingAbortController = null;
  10097. resetPingButton();
  10098. }
  10099. }
  10100. function handleLivePingEvent(evt) {
  10101. const sentEl = document.getElementById('tools-ping-stat-sent');
  10102. const recvEl = document.getElementById('tools-ping-stat-recv');
  10103. const lossEl = document.getElementById('tools-ping-stat-loss');
  10104. const avgEl = document.getElementById('tools-ping-stat-avg');
  10105. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10106. const badge = document.getElementById('tools-ping-status-badge');
  10107. const tbody = document.getElementById('tools-ping-tbody');
  10108. const rawEl = document.getElementById('tools-ping-raw');
  10109. if (evt.raw && rawEl) {
  10110. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10111. rawEl.scrollTop = rawEl.scrollHeight;
  10112. }
  10113. if (evt.type === 'reply') {
  10114. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10115. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10116. if (lossEl && evt.packet_loss_pct !== undefined) {
  10117. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10118. lossEl.className = evt.packet_loss_pct === 0
  10119. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10120. : (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');
  10121. }
  10122. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10123. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10124. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10125. }
  10126. if (badge) {
  10127. if (evt.packet_loss_pct === 0) {
  10128. 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';
  10129. badge.innerText = '100% OK';
  10130. } else {
  10131. 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';
  10132. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10133. }
  10134. }
  10135. if (tbody) {
  10136. const tr = document.createElement('tr');
  10137. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10138. tr.innerHTML = `
  10139. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10140. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10141. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10142. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10143. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10144. <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>
  10145. `;
  10146. tbody.appendChild(tr);
  10147. }
  10148. } else if (evt.type === 'timeout') {
  10149. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10150. if (lossEl && evt.packet_loss_pct !== undefined) {
  10151. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10152. 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';
  10153. }
  10154. if (badge) {
  10155. 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';
  10156. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10157. }
  10158. if (tbody) {
  10159. const tr = document.createElement('tr');
  10160. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10161. tr.innerHTML = `
  10162. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10163. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10164. <td class="py-2 px-3 text-slate-600">--</td>
  10165. <td class="py-2 px-3 text-slate-600">--</td>
  10166. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10167. <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>
  10168. `;
  10169. tbody.appendChild(tr);
  10170. }
  10171. } else if (evt.type === 'unreach') {
  10172. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10173. if (lossEl && evt.packet_loss_pct !== undefined) {
  10174. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10175. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10176. }
  10177. if (badge) {
  10178. 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';
  10179. badge.innerText = 'UNREACHABLE';
  10180. }
  10181. if (tbody) {
  10182. const tr = document.createElement('tr');
  10183. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10184. tr.innerHTML = `
  10185. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10186. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10187. <td class="py-2 px-3 text-slate-600">--</td>
  10188. <td class="py-2 px-3 text-slate-600">--</td>
  10189. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10190. <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>
  10191. `;
  10192. tbody.appendChild(tr);
  10193. }
  10194. } else if (evt.type === 'stats') {
  10195. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10196. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10197. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10198. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10199. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10200. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10201. }
  10202. } else if (evt.type === 'done') {
  10203. 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');
  10204. }
  10205. }
  10206. async function executeTraceroute(e) {
  10207. if (e) e.preventDefault();
  10208. if (tracerouteAbortController) {
  10209. tracerouteAbortController.abort();
  10210. tracerouteAbortController = null;
  10211. resetTracerouteButton();
  10212. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10213. return;
  10214. }
  10215. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10216. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10217. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10218. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10219. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10220. if (!target) {
  10221. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10222. return;
  10223. }
  10224. clearTracerouteTable();
  10225. const resCard = document.getElementById('tools-tr-results');
  10226. if (resCard) resCard.classList.remove('hidden');
  10227. tracerouteAbortController = new AbortController();
  10228. setTracerouteRunningButton();
  10229. try {
  10230. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10231. method: 'POST',
  10232. headers: { 'Content-Type': 'application/json' },
  10233. body: JSON.stringify({
  10234. target,
  10235. max_hops: maxHops,
  10236. protocol,
  10237. interface: iface,
  10238. resolve
  10239. }),
  10240. signal: tracerouteAbortController.signal
  10241. });
  10242. if (!res.ok) {
  10243. const errText = await res.text();
  10244. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10245. resetTracerouteButton();
  10246. tracerouteAbortController = null;
  10247. return;
  10248. }
  10249. const reader = res.body.getReader();
  10250. const decoder = new TextDecoder('utf-8');
  10251. let buffer = '';
  10252. while (true) {
  10253. const { done, value } = await reader.read();
  10254. if (done) break;
  10255. buffer += decoder.decode(value, { stream: true });
  10256. const blocks = buffer.split('\n\n');
  10257. buffer = blocks.pop() || '';
  10258. for (const block of blocks) {
  10259. const trimmed = block.trim();
  10260. if (!trimmed) continue;
  10261. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10262. try {
  10263. const evt = JSON.parse(line);
  10264. handleLiveTracerouteEvent(evt);
  10265. } catch (parseErr) {
  10266. console.warn('Traceroute SSE parse error:', parseErr, line);
  10267. }
  10268. }
  10269. }
  10270. } catch (err) {
  10271. if (err.name === 'AbortError') {
  10272. // User aborted normally
  10273. } else {
  10274. showToast('Traceroute Error', err.message, 'error');
  10275. }
  10276. } finally {
  10277. tracerouteAbortController = null;
  10278. resetTracerouteButton();
  10279. }
  10280. }
  10281. function handleLiveTracerouteEvent(evt) {
  10282. const statHops = document.getElementById('tools-tr-hops-count');
  10283. const tbody = document.getElementById('tools-tr-tbody');
  10284. const rawEl = document.getElementById('tools-tr-raw');
  10285. if (evt.raw && rawEl) {
  10286. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10287. rawEl.scrollTop = rawEl.scrollHeight;
  10288. }
  10289. if (evt.hops_count !== undefined && statHops) {
  10290. statHops.innerText = `${evt.hops_count} Hops`;
  10291. }
  10292. if (evt.type === 'hop' && evt.hop && tbody) {
  10293. const h = evt.hop;
  10294. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10295. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10296. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10297. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10298. const tr = document.createElement('tr');
  10299. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10300. tr.innerHTML = `
  10301. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10302. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10303. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10304. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10305. <td class="py-2.5 px-3 text-right">
  10306. ${isTimeout
  10307. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10308. : '<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>'}
  10309. </td>
  10310. `;
  10311. tbody.appendChild(tr);
  10312. } else if (evt.type === 'done') {
  10313. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10314. }
  10315. }
  10316. async function executeMTR(e) {
  10317. if (e) e.preventDefault();
  10318. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10319. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10320. if (!target) {
  10321. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10322. return;
  10323. }
  10324. const btn = document.getElementById('tools-mtr-btn');
  10325. const spinner = document.getElementById('tools-mtr-spinner');
  10326. if (btn) btn.disabled = true;
  10327. if (spinner) spinner.classList.remove('hidden');
  10328. try {
  10329. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10330. method: 'POST',
  10331. headers: { 'Content-Type': 'application/json' },
  10332. body: JSON.stringify({ target, count: cycles })
  10333. });
  10334. const data = await res.json();
  10335. if (!res.ok) {
  10336. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10337. return;
  10338. }
  10339. const resCard = document.getElementById('tools-mtr-results');
  10340. if (resCard) resCard.classList.remove('hidden');
  10341. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10342. const statHops = document.getElementById('tools-mtr-hops-count');
  10343. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10344. const tbody = document.getElementById('tools-mtr-tbody');
  10345. if (tbody) {
  10346. if (hopsCount > 0) {
  10347. tbody.innerHTML = data.hops.map(h => {
  10348. 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');
  10349. return `
  10350. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10351. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10352. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10353. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10354. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10355. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10356. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10357. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10358. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10359. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10360. </tr>
  10361. `;
  10362. }).join('');
  10363. } else {
  10364. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10365. }
  10366. }
  10367. const rawEl = document.getElementById('tools-mtr-raw');
  10368. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10369. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10370. } catch (err) {
  10371. showToast('MTR Error', err.message, 'error');
  10372. } finally {
  10373. if (btn) btn.disabled = false;
  10374. if (spinner) spinner.classList.add('hidden');
  10375. }
  10376. }
  10377. async function executeDNS(e) {
  10378. if (e) e.preventDefault();
  10379. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10380. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10381. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10382. if (!domain) {
  10383. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10384. return;
  10385. }
  10386. const btn = document.getElementById('tools-dns-btn');
  10387. const spinner = document.getElementById('tools-dns-spinner');
  10388. if (btn) btn.disabled = true;
  10389. if (spinner) spinner.classList.remove('hidden');
  10390. try {
  10391. const res = await fetch(`${API_BASE}/tools/dns`, {
  10392. method: 'POST',
  10393. headers: { 'Content-Type': 'application/json' },
  10394. body: JSON.stringify({ domain, type, server })
  10395. });
  10396. const data = await res.json();
  10397. if (!res.ok) {
  10398. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10399. return;
  10400. }
  10401. const resCard = document.getElementById('tools-dns-results');
  10402. if (resCard) resCard.classList.remove('hidden');
  10403. const metaEl = document.getElementById('tools-dns-meta');
  10404. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10405. const tbody = document.getElementById('tools-dns-tbody');
  10406. if (tbody) {
  10407. if (Array.isArray(data.records) && data.records.length > 0) {
  10408. tbody.innerHTML = data.records.map(r => `
  10409. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10410. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10411. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10412. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10413. <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>
  10414. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10415. </tr>
  10416. `).join('');
  10417. } else {
  10418. 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>`;
  10419. }
  10420. }
  10421. const rawEl = document.getElementById('tools-dns-raw');
  10422. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10423. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10424. } catch (err) {
  10425. showToast('DNS Error', err.message, 'error');
  10426. } finally {
  10427. if (btn) btn.disabled = false;
  10428. if (spinner) spinner.classList.add('hidden');
  10429. }
  10430. }
  10431. async function executePortProbe(e) {
  10432. if (e) e.preventDefault();
  10433. const target = document.getElementById('tools-port-target')?.value?.trim();
  10434. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10435. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10436. if (!target || !port) {
  10437. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10438. return;
  10439. }
  10440. const btn = document.getElementById('tools-port-btn');
  10441. const spinner = document.getElementById('tools-port-spinner');
  10442. if (btn) btn.disabled = true;
  10443. if (spinner) spinner.classList.remove('hidden');
  10444. try {
  10445. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10446. method: 'POST',
  10447. headers: { 'Content-Type': 'application/json' },
  10448. body: JSON.stringify({ target, port, timeout })
  10449. });
  10450. const data = await res.json();
  10451. if (!res.ok) {
  10452. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10453. return;
  10454. }
  10455. const resCard = document.getElementById('tools-port-results');
  10456. if (resCard) resCard.classList.remove('hidden');
  10457. const banner = document.getElementById('tools-port-banner');
  10458. const icon = document.getElementById('tools-port-icon');
  10459. const title = document.getElementById('tools-port-title');
  10460. const sub = document.getElementById('tools-port-sub');
  10461. const latency = document.getElementById('tools-port-latency');
  10462. if (data.open) {
  10463. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10464. if (icon) {
  10465. 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';
  10466. icon.innerText = '✓';
  10467. }
  10468. if (title) {
  10469. title.className = 'text-sm font-bold text-emerald-300';
  10470. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10471. }
  10472. if (sub) {
  10473. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10474. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10475. }
  10476. if (latency) {
  10477. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10478. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10479. }
  10480. } else {
  10481. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10482. if (icon) {
  10483. 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';
  10484. icon.innerText = '✕';
  10485. }
  10486. if (title) {
  10487. title.className = 'text-sm font-bold text-rose-300';
  10488. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10489. }
  10490. if (sub) {
  10491. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10492. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10493. }
  10494. if (latency) {
  10495. latency.className = 'text-base font-bold font-mono text-slate-500';
  10496. latency.innerText = '--';
  10497. }
  10498. }
  10499. const rawEl = document.getElementById('tools-port-raw');
  10500. 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'}`);
  10501. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10502. } catch (err) {
  10503. showToast('Probe Error', err.message, 'error');
  10504. } finally {
  10505. if (btn) btn.disabled = false;
  10506. if (spinner) spinner.classList.add('hidden');
  10507. }
  10508. }
  10509. // ==========================================
  10510. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10511. // ==========================================
  10512. async function loadDHCPClients(showToastMsg = false) {
  10513. try {
  10514. const [clientsRes, sumRes] = await Promise.all([
  10515. fetch(`${API_BASE}/dhcp/clients`),
  10516. fetch(`${API_BASE}/dhcp/clients/summary`)
  10517. ]);
  10518. if (clientsRes.ok) {
  10519. state.dhcpClients = await clientsRes.json();
  10520. }
  10521. if (sumRes.ok) {
  10522. state.dhcpSummary = await sumRes.json();
  10523. }
  10524. renderDHCPClients();
  10525. updateDHCPSummaryCards();
  10526. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10527. if (bDhcp && state.dhcpSummary) {
  10528. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10529. }
  10530. if (showToastMsg) {
  10531. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10532. }
  10533. } catch (err) {
  10534. console.error('Failed to load DHCP clients:', err);
  10535. if (showToastMsg) {
  10536. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10537. }
  10538. }
  10539. }
  10540. function updateDHCPSummaryCards() {
  10541. const sum = state.dhcpSummary || {
  10542. total_clients: (state.dhcpClients || []).length,
  10543. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10544. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10545. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10546. };
  10547. const totalEl = document.getElementById('dhcp-stat-total');
  10548. const boundEl = document.getElementById('dhcp-stat-bound');
  10549. const searchEl = document.getElementById('dhcp-stat-searching');
  10550. const disEl = document.getElementById('dhcp-stat-disabled');
  10551. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10552. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10553. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10554. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  10555. }
  10556. function renderDHCPClients() {
  10557. const tbody = document.getElementById('dhcp-clients-tbody');
  10558. const emptyState = document.getElementById('dhcp-clients-empty');
  10559. if (!tbody) return;
  10560. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  10561. if (clients.length === 0) {
  10562. tbody.innerHTML = '';
  10563. if (emptyState) emptyState.classList.remove('hidden');
  10564. return;
  10565. }
  10566. if (emptyState) emptyState.classList.add('hidden');
  10567. tbody.innerHTML = clients.map(c => {
  10568. let statusBadge = '';
  10569. if (!c.enabled) {
  10570. 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>';
  10571. } else if (c.status === 'bound') {
  10572. 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>';
  10573. } else if (c.status === 'searching') {
  10574. 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>';
  10575. } else if (c.status === 'stopped') {
  10576. 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>';
  10577. } else {
  10578. 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>`;
  10579. }
  10580. 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>';
  10581. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  10582. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  10583. 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>';
  10584. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  10585. // Option flags
  10586. const flags = [];
  10587. 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>');
  10588. 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>');
  10589. 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>');
  10590. 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>`);
  10591. return `
  10592. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  10593. <td class="py-3 px-4">
  10594. <div class="flex items-center gap-2">
  10595. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  10596. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  10597. </div>
  10598. </td>
  10599. <td class="py-3 px-4">${statusBadge}</td>
  10600. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  10601. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  10602. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  10603. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  10604. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  10605. <td class="py-3 px-4">
  10606. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  10607. </td>
  10608. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  10609. ${c.enabled ? `
  10610. <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>
  10611. <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>
  10612. <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>
  10613. ` : `
  10614. <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>
  10615. `}
  10616. <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>
  10617. <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>
  10618. </td>
  10619. </tr>
  10620. `;
  10621. }).join('');
  10622. }
  10623. function openDHCPClientModal(clientId = null) {
  10624. const modal = document.getElementById('modal-dhcp-client');
  10625. if (!modal) return;
  10626. const title = document.getElementById('modal-dhcp-title');
  10627. const idInput = document.getElementById('modal-dhcp-id');
  10628. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10629. const distInput = document.getElementById('modal-dhcp-distance');
  10630. const commentInput = document.getElementById('modal-dhcp-comment');
  10631. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  10632. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  10633. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  10634. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  10635. // Populate interfaces
  10636. if (ifaceSelect) {
  10637. let opts = '<option value="">Select interface...</option>';
  10638. const allIfaces = state.interfaces || [];
  10639. const allVlans = state.vlans || [];
  10640. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  10641. // Group 1: Physical & Bridge Interfaces
  10642. opts += '<optgroup label="Physical & Bridge Interfaces">';
  10643. allIfaces.forEach(i => {
  10644. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  10645. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  10646. });
  10647. opts += '</optgroup>';
  10648. // Group 2: VLAN Interfaces
  10649. if (allVlans.length > 0) {
  10650. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  10651. allVlans.forEach(v => {
  10652. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  10653. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  10654. });
  10655. opts += '</optgroup>';
  10656. }
  10657. ifaceSelect.innerHTML = opts;
  10658. }
  10659. if (clientId) {
  10660. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  10661. if (client) {
  10662. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  10663. if (idInput) idInput.value = client.id;
  10664. if (ifaceSelect) {
  10665. ifaceSelect.value = client.interface;
  10666. ifaceSelect.disabled = true; // interface cannot be changed on edit
  10667. }
  10668. if (distInput) distInput.value = client.default_route_distance || 1;
  10669. if (commentInput) commentInput.value = client.comment || '';
  10670. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  10671. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  10672. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  10673. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  10674. }
  10675. } else {
  10676. if (title) title.innerText = 'Add DHCP Client';
  10677. if (idInput) idInput.value = '';
  10678. if (ifaceSelect) {
  10679. ifaceSelect.value = '';
  10680. ifaceSelect.disabled = false;
  10681. }
  10682. if (distInput) distInput.value = 1;
  10683. if (commentInput) commentInput.value = '';
  10684. if (defRouteCheck) defRouteCheck.checked = true;
  10685. if (peerDnsCheck) peerDnsCheck.checked = true;
  10686. if (peerNtpCheck) peerNtpCheck.checked = true;
  10687. if (enabledCheck) enabledCheck.checked = true;
  10688. }
  10689. modal.classList.remove('hidden');
  10690. }
  10691. function openDHCPClientModalForIface(ifaceName) {
  10692. openDHCPClientModal();
  10693. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  10694. if (ifaceSelect && ifaceName) {
  10695. ifaceSelect.value = ifaceName;
  10696. }
  10697. }
  10698. function closeDHCPClientModal() {
  10699. const modal = document.getElementById('modal-dhcp-client');
  10700. if (modal) modal.classList.add('hidden');
  10701. }
  10702. async function submitSaveDHCPClient(e) {
  10703. if (e) e.preventDefault();
  10704. const id = document.getElementById('modal-dhcp-id')?.value;
  10705. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  10706. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  10707. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  10708. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  10709. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  10710. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  10711. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  10712. if (!id && !iface) {
  10713. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  10714. return;
  10715. }
  10716. try {
  10717. let res;
  10718. if (id) {
  10719. // PUT update
  10720. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10721. method: 'PUT',
  10722. headers: { 'Content-Type': 'application/json' },
  10723. body: JSON.stringify({
  10724. enabled,
  10725. add_default_route: defRoute,
  10726. default_route_distance: distance,
  10727. use_peer_dns: peerDns,
  10728. use_peer_ntp: peerNtp,
  10729. comment
  10730. })
  10731. });
  10732. } else {
  10733. // POST create
  10734. res = await fetch(`${API_BASE}/dhcp/clients`, {
  10735. method: 'POST',
  10736. headers: { 'Content-Type': 'application/json' },
  10737. body: JSON.stringify({
  10738. interface: iface,
  10739. enabled,
  10740. add_default_route: defRoute,
  10741. default_route_distance: distance,
  10742. use_peer_dns: peerDns,
  10743. use_peer_ntp: peerNtp,
  10744. comment
  10745. })
  10746. });
  10747. }
  10748. const data = await res.json();
  10749. if (!res.ok) {
  10750. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  10751. return;
  10752. }
  10753. closeDHCPClientModal();
  10754. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  10755. await loadDHCPClients();
  10756. fetchData(); // refresh interfaces list with new lease/status
  10757. } catch (err) {
  10758. showToast('Error', err.message, 'error');
  10759. }
  10760. }
  10761. async function toggleDHCPClientState(id, enabled) {
  10762. try {
  10763. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  10764. method: 'POST',
  10765. headers: { 'Content-Type': 'application/json' },
  10766. body: JSON.stringify({ enabled })
  10767. });
  10768. const data = await res.json();
  10769. if (!res.ok) {
  10770. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  10771. return;
  10772. }
  10773. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  10774. await loadDHCPClients();
  10775. fetchData();
  10776. } catch (err) {
  10777. showToast('Error', err.message, 'error');
  10778. }
  10779. }
  10780. async function renewDHCPClient(id) {
  10781. try {
  10782. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  10783. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  10784. method: 'POST'
  10785. });
  10786. const data = await res.json();
  10787. if (!res.ok) {
  10788. showToast('Error', data.error || 'Failed to renew lease', 'error');
  10789. return;
  10790. }
  10791. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  10792. setTimeout(() => {
  10793. loadDHCPClients();
  10794. fetchData();
  10795. }, 1500);
  10796. } catch (err) {
  10797. showToast('Error', err.message, 'error');
  10798. }
  10799. }
  10800. async function releaseDHCPClient(id) {
  10801. try {
  10802. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  10803. method: 'POST'
  10804. });
  10805. const data = await res.json();
  10806. if (!res.ok) {
  10807. showToast('Error', data.error || 'Failed to release lease', 'error');
  10808. return;
  10809. }
  10810. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  10811. await loadDHCPClients();
  10812. fetchData();
  10813. } catch (err) {
  10814. showToast('Error', err.message, 'error');
  10815. }
  10816. }
  10817. async function deleteDHCPClient(id, ifaceName) {
  10818. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  10819. return;
  10820. }
  10821. try {
  10822. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  10823. method: 'DELETE'
  10824. });
  10825. const data = await res.json();
  10826. if (!res.ok) {
  10827. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  10828. return;
  10829. }
  10830. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  10831. await loadDHCPClients();
  10832. fetchData();
  10833. } catch (err) {
  10834. showToast('Error', err.message, 'error');
  10835. }
  10836. }
  10837. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  10838. function initTableSorting() {
  10839. document.querySelectorAll('table').forEach(setupSortableTable);
  10840. }
  10841. function setupSortableTable(table) {
  10842. const thead = table.querySelector('thead');
  10843. const tbody = table.querySelector('tbody');
  10844. if (!thead || !tbody) return;
  10845. const headerRows = thead.querySelectorAll('tr');
  10846. if (headerRows.length === 0) return;
  10847. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  10848. ths.forEach((th, colIdx) => {
  10849. if (th._sortBound) return;
  10850. th._sortBound = true;
  10851. const rawText = th.innerText.trim().toLowerCase();
  10852. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  10853. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  10854. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  10855. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  10856. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  10857. return;
  10858. }
  10859. th.classList.add('table-sortable', 'group');
  10860. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  10861. let icon = th.querySelector('.table-sort-icon');
  10862. if (!icon) {
  10863. icon = document.createElement('span');
  10864. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10865. icon.innerHTML = '⇅';
  10866. th.appendChild(icon);
  10867. }
  10868. th.addEventListener('click', (e) => {
  10869. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  10870. handleHeaderClick(table, th, colIdx);
  10871. });
  10872. });
  10873. if (!tbody._sortObserved) {
  10874. tbody._sortObserved = true;
  10875. let sortDebounceTimer = null;
  10876. const observer = new MutationObserver((mutations) => {
  10877. if (tbody._isSorting) return;
  10878. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  10879. if (!hasChildChanges) return;
  10880. clearTimeout(sortDebounceTimer);
  10881. sortDebounceTimer = setTimeout(() => {
  10882. if (tbody._isSorting) return;
  10883. if (table._activeSort && table._activeSort.dir !== 'none') {
  10884. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  10885. } else {
  10886. tagOriginalRowOrder(tbody);
  10887. }
  10888. }, 10);
  10889. });
  10890. observer.observe(tbody, { childList: true });
  10891. }
  10892. tagOriginalRowOrder(tbody);
  10893. }
  10894. function tagOriginalRowOrder(tbody) {
  10895. let idx = 0;
  10896. Array.from(tbody.children).forEach(tr => {
  10897. if (!tr.querySelector('td[colspan]')) {
  10898. if (!tr.hasAttribute('data-orig-idx')) {
  10899. tr.setAttribute('data-orig-idx', idx++);
  10900. }
  10901. }
  10902. });
  10903. }
  10904. function handleHeaderClick(table, th, colIdx) {
  10905. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  10906. let newDir = 'asc';
  10907. if (currentSort.colIdx === colIdx) {
  10908. if (currentSort.dir === 'asc') newDir = 'desc';
  10909. else if (currentSort.dir === 'desc') newDir = 'none';
  10910. else newDir = 'asc';
  10911. } else {
  10912. newDir = 'asc';
  10913. }
  10914. table._activeSort = { colIdx, dir: newDir };
  10915. updateHeaderIcons(table, colIdx, newDir);
  10916. applyTableSort(table, colIdx, newDir, true);
  10917. }
  10918. function updateHeaderIcons(table, activeColIdx, dir) {
  10919. const thead = table.querySelector('thead');
  10920. if (!thead) return;
  10921. const ths = thead.querySelectorAll('th');
  10922. ths.forEach((th, idx) => {
  10923. const icon = th.querySelector('.table-sort-icon');
  10924. if (!icon) return;
  10925. if (idx === activeColIdx && dir !== 'none') {
  10926. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  10927. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  10928. th.classList.add('table-sorted-active');
  10929. } else {
  10930. icon.innerHTML = '⇅';
  10931. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  10932. th.classList.remove('table-sorted-active');
  10933. }
  10934. });
  10935. }
  10936. function applyTableSort(table, colIdx, dir, userInitiated) {
  10937. const tbody = table.querySelector('tbody');
  10938. if (!tbody || tbody.children.length <= 1) return;
  10939. tbody._isSorting = true;
  10940. tagOriginalRowOrder(tbody);
  10941. // Group parent rows and any attached drawer/sub-rows
  10942. const groups = [];
  10943. let currentGroup = null;
  10944. Array.from(tbody.children).forEach(tr => {
  10945. if (tr.querySelector('td[colspan]')) {
  10946. if (currentGroup) {
  10947. currentGroup.subRows.push(tr);
  10948. } else {
  10949. groups.push({ mainRow: tr, subRows: [] });
  10950. }
  10951. } else {
  10952. currentGroup = { mainRow: tr, subRows: [] };
  10953. groups.push(currentGroup);
  10954. }
  10955. });
  10956. if (dir === 'none') {
  10957. groups.sort((a, b) => {
  10958. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10959. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  10960. return idxA - idxB;
  10961. });
  10962. } else {
  10963. groups.sort((a, b) => {
  10964. const cellA = a.mainRow.children[colIdx];
  10965. const cellB = b.mainRow.children[colIdx];
  10966. const res = compareTableCells(cellA, cellB);
  10967. return dir === 'asc' ? res : -res;
  10968. });
  10969. }
  10970. // Re-append rows in sorted order
  10971. groups.forEach(g => {
  10972. tbody.appendChild(g.mainRow);
  10973. g.subRows.forEach(sub => tbody.appendChild(sub));
  10974. });
  10975. tbody._isSorting = false;
  10976. }
  10977. function getCellRawText(cell) {
  10978. if (!cell) return '';
  10979. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  10980. const input = cell.querySelector('input, select');
  10981. if (input) {
  10982. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  10983. return input.value;
  10984. }
  10985. return cell.innerText.trim();
  10986. }
  10987. function parseTrafficToNumber(str) {
  10988. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  10989. if (!m) return null;
  10990. const num = parseFloat(m[1].replace(/,/g, ''));
  10991. if (isNaN(num)) return null;
  10992. const unit = m[2].toUpperCase();
  10993. let mult = 1;
  10994. if (unit.startsWith('K')) mult = 1024;
  10995. else if (unit.startsWith('M')) mult = 1024 * 1024;
  10996. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  10997. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  10998. return num * mult;
  10999. }
  11000. function parseIpToNumber(str) {
  11001. const clean = str.replace(/^[!~]/, '').trim();
  11002. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  11003. if (!m) return null;
  11004. const o1 = parseInt(m[1], 10);
  11005. const o2 = parseInt(m[2], 10);
  11006. const o3 = parseInt(m[3], 10);
  11007. const o4 = parseInt(m[4], 10);
  11008. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  11009. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  11010. }
  11011. function parseCompoundPackets(str) {
  11012. const m = str.match(/^([\d,]+)p/);
  11013. if (!m) return null;
  11014. return parseInt(m[1].replace(/,/g, ''), 10);
  11015. }
  11016. function compareTableCells(cellA, cellB) {
  11017. const a = getCellRawText(cellA);
  11018. const b = getCellRawText(cellB);
  11019. if (a === '' && b !== '') return 1;
  11020. if (b === '' && a !== '') return -1;
  11021. if (a === b) return 0;
  11022. // 1. IP Addresses / CIDR
  11023. const ipA = parseIpToNumber(a);
  11024. const ipB = parseIpToNumber(b);
  11025. if (ipA !== null && ipB !== null) return ipA - ipB;
  11026. // 2. Packet counts (e.g. "1,250p / 45 KB")
  11027. const pktA = parseCompoundPackets(a);
  11028. const pktB = parseCompoundPackets(b);
  11029. if (pktA !== null && pktB !== null) return pktA - pktB;
  11030. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  11031. const trafA = parseTrafficToNumber(a);
  11032. const trafB = parseTrafficToNumber(b);
  11033. if (trafA !== null && trafB !== null) return trafA - trafB;
  11034. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  11035. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11036. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11037. const numA = Number(cleanNumA);
  11038. const numB = Number(cleanNumB);
  11039. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  11040. return numA - numB;
  11041. }
  11042. // 5. Natural case-insensitive string compare
  11043. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  11044. }
  11045. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  11046. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  11047. const docTableObserver = new MutationObserver((mutations) => {
  11048. let needsInit = false;
  11049. for (const m of mutations) {
  11050. for (const node of m.addedNodes) {
  11051. if (node.nodeType === 1) {
  11052. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  11053. needsInit = true;
  11054. break;
  11055. }
  11056. }
  11057. }
  11058. if (needsInit) break;
  11059. }
  11060. if (needsInit) {
  11061. initTableSorting();
  11062. }
  11063. });
  11064. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  11065. }