app.js 539 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795
  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. function formatBytes(bytes) {
  60. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  61. const k = 1024;
  62. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  63. const i = Math.floor(Math.log(bytes) / Math.log(k));
  64. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  65. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  66. }
  67. // Initialize on page load
  68. document.addEventListener('DOMContentLoaded', () => {
  69. const hash = window.location.hash.replace('#', '') || 'dashboard';
  70. navigate(hash);
  71. initTableSorting();
  72. fetchData();
  73. // Live polling every 2.5 seconds
  74. setInterval(() => {
  75. if (state.isPolling) {
  76. fetchData(false);
  77. }
  78. }, 2500);
  79. });
  80. // Navigation Handler
  81. function navigate(tabName) {
  82. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  83. navigate('bgp');
  84. return;
  85. }
  86. if (tabName === 'vlans') {
  87. navigate('interfaces');
  88. return;
  89. }
  90. state.activeTab = tabName;
  91. window.location.hash = tabName;
  92. // Update nav links styling
  93. document.querySelectorAll('.nav-link').forEach(link => {
  94. 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';
  95. });
  96. const activeNav = document.getElementById(`nav-${tabName}`);
  97. if (activeNav) {
  98. 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';
  99. }
  100. // Update page headers
  101. const titles = {
  102. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  103. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  104. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  105. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  106. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  107. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  108. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  109. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  110. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  111. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  112. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 dynamic routing engine' },
  113. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  114. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  115. aerotun: { title: 'AeroTUN VPN (/interface aerotun)', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  116. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  117. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  118. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  119. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  120. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  121. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  122. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  123. };
  124. const header = titles[tabName] || titles.dashboard;
  125. const pTitle = document.getElementById('page-title');
  126. if (pTitle) pTitle.innerText = header.title;
  127. const pSub = document.getElementById('page-subtitle');
  128. if (pSub) pSub.innerText = header.sub;
  129. // Toggle sections dynamically for all section elements
  130. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  131. if (el.id === `section-${tabName}`) {
  132. el.classList.remove('hidden');
  133. } else {
  134. el.classList.add('hidden');
  135. }
  136. });
  137. if (tabName === 'bridge') loadBridge();
  138. if (tabName === 'firewall') loadFirewall();
  139. if (tabName === 'routes') loadRoutes();
  140. if (tabName === 'bgp') {
  141. loadDynamicRouting();
  142. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  143. }
  144. if (tabName === 'ospf') {
  145. loadDynamicRouting();
  146. switchOspfTab(state.activeOspfTab || 'instances');
  147. }
  148. if (tabName === 'routing-filters') loadDynamicRouting();
  149. if (tabName === 'dynamic-routing') loadDynamicRouting();
  150. if (tabName === 'ppp') loadPPP();
  151. if (tabName === 'eoip') loadEoIP();
  152. if (tabName === 'aerotun') loadAeroTUN();
  153. if (tabName === 'persistence') loadDebianConfig();
  154. if (tabName === 'pppoe') loadPPPoE();
  155. if (tabName === 'wireguard') loadWireGuard();
  156. if (tabName === 'ipsec') loadIPSec();
  157. if (tabName === 'l2tp') loadL2TP();
  158. if (tabName === 'pptp') loadPPTP();
  159. if (tabName === 'tools') loadToolsView();
  160. if (tabName === 'dhcp-client') loadDHCPClients();
  161. setTimeout(initTableSorting, 50);
  162. }
  163. // Fetch all core system, network and VPN telemetry
  164. async function fetchData(isManual = false) {
  165. const spinner = document.getElementById('refresh-spinner');
  166. if (isManual && spinner) spinner.classList.add('animate-spin');
  167. try {
  168. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  169. fetch(`${API_BASE}/system/status`),
  170. fetch(`${API_BASE}/interfaces`),
  171. fetch(`${API_BASE}/vlans`),
  172. fetch(`${API_BASE}/vpn/status`),
  173. fetch(`${API_BASE}/firewall/summary`),
  174. fetch(`${API_BASE}/routing/dynamic/summary`),
  175. fetch(`${API_BASE}/bridge/summary`),
  176. fetch(`${API_BASE}/dhcp/clients/summary`),
  177. fetch(`${API_BASE}/dhcp/clients`)
  178. ]);
  179. if (dhcpSumRes && dhcpSumRes.ok) {
  180. state.dhcpSummary = await dhcpSumRes.json();
  181. const bDhcp = document.getElementById('badge-dhcp-client-count');
  182. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  183. }
  184. if (dhcpClientsRes && dhcpClientsRes.ok) {
  185. state.dhcpClients = await dhcpClientsRes.json();
  186. }
  187. if (brSummaryRes.ok) {
  188. state.bridgeSummary = await brSummaryRes.json();
  189. const bBridge = document.getElementById('badge-bridge-count');
  190. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  191. const sBr = document.getElementById('bridge-stat-bridges');
  192. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  193. const sPorts = document.getElementById('bridge-stat-ports');
  194. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  195. const sHosts = document.getElementById('bridge-stat-hosts');
  196. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  197. }
  198. if (statusRes.ok) state.systemStatus = await statusRes.json();
  199. if (ifacesRes.ok) {
  200. const ifacesData = await ifacesRes.json();
  201. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  202. state.interfaces = rawIfaces.filter(i => {
  203. if (!i.name) return false;
  204. if (i.name.startsWith('ep_')) return false;
  205. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  206. });
  207. try { populateToolsInterfaces(); } catch (e) {}
  208. }
  209. if (vlansRes.ok) {
  210. const vlansData = await vlansRes.json();
  211. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  212. }
  213. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  214. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  215. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  216. updateSystemMetrics();
  217. updateBadges();
  218. if (state.activeTab === 'dashboard') renderDashboard();
  219. if (state.activeTab === 'interfaces') renderInterfacesList();
  220. if (state.activeTab === 'vlans') renderVlansList();
  221. if (state.activeTab === 'firewall') loadFirewall(false);
  222. if (state.activeTab === 'routes') loadRoutes(false);
  223. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  224. if (state.activeTab === 'ppp') loadPPP(false);
  225. if (state.activeTab === 'eoip') loadEoIP(false);
  226. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  227. if (state.activeTab === 'pppoe') loadPPPoE(false);
  228. if (state.activeTab === 'wireguard') loadWireGuard(false);
  229. if (state.activeTab === 'ipsec') loadIPSec(false);
  230. if (state.activeTab === 'l2tp') loadL2TP(false);
  231. if (state.activeTab === 'pptp') loadPPTP(false);
  232. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  233. } catch (err) {
  234. console.error('Failed to fetch router state:', err);
  235. } finally {
  236. if (isManual && spinner) {
  237. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  238. }
  239. }
  240. }
  241. // Update Top KPI and Sidebar Telemetry
  242. function updateSystemMetrics() {
  243. const s = state.systemStatus;
  244. const v = state.vpnStatus;
  245. if (!s) return;
  246. // Sidebar Host & Uptime
  247. const sideHost = document.getElementById('side-hostname');
  248. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  249. const sideUp = document.getElementById('side-uptime');
  250. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  251. const sideGw = document.getElementById('side-gateway-ip');
  252. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  253. // Compute CPU Metrics
  254. let cpuPct = 0;
  255. if (s.cpu_pct !== undefined) {
  256. cpuPct = s.cpu_pct;
  257. } else if (s.cpu_load && s.cpu_load.length > 0) {
  258. const cores = s.cpu_cores || 1;
  259. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  260. }
  261. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  262. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  263. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  264. // Sidebar CPU
  265. const sideCpuVal = document.getElementById('side-cpu-val');
  266. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  267. const sideCpuBar = document.getElementById('side-cpu-bar');
  268. if (sideCpuBar) {
  269. sideCpuBar.style.width = cpuWidth;
  270. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  271. }
  272. // Dashboard CPU Card
  273. const dashCpuVal = document.getElementById('dash-cpu-val');
  274. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  275. const dashCpuBar = document.getElementById('dash-cpu-bar');
  276. if (dashCpuBar) {
  277. dashCpuBar.style.width = cpuWidth;
  278. if (cpuPct > 85) {
  279. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  280. } else if (cpuPct > 65) {
  281. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  282. } else {
  283. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  284. }
  285. }
  286. const dashCpuCores = document.getElementById('dash-cpu-cores');
  287. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  288. const dashCpuLoad = document.getElementById('dash-cpu-load');
  289. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  290. const dashCpuStatus = document.getElementById('dash-cpu-status');
  291. if (dashCpuStatus) {
  292. if (cpuPct > 85) {
  293. dashCpuStatus.innerText = 'High';
  294. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  295. } else if (cpuPct > 65) {
  296. dashCpuStatus.innerText = 'Heavy';
  297. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  298. } else {
  299. dashCpuStatus.innerText = 'Normal';
  300. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  301. }
  302. }
  303. // Compute RAM Metrics
  304. const memPct = Math.round(s.mem_usage_pct || 0);
  305. const memPctStr = `${memPct}%`;
  306. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  307. const usedMB = s.mem_used_mb || 0;
  308. const totalMB = s.mem_total_mb || 0;
  309. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  310. function fmtMemMB(mb) {
  311. if (mb >= 1024) {
  312. return `${(mb / 1024).toFixed(1)} GB`;
  313. }
  314. return `${mb} MB`;
  315. }
  316. // Sidebar RAM
  317. const sideRamVal = document.getElementById('side-ram-val');
  318. if (sideRamVal) sideRamVal.innerText = memPctStr;
  319. const sideRamBar = document.getElementById('side-ram-bar');
  320. if (sideRamBar) sideRamBar.style.width = memWidth;
  321. // Dashboard RAM Card
  322. const dashRamVal = document.getElementById('dash-ram-val');
  323. if (dashRamVal) dashRamVal.innerText = memPctStr;
  324. const dashRamBar = document.getElementById('dash-ram-bar');
  325. if (dashRamBar) {
  326. dashRamBar.style.width = memWidth;
  327. if (memPct > 85) {
  328. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  329. } else if (memPct > 70) {
  330. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  331. } else {
  332. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  333. }
  334. }
  335. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  336. if (dashRamUsedTotal) {
  337. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  338. }
  339. const dashRamFree = document.getElementById('dash-ram-free');
  340. if (dashRamFree) {
  341. dashRamFree.innerText = fmtMemMB(freeMB);
  342. }
  343. const dashRamStatus = document.getElementById('dash-ram-status');
  344. if (dashRamStatus) {
  345. if (memPct > 85) {
  346. dashRamStatus.innerText = 'High';
  347. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  348. } else {
  349. dashRamStatus.innerText = 'Active';
  350. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  351. }
  352. }
  353. // Legacy Dashboard Stats (Safe checks)
  354. const elIfacesUp = document.getElementById('stat-ifaces-up');
  355. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  356. const elIfacesTot = document.getElementById('stat-ifaces-total');
  357. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  358. const elIfacesDown = document.getElementById('stat-ifaces-down');
  359. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  360. const elVlans = document.getElementById('stat-vlans-count');
  361. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  362. // VPN Status Indicators
  363. if (v) {
  364. const totalActive = v.total_active_tunnels || 0;
  365. const statVpnActive = document.getElementById('stat-vpn-active');
  366. if (statVpnActive) statVpnActive.innerText = totalActive;
  367. const tunnelsDot = document.getElementById('tunnels-dot');
  368. const tunnelsLabel = document.getElementById('tunnels-label');
  369. if (tunnelsDot && tunnelsLabel) {
  370. if (totalActive > 0) {
  371. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  372. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  373. } else {
  374. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  375. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  376. }
  377. }
  378. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  379. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  380. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  381. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  382. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  383. }
  384. // Total Live Bandwidth Rate
  385. let totalRx = 0;
  386. let totalTx = 0;
  387. (state.interfaces || []).forEach(i => {
  388. if (i.rate) {
  389. totalRx += i.rate.rx_bytes_sec || 0;
  390. totalTx += i.rate.tx_bytes_sec || 0;
  391. }
  392. });
  393. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  394. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  395. }
  396. function setDotBadge(id, active) {
  397. const el = document.getElementById(id);
  398. if (!el) return;
  399. if (active) {
  400. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  401. } else {
  402. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  403. }
  404. }
  405. function updateBadges() {
  406. const bIfaces = document.getElementById('badge-ifaces-count');
  407. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  408. const bVlans = document.getElementById('badge-vlans-count');
  409. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  410. if (state.fwSummary) {
  411. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  412. const badgeFw = document.getElementById('badge-firewall-count');
  413. if (badgeFw) badgeFw.innerText = totalFwRules;
  414. }
  415. if (state.vpnStatus) {
  416. const v = state.vpnStatus;
  417. const bEoIP = document.getElementById('badge-eoip-count');
  418. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  419. const bAero = document.getElementById('badge-aerotun-count');
  420. if (bAero) bAero.innerText = v.total_aerotun || 0;
  421. const bPPPSess = document.getElementById('badge-ppp-sessions');
  422. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  423. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  424. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  425. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  426. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  427. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  428. }
  429. if (state.dynSummary) {
  430. const d = state.dynSummary;
  431. setDotBadge('badge-bgp-dot', d.bgp_running);
  432. setDotBadge('badge-ospf-dot', d.ospf_running);
  433. const bBgp = document.getElementById('badge-bgp-count');
  434. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  435. const bOspf = document.getElementById('badge-ospf-count');
  436. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  437. const bFilters = document.getElementById('badge-filters-count');
  438. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  439. }
  440. }
  441. // Render Dashboard View
  442. function renderDashboard() {
  443. const matrix = document.getElementById('port-matrix');
  444. matrix.innerHTML = '';
  445. (state.interfaces || []).forEach(iface => {
  446. const isUp = iface.state === 'UP';
  447. const isVlan = iface.is_vlan;
  448. const portCard = document.createElement('div');
  449. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  450. isUp
  451. ? (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')
  452. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  453. }`;
  454. portCard.onclick = () => openIfaceModal(iface.name);
  455. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  456. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  457. portCard.innerHTML = `
  458. <div class="flex items-center justify-between mb-2">
  459. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  460. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  461. </div>
  462. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  463. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  464. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  465. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  466. </div>
  467. `;
  468. matrix.appendChild(portCard);
  469. });
  470. const ifaceTbody = document.getElementById('quick-interfaces-table');
  471. if (ifaceTbody) {
  472. ifaceTbody.innerHTML = '';
  473. (state.interfaces || []).forEach(i => {
  474. const isUp = i.state === 'UP';
  475. const tr = document.createElement('tr');
  476. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  477. tr.onclick = () => openIfaceModal(i.name);
  478. const rxStr = i.rate?.rx_human || '0 B/s';
  479. const txStr = i.rate?.tx_human || '0 B/s';
  480. tr.innerHTML = `
  481. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  482. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  483. <span>${i.name}</span>
  484. </td>
  485. <td class="py-2.5 text-slate-300 font-sans">
  486. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  487. </td>
  488. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  489. <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>
  490. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  491. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  492. </td>
  493. <td class="py-2.5 text-right font-sans font-semibold">
  494. <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>
  495. </td>
  496. `;
  497. ifaceTbody.appendChild(tr);
  498. });
  499. }
  500. const vlanTbody = document.getElementById('quick-vlans-table');
  501. if (vlanTbody) {
  502. vlanTbody.innerHTML = '';
  503. }
  504. }
  505. // Expand / Collapse Handlers
  506. function toggleExpand(parentName) {
  507. if (state.expandedParents.has(parentName)) {
  508. state.expandedParents.delete(parentName);
  509. } else {
  510. state.expandedParents.add(parentName);
  511. }
  512. renderInterfacesList();
  513. }
  514. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  515. function supportsVLAN(iface) {
  516. if (!iface) return false;
  517. if (iface.is_vlan) return false;
  518. const name = (iface.name || '').toLowerCase();
  519. const type = (iface.type || '').toLowerCase();
  520. const role = (iface.role || '').toLowerCase();
  521. // Exclude loopback
  522. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  523. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  524. if (type === 'wireguard' || name.startsWith('wg')) return false;
  525. // Exclude PPP / PPPoE
  526. if (type === 'ppp' || name.startsWith('ppp')) return false;
  527. // Exclude other Layer 3 tunnels and dummy devices
  528. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  529. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  530. return false;
  531. }
  532. // If name already contains a dot, it's already a sub-interface
  533. if (name.includes('.')) return false;
  534. return true;
  535. }
  536. // Expand / Collapse Handlers
  537. function toggleExpand(parentName) {
  538. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  539. if (childVlans.length === 0) {
  540. // Cannot expand an interface with no VLANs
  541. state.expandedParents.delete(parentName);
  542. return;
  543. }
  544. if (state.expandedParents.has(parentName)) {
  545. state.expandedParents.delete(parentName);
  546. } else {
  547. state.expandedParents.add(parentName);
  548. }
  549. renderInterfacesList();
  550. }
  551. function expandAllIfaces(expand) {
  552. if (expand) {
  553. (state.interfaces || []).forEach(i => {
  554. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  555. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  556. });
  557. } else {
  558. state.expandedParents.clear();
  559. }
  560. renderInterfacesList();
  561. }
  562. // Filter and Render Hierarchical Interfaces List
  563. function filterIfaces(filter) {
  564. state.ifaceFilter = filter || 'all';
  565. renderInterfacesList();
  566. }
  567. function renderInterfacesList() {
  568. const tbody = document.getElementById('interfaces-tree-tbody');
  569. const emptyState = document.getElementById('interfaces-empty-state');
  570. const summary = document.getElementById('ifaces-list-summary');
  571. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  572. tbody.innerHTML = '';
  573. const allIfaces = state.interfaces || [];
  574. const allVlans = state.vlans || [];
  575. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  576. const filteredParents = parentIfaces.filter(parent => {
  577. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  578. if (query) {
  579. const matchName = parent.name.toLowerCase().includes(query);
  580. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  581. const matchRole = (parent.role || '').toLowerCase().includes(query);
  582. const matchType = (parent.type || '').toLowerCase().includes(query);
  583. const matchVlan = childVlans.some(v =>
  584. v.name.toLowerCase().includes(query) ||
  585. String(v.vlan_id).includes(query) ||
  586. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  587. (v.description || '').toLowerCase().includes(query)
  588. );
  589. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  590. }
  591. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  592. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  593. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  594. return true;
  595. });
  596. if (summary) {
  597. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  598. }
  599. if (filteredParents.length === 0) {
  600. emptyState?.classList.remove('hidden');
  601. return;
  602. }
  603. emptyState?.classList.add('hidden');
  604. filteredParents.forEach(parent => {
  605. const isUp = parent.state === 'UP';
  606. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  607. const hasVlans = childVlans.length > 0;
  608. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  609. const canHaveVlan = supportsVLAN(parent);
  610. const parentRow = document.createElement('tr');
  611. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  612. parentRow.innerHTML = `
  613. <td class="py-3 px-3 text-center">
  614. ${hasVlans ? `
  615. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  616. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  617. <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">
  618. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  619. </svg>
  620. </button>
  621. ` : `
  622. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  623. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  624. </div>
  625. `}
  626. </td>
  627. <td class="py-3 px-4">
  628. <div class="flex items-center space-x-2.5">
  629. <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">
  630. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  631. </div>
  632. <div>
  633. <div class="flex items-center gap-2">
  634. ${hasVlans ? `
  635. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  636. <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>
  637. ` : `
  638. <span class="font-bold text-white text-sm">${parent.name}</span>
  639. <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>
  640. `}
  641. </div>
  642. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  643. </div>
  644. </div>
  645. </td>
  646. <td class="py-3 px-4 font-sans">
  647. <div class="flex items-center gap-1.5">
  648. <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>
  649. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  650. </div>
  651. </td>
  652. <td class="py-3 px-4">
  653. ${parent.ipv4 && parent.ipv4.length > 0
  654. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  655. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  656. }
  657. ${(() => {
  658. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  659. if (!c) return '';
  660. 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');
  661. 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>`;
  662. })()}
  663. </td>
  664. <td class="py-3 px-4 text-slate-400 text-[11px]">
  665. <div>${parent.mac || 'N/A'}</div>
  666. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  667. </td>
  668. <td class="py-3 px-4 text-[11px]">
  669. <div class="flex items-center space-x-2">
  670. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  671. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  672. </div>
  673. </td>
  674. <td class="py-3 px-4 font-sans">
  675. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  676. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  677. 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'
  678. }" title="Click to toggle link status">
  679. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  680. <span>${parent.state}</span>
  681. </button>
  682. </td>
  683. <td class="py-3 px-4 text-right space-x-2 font-sans">
  684. ${(() => {
  685. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  686. if (c) {
  687. 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>`;
  688. }
  689. 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>`;
  690. })()}
  691. ${canHaveVlan ? `
  692. <button onclick="openVlanModal('${parent.name}')"
  693. 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">
  694. + Add VLAN
  695. </button>
  696. ` : ''}
  697. <button onclick="openIfaceModal('${parent.name}')"
  698. 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">
  699. Configure
  700. </button>
  701. </td>
  702. `;
  703. tbody.appendChild(parentRow);
  704. if (isExpanded) {
  705. const drawerRow = document.createElement('tr');
  706. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  707. const drawerCell = document.createElement('td');
  708. drawerCell.colSpan = 8;
  709. drawerCell.className = 'p-0';
  710. drawerCell.innerHTML = `
  711. <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">
  712. <div class="flex items-center justify-between mb-3">
  713. <div class="flex items-center space-x-3">
  714. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  715. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  716. </span>
  717. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  718. ${childVlans.length} Attached
  719. </span>
  720. </div>
  721. <button onclick="openVlanModal('${parent.name}')"
  722. 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">
  723. <span>+ Create VLAN on ${parent.name}</span>
  724. </button>
  725. </div>
  726. ${childVlans.length === 0 ? `
  727. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  728. <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>
  729. <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">
  730. <span>+ Create Your First VLAN on ${parent.name}</span>
  731. </button>
  732. </div>
  733. ` : `
  734. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  735. <table class="w-full text-left text-xs font-mono">
  736. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  737. <tr>
  738. <th class="py-2.5 px-4">VLAN ID</th>
  739. <th class="py-2.5 px-4">Interface Device</th>
  740. <th class="py-2.5 px-4">Subnet Gateway</th>
  741. <th class="py-2.5 px-4">Role / Alias</th>
  742. <th class="py-2.5 px-4">MTU</th>
  743. <th class="py-2.5 px-4">Throughput</th>
  744. <th class="py-2.5 px-4">Status</th>
  745. <th class="py-2.5 px-4 text-right">Actions</th>
  746. </tr>
  747. </thead>
  748. <tbody class="divide-y divide-slate-800/70">
  749. ${childVlans.map(v => {
  750. const isVlanUp = v.state === 'UP';
  751. return `
  752. <tr class="hover:bg-slate-800/40 transition">
  753. <td class="py-2.5 px-4">
  754. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  755. VLAN ${v.vlan_id}
  756. </span>
  757. </td>
  758. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  759. <span class="text-cyan-500">└─</span>
  760. <span>${v.name}</span>
  761. </td>
  762. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  763. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  764. ${(() => {
  765. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  766. if (!c) return '';
  767. 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';
  768. 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>`;
  769. })()}
  770. </td>
  771. <td class="py-2.5 px-4 font-sans text-slate-300">
  772. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  773. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  774. </td>
  775. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  776. <td class="py-2.5 px-4 text-[11px]">
  777. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  778. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  779. </td>
  780. <td class="py-2.5 px-4 font-sans">
  781. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  782. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  783. 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'
  784. }">
  785. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  786. <span>${v.state}</span>
  787. </button>
  788. </td>
  789. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  790. ${(() => {
  791. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  792. if (c) {
  793. 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>`;
  794. }
  795. 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>`;
  796. })()}
  797. <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>
  798. <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>
  799. </td>
  800. </tr>
  801. `;
  802. }).join('')}
  803. </tbody>
  804. </table>
  805. </div>
  806. `}
  807. </div>
  808. `;
  809. drawerRow.appendChild(drawerCell);
  810. tbody.appendChild(drawerRow);
  811. }
  812. });
  813. }
  814. // Render VLANs Dedicated View
  815. function renderVlansList() {
  816. const tbody = document.getElementById('vlans-table-body');
  817. if (!tbody) return;
  818. const emptyState = document.getElementById('vlans-empty-state');
  819. const countBadge = document.getElementById('vlans-table-count');
  820. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  821. tbody.innerHTML = '';
  822. const allVlans = state.vlans || [];
  823. if (countBadge) countBadge.innerText = allVlans.length;
  824. const filtered = allVlans.filter(v => {
  825. if (!query) return true;
  826. return v.name.toLowerCase().includes(query) ||
  827. String(v.vlan_id).includes(query) ||
  828. (v.description || '').toLowerCase().includes(query) ||
  829. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  830. });
  831. if (allVlans.length === 0) {
  832. emptyState.classList.remove('hidden');
  833. return;
  834. }
  835. emptyState.classList.add('hidden');
  836. filtered.forEach(v => {
  837. const isUp = v.state === 'UP';
  838. const tr = document.createElement('tr');
  839. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  840. tr.innerHTML = `
  841. <td class="py-3 px-4">
  842. <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">
  843. VLAN ${v.vlan_id}
  844. </span>
  845. </td>
  846. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  847. <td class="py-3 px-4 text-slate-300">
  848. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  849. </td>
  850. <td class="py-3 px-4 text-emerald-400 font-medium">
  851. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  852. </td>
  853. <td class="py-3 px-4 text-slate-300 font-sans">
  854. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  855. </td>
  856. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  857. <td class="py-3 px-4 font-sans">
  858. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  859. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  860. 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'
  861. }">
  862. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  863. <span>${v.state}</span>
  864. </button>
  865. </td>
  866. <td class="py-3 px-4 text-right space-x-2 font-sans">
  867. <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>
  868. <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>
  869. </td>
  870. `;
  871. tbody.appendChild(tr);
  872. });
  873. }
  874. // Toggle interface UP / DOWN
  875. async function toggleInterfaceState(name, newState) {
  876. try {
  877. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  878. method: 'POST',
  879. headers: { 'Content-Type': 'application/json' },
  880. body: JSON.stringify({ state: newState })
  881. });
  882. const data = await res.json();
  883. if (res.ok) {
  884. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  885. fetchData(false);
  886. } else {
  887. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  888. }
  889. } catch (err) {
  890. showToast('Error', err.message, 'error');
  891. }
  892. }
  893. // ---------------- MikroTik Flag & Utilities ----------------
  894. function renderMikroTikFlag(running, disabled) {
  895. if (running) {
  896. 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>`;
  897. }
  898. if (disabled) {
  899. 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>`;
  900. }
  901. 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>`;
  902. }
  903. function copyToClipboard(text, label = 'Text') {
  904. navigator.clipboard.writeText(text).then(() => {
  905. showToast('Copied', `${label} copied to clipboard`, 'success');
  906. }).catch(() => {
  907. prompt('Copy value:', text);
  908. });
  909. }
  910. // ======================== PPP Profiles Shared Helper ========================
  911. async function fetchPPPProfilesList() {
  912. try {
  913. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  914. if (res.ok) {
  915. state.pppProfiles = await res.json();
  916. }
  917. } catch (err) {
  918. console.error('Failed to load PPP profiles:', err);
  919. }
  920. }
  921. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  922. const sel = document.getElementById(selectId);
  923. if (!sel) return;
  924. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  925. { name: 'default', use_encryption: 'no' },
  926. { name: 'default-encryption', use_encryption: 'required' }
  927. ];
  928. sel.innerHTML = '';
  929. profiles.forEach(p => {
  930. const opt = document.createElement('option');
  931. opt.value = p.name;
  932. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  933. opt.innerText = `${p.name}${encBadge}`;
  934. sel.appendChild(opt);
  935. });
  936. if (selectedVal) {
  937. sel.value = selectedVal;
  938. } else {
  939. sel.value = defaultVal;
  940. }
  941. if (!sel.value && sel.options.length > 0) {
  942. sel.selectedIndex = 0;
  943. }
  944. }
  945. // ======================== PPPoE Multi-Instance ========================
  946. async function loadPPPoE(populateInputs = true) {
  947. try {
  948. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  949. await fetchPPPProfilesList();
  950. }
  951. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  952. const list = await res.json();
  953. state.pppoeList = Array.isArray(list) ? list : [];
  954. const badge = document.getElementById('pppoe-count-badge');
  955. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  956. const tbody = document.getElementById('pppoe-table-body');
  957. const empty = document.getElementById('pppoe-empty');
  958. if (!tbody) return;
  959. tbody.innerHTML = '';
  960. if (state.pppoeList.length === 0) {
  961. if (empty) empty.classList.remove('hidden');
  962. } else {
  963. if (empty) empty.classList.add('hidden');
  964. state.pppoeList.forEach(inst => {
  965. const tr = document.createElement('tr');
  966. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  967. tr.innerHTML = `
  968. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  969. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  970. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  971. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  972. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  973. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  974. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  975. <td class="py-2.5 px-3 text-center">
  976. <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'}">
  977. ${inst.default_route ? 'Yes' : 'No'}
  978. </span>
  979. </td>
  980. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  981. ${inst.running ? `
  982. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  983. ` : `
  984. <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>
  985. `}
  986. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  987. ${inst.disabled ? 'Enable' : 'Disable'}
  988. </button>
  989. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  990. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  991. </td>
  992. `;
  993. tbody.appendChild(tr);
  994. });
  995. }
  996. } catch (err) {
  997. console.error('Failed to load PPPoE:', err);
  998. }
  999. }
  1000. function openAddPPPoEModal() {
  1001. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1002. document.getElementById('pppoe-modal-edit-orig').value = '';
  1003. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1004. document.getElementById('pppoe-modal-name').readOnly = false;
  1005. document.getElementById('pppoe-modal-user').value = '';
  1006. document.getElementById('pppoe-modal-pass').value = '';
  1007. document.getElementById('pppoe-modal-service').value = '';
  1008. document.getElementById('pppoe-modal-mtu').value = '1492';
  1009. document.getElementById('pppoe-modal-defroute').checked = true;
  1010. document.getElementById('pppoe-modal-reconnect').checked = true;
  1011. document.getElementById('pppoe-modal-disabled').checked = false;
  1012. // Populate profiles
  1013. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1014. // Populate interfaces
  1015. const sel = document.getElementById('pppoe-modal-iface');
  1016. sel.innerHTML = '';
  1017. (state.interfaces || []).forEach(i => {
  1018. if (i.name === 'lo') return;
  1019. const opt = document.createElement('option');
  1020. opt.value = i.name;
  1021. opt.innerText = `${i.name} (${i.role || i.type})`;
  1022. sel.appendChild(opt);
  1023. });
  1024. document.getElementById('pppoe-modal').classList.remove('hidden');
  1025. }
  1026. function openEditPPPoEModal(name) {
  1027. const inst = (state.pppoeList || []).find(i => i.name === name);
  1028. if (!inst) return;
  1029. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1030. document.getElementById('pppoe-modal-edit-orig').value = name;
  1031. document.getElementById('pppoe-modal-name').value = inst.name;
  1032. document.getElementById('pppoe-modal-name').readOnly = true;
  1033. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1034. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1035. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1036. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1037. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1038. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1039. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1040. // Populate profiles
  1041. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1042. const sel = document.getElementById('pppoe-modal-iface');
  1043. sel.innerHTML = '';
  1044. (state.interfaces || []).forEach(i => {
  1045. if (i.name === 'lo') return;
  1046. const opt = document.createElement('option');
  1047. opt.value = i.name;
  1048. opt.innerText = `${i.name} (${i.role || i.type})`;
  1049. if (i.name === inst.interface) opt.selected = true;
  1050. sel.appendChild(opt);
  1051. });
  1052. document.getElementById('pppoe-modal').classList.remove('hidden');
  1053. }
  1054. function closePPPoEModal() {
  1055. document.getElementById('pppoe-modal').classList.add('hidden');
  1056. }
  1057. async function submitSavePPPoE(e) {
  1058. e.preventDefault();
  1059. const name = document.getElementById('pppoe-modal-name').value.trim();
  1060. const iface = document.getElementById('pppoe-modal-iface').value;
  1061. const user = document.getElementById('pppoe-modal-user').value.trim();
  1062. const pass = document.getElementById('pppoe-modal-pass').value;
  1063. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1064. const service = document.getElementById('pppoe-modal-service').value.trim();
  1065. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1066. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1067. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1068. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1069. try {
  1070. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1071. method: 'POST',
  1072. headers: { 'Content-Type': 'application/json' },
  1073. body: JSON.stringify({
  1074. name,
  1075. interface: iface,
  1076. username: user,
  1077. password: pass,
  1078. profile: profile,
  1079. service_name: service,
  1080. mtu,
  1081. default_route: defRoute,
  1082. auto_reconnect: reconnect,
  1083. disabled
  1084. })
  1085. });
  1086. if (res.ok) {
  1087. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1088. closePPPoEModal();
  1089. loadPPPoE(false);
  1090. fetchData(false);
  1091. } else {
  1092. const err = await res.json();
  1093. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1094. }
  1095. } catch (err) {
  1096. showToast('Error', err.message, 'error');
  1097. }
  1098. }
  1099. async function connectPPPoEInstance(name) {
  1100. try {
  1101. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1102. if (res.ok) {
  1103. showToast('Connecting', `Dialing ${name}...`, 'info');
  1104. setTimeout(() => loadPPPoE(false), 2000);
  1105. }
  1106. } catch (err) {
  1107. showToast('Error', err.message, 'error');
  1108. }
  1109. }
  1110. async function disconnectPPPoEInstance(name) {
  1111. try {
  1112. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1113. if (res.ok) {
  1114. showToast('Disconnected', `${name} session terminated`, 'info');
  1115. setTimeout(() => loadPPPoE(false), 1000);
  1116. }
  1117. } catch (err) {
  1118. showToast('Error', err.message, 'error');
  1119. }
  1120. }
  1121. async function togglePPPoEState(name, enable) {
  1122. try {
  1123. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1124. method: 'POST',
  1125. headers: { 'Content-Type': 'application/json' },
  1126. body: JSON.stringify({ enabled: enable })
  1127. });
  1128. if (res.ok) {
  1129. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1130. loadPPPoE(false);
  1131. }
  1132. } catch (err) {
  1133. showToast('Error', err.message, 'error');
  1134. }
  1135. }
  1136. async function deletePPPoEInstance(name) {
  1137. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1138. try {
  1139. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1140. if (res.ok) {
  1141. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1142. loadPPPoE(false);
  1143. fetchData(false);
  1144. }
  1145. } catch (err) {
  1146. showToast('Error', err.message, 'error');
  1147. }
  1148. }
  1149. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1150. state.wgSubTab = 'ifaces';
  1151. function switchWGSubTab(tab) {
  1152. state.wgSubTab = tab;
  1153. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1154. const peersPanel = document.getElementById('wg-subtab-peers');
  1155. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1156. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1157. if (tab === 'ifaces') {
  1158. ifacesPanel?.classList.remove('hidden');
  1159. peersPanel?.classList.add('hidden');
  1160. 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';
  1161. 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';
  1162. } else {
  1163. ifacesPanel?.classList.add('hidden');
  1164. peersPanel?.classList.remove('hidden');
  1165. 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';
  1166. 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';
  1167. renderWGPeers();
  1168. }
  1169. }
  1170. async function loadWireGuard(populateInputs = true) {
  1171. try {
  1172. const [ifacesRes, peersRes] = await Promise.all([
  1173. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1174. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1175. ]);
  1176. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1177. const peers = peersRes.ok ? await peersRes.json() : [];
  1178. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1179. state.wgPeers = Array.isArray(peers) ? peers : [];
  1180. // Badges
  1181. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1182. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1183. const peersCountBadge = document.getElementById('wg-peers-count');
  1184. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1185. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1186. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1187. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1188. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1189. // Render Interfaces
  1190. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1191. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1192. if (ifacesTbody) {
  1193. ifacesTbody.innerHTML = '';
  1194. if (state.wgInterfaces.length === 0) {
  1195. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1196. } else {
  1197. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1198. state.wgInterfaces.forEach(iface => {
  1199. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1200. const tr = document.createElement('tr');
  1201. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1202. tr.innerHTML = `
  1203. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1204. <td class="py-2.5 px-3">
  1205. <div class="flex items-center gap-1.5">
  1206. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1207. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1208. </div>
  1209. </td>
  1210. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1211. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1212. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1213. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1214. ${(iface.public_key || '').substring(0, 10)}... 📋
  1215. </span>
  1216. </td>
  1217. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1218. <td class="py-2.5 px-3 text-center">
  1219. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1220. </td>
  1221. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1222. ${iface.running ? `
  1223. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1224. ` : `
  1225. <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>
  1226. `}
  1227. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1228. ${iface.disabled ? 'Enable' : 'Disable'}
  1229. </button>
  1230. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1231. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1232. </td>
  1233. `;
  1234. ifacesTbody.appendChild(tr);
  1235. });
  1236. }
  1237. }
  1238. // Populate filter dropdown in peers tab
  1239. const filterSel = document.getElementById('wg-peers-filter-iface');
  1240. if (filterSel) {
  1241. const currentVal = filterSel.value;
  1242. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1243. state.wgInterfaces.forEach(i => {
  1244. const opt = document.createElement('option');
  1245. opt.value = i.name;
  1246. opt.innerText = i.name;
  1247. if (i.name === currentVal) opt.selected = true;
  1248. filterSel.appendChild(opt);
  1249. });
  1250. }
  1251. renderWGPeers();
  1252. } catch (err) {
  1253. console.error('Failed to load WireGuard:', err);
  1254. }
  1255. }
  1256. function renderWGPeers() {
  1257. const filterSel = document.getElementById('wg-peers-filter-iface');
  1258. const selectedIface = filterSel ? filterSel.value : '';
  1259. const tbody = document.getElementById('wg-peers-table-body');
  1260. const empty = document.getElementById('wg-peers-empty');
  1261. if (!tbody) return;
  1262. tbody.innerHTML = '';
  1263. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1264. if (filtered.length === 0) {
  1265. if (empty) empty.classList.remove('hidden');
  1266. } else {
  1267. if (empty) empty.classList.add('hidden');
  1268. filtered.forEach(p => {
  1269. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1270. const tr = document.createElement('tr');
  1271. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1272. tr.innerHTML = `
  1273. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1274. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1275. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1276. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1277. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1278. ${(p.public_key || '').substring(0, 10)}... 📋
  1279. </span>
  1280. </td>
  1281. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1282. <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>
  1283. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1284. <td class="py-2.5 px-3 font-mono text-[11px]">
  1285. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1286. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1287. </td>
  1288. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1289. <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">
  1290. ${p.disabled ? 'Enable' : 'Disable'}
  1291. </button>
  1292. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1293. <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>
  1294. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1295. </td>
  1296. `;
  1297. tbody.appendChild(tr);
  1298. });
  1299. }
  1300. }
  1301. function openAddWGInterfaceModal() {
  1302. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1303. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1304. const nameEl = document.getElementById('wg-iface-modal-name');
  1305. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1306. nameEl.readOnly = false;
  1307. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1308. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1309. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1310. document.getElementById('wg-iface-modal-comment').value = '';
  1311. document.getElementById('wg-iface-modal-pubkey').value = '';
  1312. document.getElementById('wg-iface-modal-privkey').value = '';
  1313. document.getElementById('wg-iface-modal-disabled').checked = false;
  1314. generateWGInterfaceKeys();
  1315. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1316. }
  1317. function openEditWGInterfaceModal(name) {
  1318. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1319. if (!iface) return;
  1320. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1321. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1322. const nameEl = document.getElementById('wg-iface-modal-name');
  1323. nameEl.value = iface.name;
  1324. nameEl.readOnly = false; // ALLOW RENAMING
  1325. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1326. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1327. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1328. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1329. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1330. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1331. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1332. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1333. }
  1334. function closeAddWGInterfaceModal() {
  1335. document.getElementById('wg-iface-modal').classList.add('hidden');
  1336. }
  1337. async function generateWGInterfaceKeys() {
  1338. try {
  1339. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1340. const keys = await res.json();
  1341. if (res.ok) {
  1342. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1343. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1344. }
  1345. } catch (err) {
  1346. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1347. }
  1348. }
  1349. async function onWGInterfacePrivKeyInput() {
  1350. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1351. if (!privKey) return;
  1352. try {
  1353. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1354. method: 'POST',
  1355. headers: { 'Content-Type': 'application/json' },
  1356. body: JSON.stringify({ private_key: privKey })
  1357. });
  1358. if (res.ok) {
  1359. const data = await res.json();
  1360. if (data.public_key) {
  1361. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1362. }
  1363. }
  1364. } catch (err) {
  1365. // Ignore while typing
  1366. }
  1367. }
  1368. function toggleWGPrivKeyVisibility() {
  1369. const el = document.getElementById('wg-iface-modal-privkey');
  1370. const btn = document.getElementById('btn-toggle-wg-privkey');
  1371. if (el.type === 'password') {
  1372. el.type = 'text';
  1373. btn.innerText = '🙈 Hide';
  1374. } else {
  1375. el.type = 'password';
  1376. btn.innerText = '👁️ Show';
  1377. }
  1378. }
  1379. function copyWGInterfacePubKey() {
  1380. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1381. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1382. }
  1383. async function submitSaveWGInterface(e) {
  1384. e.preventDefault();
  1385. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1386. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1387. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1388. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1389. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1390. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1391. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1392. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1393. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1394. try {
  1395. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1396. method: 'POST',
  1397. headers: { 'Content-Type': 'application/json' },
  1398. body: JSON.stringify({
  1399. orig_name: origName,
  1400. name,
  1401. listen_port: port,
  1402. address: addr,
  1403. mtu,
  1404. comment,
  1405. public_key: pub,
  1406. private_key: priv,
  1407. disabled
  1408. })
  1409. });
  1410. const data = await res.json();
  1411. if (res.ok) {
  1412. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1413. closeAddWGInterfaceModal();
  1414. loadWireGuard(false);
  1415. fetchData(false);
  1416. } else {
  1417. showToast('Error', data.error || 'Failed to save interface', 'error');
  1418. }
  1419. } catch (err) {
  1420. showToast('Error', err.message, 'error');
  1421. }
  1422. }
  1423. async function startWGInterface(name) {
  1424. try {
  1425. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1426. if (res.ok) {
  1427. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1428. loadWireGuard(false);
  1429. fetchData(false);
  1430. }
  1431. } catch (err) {
  1432. showToast('Error', err.message, 'error');
  1433. }
  1434. }
  1435. async function stopWGInterface(name) {
  1436. try {
  1437. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1438. if (res.ok) {
  1439. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1440. loadWireGuard(false);
  1441. fetchData(false);
  1442. }
  1443. } catch (err) {
  1444. showToast('Error', err.message, 'error');
  1445. }
  1446. }
  1447. async function toggleWGInterfaceState(name, enable) {
  1448. try {
  1449. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1450. method: 'POST',
  1451. headers: { 'Content-Type': 'application/json' },
  1452. body: JSON.stringify({ enabled: enable })
  1453. });
  1454. if (res.ok) {
  1455. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1456. loadWireGuard(false);
  1457. fetchData(false);
  1458. }
  1459. } catch (err) {
  1460. showToast('Error', err.message, 'error');
  1461. }
  1462. }
  1463. async function deleteWGInterface(name) {
  1464. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1465. try {
  1466. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1467. if (res.ok) {
  1468. showToast('Deleted', `Interface ${name} removed`, 'success');
  1469. loadWireGuard(false);
  1470. fetchData(false);
  1471. }
  1472. } catch (err) {
  1473. showToast('Error', err.message, 'error');
  1474. }
  1475. }
  1476. function populateWGPeerIfaceSelect(selectedIface = '') {
  1477. const sel = document.getElementById('wg-peer-modal-iface');
  1478. if (!sel) return;
  1479. sel.innerHTML = '';
  1480. (state.wgInterfaces || []).forEach(i => {
  1481. const opt = document.createElement('option');
  1482. opt.value = i.name;
  1483. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1484. if (i.name === selectedIface) opt.selected = true;
  1485. sel.appendChild(opt);
  1486. });
  1487. }
  1488. function openAddWGPeerModal() {
  1489. if ((state.wgInterfaces || []).length === 0) {
  1490. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1491. openAddWGInterfaceModal();
  1492. return;
  1493. }
  1494. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1495. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1496. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1497. populateWGPeerIfaceSelect();
  1498. document.getElementById('wg-peer-modal-name').value = '';
  1499. document.getElementById('wg-peer-modal-pubkey').value = '';
  1500. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1501. document.getElementById('wg-peer-modal-endpoint').value = '';
  1502. document.getElementById('wg-peer-modal-port').value = '';
  1503. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1504. document.getElementById('wg-peer-modal-preshared').value = '';
  1505. document.getElementById('wg-peer-modal-disabled').checked = false;
  1506. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1507. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1508. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1509. }
  1510. function openEditWGPeerModal(ifaceName, pubKey) {
  1511. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1512. if (!peer) {
  1513. showToast('Not Found', 'Peer not found', 'warning');
  1514. return;
  1515. }
  1516. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1517. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1518. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1519. populateWGPeerIfaceSelect(peer.interface);
  1520. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1521. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1522. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1523. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1524. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1525. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1526. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1527. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1528. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1529. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1530. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1531. }
  1532. function closeAddWGPeerModal() {
  1533. document.getElementById('wg-peer-modal').classList.add('hidden');
  1534. }
  1535. async function generatePeerKeypairHelper() {
  1536. try {
  1537. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1538. const keys = await res.json();
  1539. if (res.ok) {
  1540. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1541. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1542. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1543. checkWGPeerKeyValidity();
  1544. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1545. }
  1546. } catch (err) {
  1547. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1548. }
  1549. }
  1550. function copyGeneratedPeerPrivKey() {
  1551. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1552. if (priv) copyToClipboard(priv, 'Client Private Key');
  1553. }
  1554. async function generatePeerPSK() {
  1555. try {
  1556. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1557. const keys = await res.json();
  1558. if (res.ok && keys.private_key) {
  1559. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1560. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1561. }
  1562. } catch (err) {
  1563. showToast('Error', err.message, 'error');
  1564. }
  1565. }
  1566. function checkWGPeerKeyValidity() {
  1567. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1568. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1569. const warningEl = document.getElementById('wg-peer-key-warning');
  1570. if (!warningEl) return;
  1571. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1572. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1573. warningEl.classList.remove('hidden');
  1574. } else {
  1575. warningEl.classList.add('hidden');
  1576. }
  1577. }
  1578. async function submitSaveWGPeer(e) {
  1579. e.preventDefault();
  1580. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1581. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1582. const iface = document.getElementById('wg-peer-modal-iface').value;
  1583. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1584. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1585. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1586. .split(',')
  1587. .map(s => s.trim())
  1588. .filter(s => s.length > 0);
  1589. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1590. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1591. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1592. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1593. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1594. // Validation
  1595. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1596. if (targetIface && targetIface.public_key === pub) {
  1597. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1598. return;
  1599. }
  1600. try {
  1601. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1602. method: 'POST',
  1603. headers: { 'Content-Type': 'application/json' },
  1604. body: JSON.stringify({
  1605. orig_interface: origIface,
  1606. orig_public_key: origPubKey,
  1607. interface: iface,
  1608. name,
  1609. public_key: pub,
  1610. allowed_ips: allowed,
  1611. endpoint_address: epHost,
  1612. endpoint_port: epPort,
  1613. persistent_keepalive: keepalive,
  1614. preshared_key: psk,
  1615. disabled
  1616. })
  1617. });
  1618. const data = await res.json();
  1619. if (res.ok) {
  1620. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1621. closeAddWGPeerModal();
  1622. loadWireGuard(false);
  1623. } else {
  1624. showToast('Error', data.error || 'Failed to save peer', 'error');
  1625. }
  1626. } catch (err) {
  1627. showToast('Error', err.message, 'error');
  1628. }
  1629. }
  1630. async function toggleWGPeerState(iface, pubkey, enable) {
  1631. try {
  1632. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1633. method: 'POST',
  1634. headers: { 'Content-Type': 'application/json' },
  1635. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1636. });
  1637. const data = await res.json();
  1638. if (res.ok) {
  1639. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1640. loadWireGuard(false);
  1641. } else {
  1642. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1643. }
  1644. } catch (err) {
  1645. showToast('Error', err.message, 'error');
  1646. }
  1647. }
  1648. async function deleteWGPeer(iface, pubkey) {
  1649. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1650. try {
  1651. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1652. method: 'POST',
  1653. headers: { 'Content-Type': 'application/json' },
  1654. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1655. });
  1656. const data = await res.json();
  1657. if (res.ok) {
  1658. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1659. loadWireGuard(false);
  1660. } else {
  1661. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1662. }
  1663. } catch (err) {
  1664. showToast('Error', err.message, 'error');
  1665. }
  1666. }
  1667. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1668. function switchIpsecModalTab(tab) {
  1669. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1670. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1671. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1672. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1673. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1674. if (tab === 'p1') {
  1675. if (p1Tab) {
  1676. 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';
  1677. }
  1678. if (p2Tab) {
  1679. 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';
  1680. }
  1681. if (p1Content) p1Content.classList.remove('hidden');
  1682. if (p2Content) p2Content.classList.add('hidden');
  1683. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1684. } else {
  1685. if (p1Tab) {
  1686. 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';
  1687. }
  1688. if (p2Tab) {
  1689. 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';
  1690. }
  1691. if (p1Content) p1Content.classList.add('hidden');
  1692. if (p2Content) p2Content.classList.remove('hidden');
  1693. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1694. }
  1695. }
  1696. function toggleIpsecPhaseStep() {
  1697. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1698. if (p1Content && !p1Content.classList.contains('hidden')) {
  1699. switchIpsecModalTab('p2');
  1700. } else {
  1701. switchIpsecModalTab('p1');
  1702. }
  1703. }
  1704. function toggleIpsecPskVisibility() {
  1705. const pskInput = document.getElementById('ipsec-modal-psk');
  1706. if (!pskInput) return;
  1707. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1708. }
  1709. function addIpsecLocalSubnet(val = '') {
  1710. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1711. if (!container) return;
  1712. const row = document.createElement('div');
  1713. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1714. row.innerHTML = `
  1715. <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">
  1716. <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>
  1717. `;
  1718. container.appendChild(row);
  1719. }
  1720. function addIpsecRemoteSubnet(val = '') {
  1721. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1722. if (!container) return;
  1723. const row = document.createElement('div');
  1724. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1725. row.innerHTML = `
  1726. <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">
  1727. <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>
  1728. `;
  1729. container.appendChild(row);
  1730. }
  1731. function updateIpsecEspProposalFromPFS(val) {
  1732. const prop = document.getElementById('ipsec-modal-espprop');
  1733. if (!prop) return;
  1734. if (val === 'none') {
  1735. prop.value = 'aes256-sha256,aes128-sha256,default';
  1736. } else {
  1737. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1738. }
  1739. }
  1740. function updateIpsecIkeProposalFromDH(dh) {
  1741. const el = document.getElementById('ipsec-modal-ikeprop');
  1742. if (el) {
  1743. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1744. }
  1745. }
  1746. function safeSetVal(id, val) {
  1747. const el = document.getElementById(id);
  1748. if (el) el.value = val;
  1749. }
  1750. function safeSetChecked(id, val) {
  1751. const el = document.getElementById(id);
  1752. if (el) el.checked = !!val;
  1753. }
  1754. function safeGetVal(id, def = '') {
  1755. const el = document.getElementById(id);
  1756. return el ? el.value : def;
  1757. }
  1758. async function loadIPSec(populateInputs = true) {
  1759. try {
  1760. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1761. const list = await res.json();
  1762. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1763. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1764. const badge = document.getElementById('ipsec-sas-badge');
  1765. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1766. const tbody = document.getElementById('ipsec-table-body');
  1767. const empty = document.getElementById('ipsec-empty');
  1768. if (!tbody) return;
  1769. tbody.innerHTML = '';
  1770. if (state.ipsecTunnels.length === 0) {
  1771. if (empty) empty.classList.remove('hidden');
  1772. } else {
  1773. if (empty) empty.classList.add('hidden');
  1774. state.ipsecTunnels.forEach(c => {
  1775. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1776. const tr = document.createElement('tr');
  1777. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1778. // Local subnets tags
  1779. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1780. 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('');
  1781. // Remote subnets tags
  1782. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1783. 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('');
  1784. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1785. const p2Name = c.phase2_name || `${c.name}_p2`;
  1786. tr.innerHTML = `
  1787. <td class="py-2.5 px-3 text-center">
  1788. ${isEstablished ? `
  1789. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1790. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1791. <span>UP</span>
  1792. </span>
  1793. ` : (c.disabled ? `
  1794. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1795. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1796. <span>DOWN</span>
  1797. </span>
  1798. ` : `
  1799. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1800. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1801. <span>IDLE</span>
  1802. </span>
  1803. `)}
  1804. </td>
  1805. <td class="py-2.5 px-4 font-bold text-white">
  1806. <div class="flex items-center gap-2">
  1807. <span class="text-amber-400">🛡</span>
  1808. <div>
  1809. <div>${escapeHtml(c.name)}</div>
  1810. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1811. </div>
  1812. </div>
  1813. </td>
  1814. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1815. <td class="py-2.5 px-4 font-sans">
  1816. <div class="flex items-center gap-1.5">
  1817. <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>
  1818. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1819. </div>
  1820. </td>
  1821. <td class="py-2.5 px-4">
  1822. <div class="space-y-1">
  1823. <div class="flex items-center flex-wrap gap-1">
  1824. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1825. ${localBadges}
  1826. </div>
  1827. <div class="flex items-center flex-wrap gap-1">
  1828. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1829. ${remoteBadges}
  1830. </div>
  1831. </div>
  1832. </td>
  1833. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1834. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1835. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1836. </div>
  1837. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1838. </td>
  1839. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1840. ${isEstablished ? `
  1841. <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>
  1842. ` : `
  1843. <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>
  1844. `}
  1845. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1846. ${c.disabled ? 'Enable' : 'Disable'}
  1847. </button>
  1848. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1849. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1850. </td>
  1851. `;
  1852. tbody.appendChild(tr);
  1853. });
  1854. }
  1855. } catch (err) {
  1856. console.error('Failed to load IPSec:', err);
  1857. }
  1858. }
  1859. function openAddIPSecModal() {
  1860. const modal = document.getElementById('ipsec-modal');
  1861. if (!modal) return;
  1862. const title = document.getElementById('ipsec-modal-title');
  1863. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1864. // Phase 1 Fields
  1865. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1866. const nameEl = document.getElementById('ipsec-modal-name');
  1867. if (nameEl) nameEl.readOnly = false;
  1868. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1869. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1870. safeSetVal('ipsec-modal-remotegw', '');
  1871. safeSetVal('ipsec-modal-localaddrs', '');
  1872. safeSetVal('ipsec-modal-comments', '');
  1873. safeSetVal('ipsec-modal-psk', '');
  1874. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1875. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1876. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1877. safeSetVal('ipsec-modal-localid', '');
  1878. safeSetVal('ipsec-modal-remoteid', '');
  1879. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1880. // Phase 2 Fields
  1881. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1882. safeSetVal('ipsec-modal-espkeylife', '28800');
  1883. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1884. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1885. safeSetChecked('ipsec-modal-autostart', true);
  1886. safeSetChecked('ipsec-modal-disabled', false);
  1887. // Clear & Populate default dynamic subnets
  1888. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1889. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1890. if (localContainer) {
  1891. localContainer.innerHTML = '';
  1892. addIpsecLocalSubnet('192.168.10.0/24');
  1893. }
  1894. if (remoteContainer) {
  1895. remoteContainer.innerHTML = '';
  1896. addIpsecRemoteSubnet('192.168.20.0/24');
  1897. }
  1898. switchIpsecModalTab('p1');
  1899. modal.classList.remove('hidden');
  1900. }
  1901. function openEditIPSecModal(name) {
  1902. const modal = document.getElementById('ipsec-modal');
  1903. if (!modal) return;
  1904. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1905. if (!conn) return;
  1906. const title = document.getElementById('ipsec-modal-title');
  1907. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1908. // Phase 1 Fields
  1909. safeSetVal('ipsec-modal-name', conn.name);
  1910. const nameEl = document.getElementById('ipsec-modal-name');
  1911. if (nameEl) nameEl.readOnly = true;
  1912. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1913. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1914. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1915. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1916. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1917. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1918. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1919. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1920. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1921. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1922. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1923. // Phase 2 Fields
  1924. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1925. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1926. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1927. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1928. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1929. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1930. // Populate dynamic subnets
  1931. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1932. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1933. if (localContainer) {
  1934. localContainer.innerHTML = '';
  1935. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1936. locals.forEach(s => addIpsecLocalSubnet(s));
  1937. }
  1938. if (remoteContainer) {
  1939. remoteContainer.innerHTML = '';
  1940. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1941. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1942. }
  1943. switchIpsecModalTab('p1');
  1944. modal.classList.remove('hidden');
  1945. }
  1946. function closeAddIPSecModal() {
  1947. const modal = document.getElementById('ipsec-modal');
  1948. if (modal) modal.classList.add('hidden');
  1949. }
  1950. async function submitSaveIPSec(e) {
  1951. if (e) e.preventDefault();
  1952. const name = safeGetVal('ipsec-modal-name').trim();
  1953. if (!name) {
  1954. showToast('Error', 'Tunnel name is required', 'error');
  1955. return;
  1956. }
  1957. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1958. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1959. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1960. const comments = safeGetVal('ipsec-modal-comments').trim();
  1961. const psk = safeGetVal('ipsec-modal-psk');
  1962. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1963. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1964. const localId = safeGetVal('ipsec-modal-localid').trim();
  1965. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1966. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1967. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1968. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1969. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1970. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1971. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1972. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1973. // Scrape dynamic local and remote subnets
  1974. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1975. const localSubnets = [];
  1976. localInputs.forEach(inp => {
  1977. const v = inp.value.trim();
  1978. if (v) localSubnets.push(v);
  1979. });
  1980. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1981. const remoteSubnets = [];
  1982. remoteInputs.forEach(inp => {
  1983. const v = inp.value.trim();
  1984. if (v) remoteSubnets.push(v);
  1985. });
  1986. try {
  1987. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1988. method: 'POST',
  1989. headers: { 'Content-Type': 'application/json' },
  1990. body: JSON.stringify({
  1991. name,
  1992. comment: comments,
  1993. ike_version: ikeVersion,
  1994. local_addrs: localAddrs,
  1995. remote_addrs: remotegw,
  1996. preshared_key: psk,
  1997. ike_proposals: ikeProposals,
  1998. ike_keylife: ikeKeylife,
  1999. local_id: localId,
  2000. remote_id: remoteId,
  2001. dpd: dpd,
  2002. phase2_name: phase2Name,
  2003. esp_proposals: espProposals,
  2004. esp_keylife: espKeylife,
  2005. pfs_group: pfsGroup,
  2006. pfs: pfsGroup !== 'none',
  2007. local_subnets: localSubnets,
  2008. remote_subnets: remoteSubnets,
  2009. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2010. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2011. auto_start: autostart,
  2012. disabled
  2013. })
  2014. });
  2015. if (res.ok) {
  2016. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2017. closeAddIPSecModal();
  2018. loadIPSec(false);
  2019. } else {
  2020. const err = await res.json();
  2021. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2022. }
  2023. } catch (err) {
  2024. showToast('Error', err.message, 'error');
  2025. }
  2026. }
  2027. async function startIPSecTunnel(name) {
  2028. try {
  2029. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2030. if (res.ok) {
  2031. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2032. setTimeout(() => loadIPSec(false), 2000);
  2033. }
  2034. } catch (err) {
  2035. showToast('Error', err.message, 'error');
  2036. }
  2037. }
  2038. async function stopIPSecTunnel(name) {
  2039. try {
  2040. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2041. if (res.ok) {
  2042. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2043. loadIPSec(false);
  2044. }
  2045. } catch (err) {
  2046. showToast('Error', err.message, 'error');
  2047. }
  2048. }
  2049. async function toggleIPSecState(name, enable) {
  2050. try {
  2051. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2052. method: 'POST',
  2053. headers: { 'Content-Type': 'application/json' },
  2054. body: JSON.stringify({ enabled: enable })
  2055. });
  2056. if (res.ok) {
  2057. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2058. loadIPSec(false);
  2059. }
  2060. } catch (err) {
  2061. showToast('Error', err.message, 'error');
  2062. }
  2063. }
  2064. async function deleteIPSecConn(name) {
  2065. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2066. try {
  2067. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2068. if (res.ok) {
  2069. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2070. loadIPSec(false);
  2071. fetchData(false);
  2072. }
  2073. } catch (err) {
  2074. showToast('Error', err.message, 'error');
  2075. }
  2076. }
  2077. // ======================== L2TP Multi-Instance ========================
  2078. async function loadL2TP(populateInputs = true) {
  2079. try {
  2080. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2081. await fetchPPPProfilesList();
  2082. }
  2083. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2084. const list = await res.json();
  2085. state.l2tpList = Array.isArray(list) ? list : [];
  2086. const badge = document.getElementById('l2tp-count-badge');
  2087. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2088. const tbody = document.getElementById('l2tp-table-body');
  2089. const empty = document.getElementById('l2tp-empty');
  2090. if (!tbody) return;
  2091. tbody.innerHTML = '';
  2092. if (state.l2tpList.length === 0) {
  2093. if (empty) empty.classList.remove('hidden');
  2094. } else {
  2095. if (empty) empty.classList.add('hidden');
  2096. state.l2tpList.forEach(inst => {
  2097. const tr = document.createElement('tr');
  2098. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2099. tr.innerHTML = `
  2100. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2101. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2102. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2103. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2104. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2105. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2106. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2107. <td class="py-2.5 px-3 text-center">
  2108. <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'}">
  2109. ${inst.default_route ? 'Yes' : 'No'}
  2110. </span>
  2111. </td>
  2112. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2113. ${inst.running ? `
  2114. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2115. ` : `
  2116. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2117. `}
  2118. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2119. ${inst.disabled ? 'Enable' : 'Disable'}
  2120. </button>
  2121. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2122. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2123. </td>
  2124. `;
  2125. tbody.appendChild(tr);
  2126. });
  2127. }
  2128. } catch (err) {
  2129. console.error('Failed to load L2TP:', err);
  2130. }
  2131. }
  2132. async function openAddL2TPModal() {
  2133. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2134. await fetchPPPProfilesList();
  2135. }
  2136. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2137. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2138. document.getElementById('l2tp-modal-name').readOnly = false;
  2139. document.getElementById('l2tp-modal-server').value = '';
  2140. document.getElementById('l2tp-modal-user').value = '';
  2141. document.getElementById('l2tp-modal-pass').value = '';
  2142. document.getElementById('l2tp-modal-ipsec').value = '';
  2143. document.getElementById('l2tp-modal-defroute').checked = true;
  2144. document.getElementById('l2tp-modal-disabled').checked = false;
  2145. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2146. document.getElementById('l2tp-modal').classList.remove('hidden');
  2147. }
  2148. async function openEditL2TPModal(name) {
  2149. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2150. await fetchPPPProfilesList();
  2151. }
  2152. const inst = (state.l2tpList || []).find(i => i.name === name);
  2153. if (!inst) return;
  2154. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2155. document.getElementById('l2tp-modal-name').value = inst.name;
  2156. document.getElementById('l2tp-modal-name').readOnly = true;
  2157. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2158. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2159. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2160. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2161. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2162. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2163. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2164. document.getElementById('l2tp-modal').classList.remove('hidden');
  2165. }
  2166. function closeL2TPModal() {
  2167. document.getElementById('l2tp-modal').classList.add('hidden');
  2168. }
  2169. async function submitSaveL2TP(e) {
  2170. e.preventDefault();
  2171. const name = document.getElementById('l2tp-modal-name').value.trim();
  2172. const server = document.getElementById('l2tp-modal-server').value.trim();
  2173. const user = document.getElementById('l2tp-modal-user').value.trim();
  2174. const pass = document.getElementById('l2tp-modal-pass').value;
  2175. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2176. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2177. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2178. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2179. try {
  2180. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2181. method: 'POST',
  2182. headers: { 'Content-Type': 'application/json' },
  2183. body: JSON.stringify({
  2184. name,
  2185. connect_to: server,
  2186. username: user,
  2187. password: pass,
  2188. profile: profile,
  2189. ipsec_secret: ipsec,
  2190. default_route: defRoute,
  2191. disabled
  2192. })
  2193. });
  2194. if (res.ok) {
  2195. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2196. closeL2TPModal();
  2197. loadL2TP(false);
  2198. fetchData(false);
  2199. }
  2200. } catch (err) {
  2201. showToast('Error', err.message, 'error');
  2202. }
  2203. }
  2204. async function connectL2TPInstance(name) {
  2205. try {
  2206. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2207. if (res.ok) {
  2208. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2209. setTimeout(() => loadL2TP(false), 2000);
  2210. }
  2211. } catch (err) {
  2212. showToast('Error', err.message, 'error');
  2213. }
  2214. }
  2215. async function disconnectL2TPInstance(name) {
  2216. try {
  2217. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2218. if (res.ok) {
  2219. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2220. loadL2TP(false);
  2221. }
  2222. } catch (err) {
  2223. showToast('Error', err.message, 'error');
  2224. }
  2225. }
  2226. async function toggleL2TPState(name, enable) {
  2227. try {
  2228. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2229. method: 'POST',
  2230. headers: { 'Content-Type': 'application/json' },
  2231. body: JSON.stringify({ enabled: enable })
  2232. });
  2233. if (res.ok) {
  2234. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2235. loadL2TP(false);
  2236. }
  2237. } catch (err) {
  2238. showToast('Error', err.message, 'error');
  2239. }
  2240. }
  2241. async function deleteL2TPInstance(name) {
  2242. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2243. try {
  2244. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2245. if (res.ok) {
  2246. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2247. loadL2TP(false);
  2248. fetchData(false);
  2249. }
  2250. } catch (err) {
  2251. showToast('Error', err.message, 'error');
  2252. }
  2253. }
  2254. // ======================== PPTP Multi-Instance ========================
  2255. async function loadPPTP(populateInputs = true) {
  2256. try {
  2257. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2258. await fetchPPPProfilesList();
  2259. }
  2260. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2261. const list = await res.json();
  2262. state.pptpList = Array.isArray(list) ? list : [];
  2263. const badge = document.getElementById('pptp-count-badge');
  2264. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2265. const tbody = document.getElementById('pptp-table-body');
  2266. const empty = document.getElementById('pptp-empty');
  2267. if (!tbody) return;
  2268. tbody.innerHTML = '';
  2269. if (state.pptpList.length === 0) {
  2270. if (empty) empty.classList.remove('hidden');
  2271. } else {
  2272. if (empty) empty.classList.add('hidden');
  2273. state.pptpList.forEach(inst => {
  2274. const tr = document.createElement('tr');
  2275. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2276. tr.innerHTML = `
  2277. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2278. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2279. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2280. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2281. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2282. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2283. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2284. <td class="py-2.5 px-3 text-center">
  2285. <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'}">
  2286. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2287. </span>
  2288. </td>
  2289. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2290. ${inst.running ? `
  2291. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2292. ` : `
  2293. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2294. `}
  2295. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2296. ${inst.disabled ? 'Enable' : 'Disable'}
  2297. </button>
  2298. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2299. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2300. </td>
  2301. `;
  2302. tbody.appendChild(tr);
  2303. });
  2304. }
  2305. } catch (err) {
  2306. console.error('Failed to load PPTP:', err);
  2307. }
  2308. }
  2309. async function openAddPPTPModal() {
  2310. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2311. await fetchPPPProfilesList();
  2312. }
  2313. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2314. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2315. document.getElementById('pptp-modal-name').readOnly = false;
  2316. document.getElementById('pptp-modal-server').value = '';
  2317. document.getElementById('pptp-modal-user').value = '';
  2318. document.getElementById('pptp-modal-pass').value = '';
  2319. document.getElementById('pptp-modal-mppe').checked = true;
  2320. document.getElementById('pptp-modal-defroute').checked = true;
  2321. document.getElementById('pptp-modal-disabled').checked = false;
  2322. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2323. document.getElementById('pptp-modal').classList.remove('hidden');
  2324. }
  2325. async function openEditPPTPModal(name) {
  2326. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2327. await fetchPPPProfilesList();
  2328. }
  2329. const inst = (state.pptpList || []).find(i => i.name === name);
  2330. if (!inst) return;
  2331. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2332. document.getElementById('pptp-modal-name').value = inst.name;
  2333. document.getElementById('pptp-modal-name').readOnly = true;
  2334. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2335. document.getElementById('pptp-modal-user').value = inst.username || '';
  2336. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2337. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2338. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2339. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2340. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2341. document.getElementById('pptp-modal').classList.remove('hidden');
  2342. }
  2343. function closePPTPModal() {
  2344. document.getElementById('pptp-modal').classList.add('hidden');
  2345. }
  2346. async function submitSavePPTP(e) {
  2347. e.preventDefault();
  2348. const name = document.getElementById('pptp-modal-name').value.trim();
  2349. const server = document.getElementById('pptp-modal-server').value.trim();
  2350. const user = document.getElementById('pptp-modal-user').value.trim();
  2351. const pass = document.getElementById('pptp-modal-pass').value;
  2352. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2353. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2354. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2355. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2356. try {
  2357. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2358. method: 'POST',
  2359. headers: { 'Content-Type': 'application/json' },
  2360. body: JSON.stringify({
  2361. name,
  2362. connect_to: server,
  2363. username: user,
  2364. password: pass,
  2365. profile: profile,
  2366. require_mppe: mppe,
  2367. default_route: defRoute,
  2368. auto_reconnect: true,
  2369. disabled
  2370. })
  2371. });
  2372. if (res.ok) {
  2373. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2374. closePPTPModal();
  2375. loadPPTP(false);
  2376. fetchData(false);
  2377. }
  2378. } catch (err) {
  2379. showToast('Error', err.message, 'error');
  2380. }
  2381. }
  2382. async function connectPPTPInstance(name) {
  2383. try {
  2384. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2385. if (res.ok) {
  2386. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2387. setTimeout(() => loadPPTP(false), 2000);
  2388. }
  2389. } catch (err) {
  2390. showToast('Error', err.message, 'error');
  2391. }
  2392. }
  2393. async function disconnectPPTPInstance(name) {
  2394. try {
  2395. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2396. if (res.ok) {
  2397. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2398. loadPPTP(false);
  2399. }
  2400. } catch (err) {
  2401. showToast('Error', err.message, 'error');
  2402. }
  2403. }
  2404. async function togglePPTPState(name, enable) {
  2405. try {
  2406. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2407. method: 'POST',
  2408. headers: { 'Content-Type': 'application/json' },
  2409. body: JSON.stringify({ enabled: enable })
  2410. });
  2411. if (res.ok) {
  2412. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2413. loadPPTP(false);
  2414. }
  2415. } catch (err) {
  2416. showToast('Error', err.message, 'error');
  2417. }
  2418. }
  2419. async function deletePPTPInstance(name) {
  2420. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2421. try {
  2422. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2423. if (res.ok) {
  2424. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2425. loadPPTP(false);
  2426. fetchData(false);
  2427. }
  2428. } catch (err) {
  2429. showToast('Error', err.message, 'error');
  2430. }
  2431. }
  2432. // ---------------- Modal & Helper Functions ----------------
  2433. function openVlanModal(defaultParent = '') {
  2434. const select = document.getElementById('vlan-parent');
  2435. select.innerHTML = '';
  2436. const allIfaces = state.interfaces || [];
  2437. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2438. if (eligible.length === 0) {
  2439. const opt = document.createElement('option');
  2440. opt.value = '';
  2441. opt.innerText = 'No VLAN-capable interfaces available';
  2442. select.appendChild(opt);
  2443. } else {
  2444. eligible.forEach(i => {
  2445. const opt = document.createElement('option');
  2446. opt.value = i.name;
  2447. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2448. if (i.name === defaultParent) opt.selected = true;
  2449. select.appendChild(opt);
  2450. });
  2451. }
  2452. document.getElementById('vlan-id').value = '';
  2453. document.getElementById('vlan-name').value = '';
  2454. document.getElementById('vlan-ip').value = '';
  2455. document.getElementById('vlan-desc').value = '';
  2456. autoSuggestVlanName();
  2457. document.getElementById('vlan-modal').classList.remove('hidden');
  2458. }
  2459. function closeVlanModal() {
  2460. document.getElementById('vlan-modal').classList.add('hidden');
  2461. }
  2462. function autoSuggestVlanName() {
  2463. const parent = document.getElementById('vlan-parent').value;
  2464. if (!parent) return;
  2465. const id = document.getElementById('vlan-id').value;
  2466. const nameInput = document.getElementById('vlan-name');
  2467. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2468. }
  2469. function setSubnetPreset(cidr) {
  2470. const ipInput = document.getElementById('vlan-ip');
  2471. const id = document.getElementById('vlan-id').value || '10';
  2472. ipInput.value = `192.168.${id}.1${cidr}`;
  2473. }
  2474. async function submitCreateVlan(e) {
  2475. e.preventDefault();
  2476. const btn = document.getElementById('vlan-submit-btn');
  2477. btn.disabled = true;
  2478. btn.innerText = 'Creating...';
  2479. const parent = document.getElementById('vlan-parent').value;
  2480. if (!parent) {
  2481. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2482. btn.disabled = false;
  2483. btn.innerText = 'Create VLAN';
  2484. return;
  2485. }
  2486. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2487. const name = document.getElementById('vlan-name').value.trim();
  2488. const ip = document.getElementById('vlan-ip').value.trim();
  2489. const role = document.getElementById('vlan-role').value;
  2490. const desc = document.getElementById('vlan-desc').value.trim();
  2491. try {
  2492. const res = await fetch(`${API_BASE}/vlans`, {
  2493. method: 'POST',
  2494. headers: { 'Content-Type': 'application/json' },
  2495. body: JSON.stringify({
  2496. parent_name: parent,
  2497. vlan_id: id,
  2498. name: name,
  2499. ip_address: ip,
  2500. role: role,
  2501. description: desc,
  2502. mtu: 1500,
  2503. auto_up: true
  2504. })
  2505. });
  2506. const data = await res.json();
  2507. if (res.ok) {
  2508. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2509. state.expandedParents.add(parent);
  2510. closeVlanModal();
  2511. await fetchData(true);
  2512. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2513. } else {
  2514. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2515. }
  2516. } catch (err) {
  2517. showToast('Error', err.message, 'error');
  2518. } finally {
  2519. btn.disabled = false;
  2520. btn.innerText = 'Create VLAN';
  2521. }
  2522. }
  2523. async function confirmDeleteVlan(name) {
  2524. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2525. try {
  2526. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2527. if (res.ok) {
  2528. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2529. closeIfaceModal();
  2530. fetchData(true);
  2531. }
  2532. } catch (err) {
  2533. showToast('Error', err.message, 'error');
  2534. }
  2535. }
  2536. function openIfaceModal(name) {
  2537. const iface = (state.interfaces || []).find(i => i.name === name);
  2538. if (!iface) return;
  2539. state.currentModalIface = iface.name;
  2540. document.getElementById('modal-iface-name').innerText = iface.name;
  2541. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2542. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2543. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2544. document.getElementById('modal-iface-desc').value = iface.description || '';
  2545. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2546. if (iface.is_vlan) {
  2547. delBtn.classList.remove('hidden');
  2548. } else {
  2549. delBtn.classList.add('hidden');
  2550. }
  2551. renderModalIPs(iface);
  2552. document.getElementById('iface-modal').classList.remove('hidden');
  2553. }
  2554. function renderModalIPs(iface) {
  2555. const container = document.getElementById('modal-ip-list');
  2556. container.innerHTML = '';
  2557. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2558. if (addrs.length === 0) {
  2559. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2560. return;
  2561. }
  2562. addrs.forEach(addr => {
  2563. const row = document.createElement('div');
  2564. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2565. row.innerHTML = `
  2566. <span class="text-white">${addr}</span>
  2567. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2568. `;
  2569. container.appendChild(row);
  2570. });
  2571. }
  2572. function closeIfaceModal() {
  2573. document.getElementById('iface-modal').classList.add('hidden');
  2574. state.currentModalIface = null;
  2575. }
  2576. async function setIfaceState(name, newState) {
  2577. await toggleInterfaceState(name, newState);
  2578. const updated = (state.interfaces || []).find(i => i.name === name);
  2579. if (updated) openIfaceModal(name);
  2580. }
  2581. async function applyMTU() {
  2582. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2583. try {
  2584. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2585. method: 'POST',
  2586. headers: { 'Content-Type': 'application/json' },
  2587. body: JSON.stringify({ mtu })
  2588. });
  2589. if (res.ok) {
  2590. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2591. fetchData(false);
  2592. }
  2593. } catch (err) {
  2594. showToast('Error', err.message, 'error');
  2595. }
  2596. }
  2597. async function addInterfaceIP() {
  2598. const ip = document.getElementById('modal-new-ip').value.trim();
  2599. if (!ip) return;
  2600. try {
  2601. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2602. method: 'POST',
  2603. headers: { 'Content-Type': 'application/json' },
  2604. body: JSON.stringify({ ip })
  2605. });
  2606. if (res.ok) {
  2607. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2608. document.getElementById('modal-new-ip').value = '';
  2609. await fetchData(false);
  2610. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2611. if (iface) renderModalIPs(iface);
  2612. } else {
  2613. const err = await res.json();
  2614. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2615. }
  2616. } catch (err) {
  2617. showToast('Error', err.message, 'error');
  2618. }
  2619. }
  2620. async function removeInterfaceIP(ip) {
  2621. if (!confirm(`Remove IP ${ip}?`)) return;
  2622. try {
  2623. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2624. method: 'DELETE',
  2625. headers: { 'Content-Type': 'application/json' },
  2626. body: JSON.stringify({ ip })
  2627. });
  2628. if (res.ok) {
  2629. showToast('IP Removed', `Removed ${ip}`, 'success');
  2630. await fetchData(false);
  2631. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2632. if (iface) renderModalIPs(iface);
  2633. }
  2634. } catch (err) {
  2635. showToast('Error', err.message, 'error');
  2636. }
  2637. }
  2638. async function saveInterfaceMetadata() {
  2639. const role = document.getElementById('modal-iface-role').value;
  2640. const desc = document.getElementById('modal-iface-desc').value.trim();
  2641. try {
  2642. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2643. method: 'POST',
  2644. headers: { 'Content-Type': 'application/json' },
  2645. body: JSON.stringify({ role, description: desc })
  2646. });
  2647. if (res.ok) {
  2648. showToast('Saved', 'Metadata updated', 'success');
  2649. closeIfaceModal();
  2650. fetchData(false);
  2651. }
  2652. } catch (err) {
  2653. showToast('Error', err.message, 'error');
  2654. }
  2655. }
  2656. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2657. state.fwSubTab = 'filter';
  2658. state.routesSubTab = 'routes';
  2659. function renderRuleFlag(disabled, hasComment) {
  2660. let flags = '';
  2661. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2662. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2663. return flags || '<span class="text-slate-600">-</span>';
  2664. }
  2665. function renderActionBadge(action) {
  2666. const act = (action || '').toLowerCase();
  2667. let color = 'bg-slate-800 text-slate-300';
  2668. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2669. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2670. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2671. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2672. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2673. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2674. }
  2675. function switchFWSubTab(tab) {
  2676. state.fwSubTab = tab;
  2677. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2678. tabs.forEach(t => {
  2679. const panel = document.getElementById(`fw-subtab-${t}`);
  2680. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2681. if (panel) {
  2682. if (t === tab) panel.classList.remove('hidden');
  2683. else panel.classList.add('hidden');
  2684. }
  2685. if (btn) {
  2686. if (t === tab) {
  2687. 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';
  2688. } else {
  2689. 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';
  2690. }
  2691. }
  2692. });
  2693. const addBtn = document.getElementById('fw-primary-add-btn');
  2694. if (addBtn) {
  2695. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2696. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2697. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2698. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2699. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2700. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2701. }
  2702. if (tab === 'geo') loadGeoIP();
  2703. if (tab === 'connections') loadConnections();
  2704. setTimeout(initTableSorting, 50);
  2705. }
  2706. function openCurrentFWModal() {
  2707. if (state.fwSubTab === 'filter') openAddFilterModal();
  2708. else if (state.fwSubTab === 'nat') openAddNATModal();
  2709. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2710. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2711. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2712. else if (state.fwSubTab === 'connections') loadConnections();
  2713. }
  2714. async function loadFirewall(populateDropdowns = true) {
  2715. try {
  2716. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2717. fetch(`${API_BASE}/firewall/summary`),
  2718. fetch(`${API_BASE}/firewall/filter`),
  2719. fetch(`${API_BASE}/firewall/nat`),
  2720. fetch(`${API_BASE}/firewall/mangle`),
  2721. fetch(`${API_BASE}/firewall/address-lists`),
  2722. fetch(`${API_BASE}/firewall/geoip/status`),
  2723. fetch(`${API_BASE}/firewall/geoip/countries`)
  2724. ]);
  2725. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2726. if (filterRes.ok) state.filterRules = await filterRes.json();
  2727. if (natRes.ok) state.natRules = await natRes.json();
  2728. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2729. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2730. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2731. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2732. // Badges
  2733. const bFilter = document.getElementById('fw-badge-filter');
  2734. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2735. const bNat = document.getElementById('fw-badge-nat');
  2736. if (bNat) bNat.innerText = (state.natRules || []).length;
  2737. const bMangle = document.getElementById('fw-badge-mangle');
  2738. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2739. const bAddr = document.getElementById('fw-badge-addrlist');
  2740. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2741. const bGeo = document.getElementById('fw-badge-geo');
  2742. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2743. renderFilterRules();
  2744. renderNATRules();
  2745. renderMangleRules();
  2746. renderAddressLists();
  2747. renderGeoCountries();
  2748. if (state.fwSubTab === 'connections') {
  2749. loadConnections();
  2750. }
  2751. } catch (err) {
  2752. console.error('Failed to load firewall:', err);
  2753. }
  2754. }
  2755. // ----------------- Filter Rules -----------------
  2756. function renderFilterRules() {
  2757. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2758. const tbody = document.getElementById('filter-table-body');
  2759. const empty = document.getElementById('filter-empty');
  2760. if (!tbody) return;
  2761. tbody.innerHTML = '';
  2762. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2763. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2764. if (rules.length === 0) {
  2765. empty?.classList.remove('hidden');
  2766. return;
  2767. }
  2768. empty?.classList.add('hidden');
  2769. rules.forEach((r, idx) => {
  2770. const tr = document.createElement('tr');
  2771. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2772. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2773. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2774. let actionExtra = '';
  2775. if (r.action === 'reject') {
  2776. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2777. } else if (r.action === 'jump') {
  2778. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2779. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2780. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2781. } else if (r.action === 'log' && r.log_prefix) {
  2782. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2783. }
  2784. tr.innerHTML = `
  2785. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2786. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2787. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2788. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2789. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2790. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2791. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2792. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2793. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2794. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2795. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2796. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2797. </td>
  2798. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2799. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2800. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2801. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2802. <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>
  2803. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2804. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2805. </td>
  2806. `;
  2807. tbody.appendChild(tr);
  2808. });
  2809. }
  2810. function formatTarget(addr, list, geo) {
  2811. const parts = [];
  2812. if (addr) parts.push(`<span>${addr}</span>`);
  2813. if (list) {
  2814. const inv = list.startsWith('!') ? '!' : '';
  2815. const clean = list.replace(/^!/, '');
  2816. 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>`);
  2817. }
  2818. if (geo) {
  2819. const inv = geo.startsWith('!') ? '!' : '';
  2820. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2821. 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>`);
  2822. }
  2823. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2824. return parts.join(' ');
  2825. }
  2826. function populateInterfaceSelect(selectId, currentVal = '') {
  2827. const sel = document.getElementById(selectId);
  2828. if (!sel) return;
  2829. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2830. (state.interfaces || []).forEach(i => {
  2831. const opt = document.createElement('option');
  2832. opt.value = i.name;
  2833. opt.innerText = `${i.name} (${i.role || i.type})`;
  2834. if (i.name === currentVal) opt.selected = true;
  2835. sel.appendChild(opt);
  2836. });
  2837. }
  2838. function populateAddressListSelect(selectId, currentVal = '') {
  2839. const sel = document.getElementById(selectId);
  2840. if (!sel) return;
  2841. sel.innerHTML = '<option value="">(None)</option>';
  2842. const cleanVal = (currentVal || '').replace(/^!/, '');
  2843. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2844. customNames.forEach(name => {
  2845. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2846. const opt = document.createElement('option');
  2847. opt.value = name;
  2848. opt.innerText = `${name} (${count} entries)`;
  2849. if (name === cleanVal) opt.selected = true;
  2850. sel.appendChild(opt);
  2851. });
  2852. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2853. const opt = document.createElement('option');
  2854. opt.value = cleanVal;
  2855. opt.innerText = cleanVal;
  2856. opt.selected = true;
  2857. sel.appendChild(opt);
  2858. }
  2859. populateCommonAddrListDatalist();
  2860. }
  2861. function populateCommonAddrListDatalist() {
  2862. const dl = document.getElementById('fw-addrlist-datalist');
  2863. if (!dl) return;
  2864. dl.innerHTML = '';
  2865. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2866. names.forEach(name => {
  2867. const opt = document.createElement('option');
  2868. opt.value = name;
  2869. dl.appendChild(opt);
  2870. });
  2871. }
  2872. function populateGeoIPSelect(selectId, currentVal = '') {
  2873. const sel = document.getElementById(selectId);
  2874. if (!sel) return;
  2875. sel.innerHTML = '<option value="">(None)</option>';
  2876. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2877. // Presets optgroup
  2878. const grpPresets = document.createElement('optgroup');
  2879. grpPresets.label = '⚡ Regional Presets';
  2880. const presets = [
  2881. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2882. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2883. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2884. ];
  2885. presets.forEach(p => {
  2886. const opt = document.createElement('option');
  2887. opt.value = p.code;
  2888. opt.innerText = p.label;
  2889. if (p.code === cleanVal) opt.selected = true;
  2890. grpPresets.appendChild(opt);
  2891. });
  2892. sel.appendChild(grpPresets);
  2893. // All Countries optgroup
  2894. const grpCountries = document.createElement('optgroup');
  2895. grpCountries.label = '🌍 All Countries';
  2896. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2897. countries.forEach(c => {
  2898. const opt = document.createElement('option');
  2899. opt.value = c.code;
  2900. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2901. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2902. if (c.code === cleanVal) opt.selected = true;
  2903. grpCountries.appendChild(opt);
  2904. });
  2905. sel.appendChild(grpCountries);
  2906. }
  2907. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2908. function switchFwRuleTab(tab) {
  2909. state.activeFwRuleTab = tab;
  2910. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2911. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2912. btn.classList.add('text-slate-400', 'border-transparent');
  2913. });
  2914. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2915. if (activeBtn) {
  2916. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2917. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2918. }
  2919. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2920. const activePane = document.getElementById(`fw-pane-${tab}`);
  2921. if (activePane) activePane.classList.remove('hidden');
  2922. if (tab === 'statistics') {
  2923. startFwStatPolling();
  2924. } else {
  2925. stopFwStatPolling();
  2926. }
  2927. }
  2928. function toggleFwField(fieldKey, expand) {
  2929. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2930. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2931. if (!plusBtn || !fieldBox) return;
  2932. if (expand) {
  2933. plusBtn.classList.add('hidden');
  2934. fieldBox.classList.remove('hidden');
  2935. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2936. if (valInput) valInput.focus();
  2937. } else {
  2938. fieldBox.classList.add('hidden');
  2939. plusBtn.classList.remove('hidden');
  2940. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2941. if (valInput) {
  2942. if (valInput.tagName === 'SELECT') {
  2943. valInput.selectedIndex = 0;
  2944. } else {
  2945. valInput.value = '';
  2946. }
  2947. }
  2948. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2949. if (invInput) invInput.checked = false;
  2950. if (fieldKey === 'cs') {
  2951. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2952. const el = document.getElementById(id);
  2953. if (el) el.checked = false;
  2954. });
  2955. }
  2956. if (fieldKey === 'natstate') {
  2957. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2958. const el = document.getElementById(id);
  2959. if (el) el.checked = false;
  2960. });
  2961. }
  2962. if (fieldKey === 'days') {
  2963. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2964. const el = document.getElementById(`fw-day-${d}`);
  2965. if (el) el.checked = true;
  2966. });
  2967. }
  2968. }
  2969. }
  2970. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2971. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2972. toggleFwField(fieldKey, true);
  2973. let strVal = String(value);
  2974. if (hasInvert) {
  2975. const inv = strVal.startsWith('!');
  2976. if (inv) strVal = strVal.slice(1);
  2977. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2978. if (invEl) invEl.checked = inv;
  2979. }
  2980. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2981. if (valEl) valEl.value = strVal;
  2982. } else {
  2983. toggleFwField(fieldKey, false);
  2984. }
  2985. }
  2986. function getFwFieldVal(fieldKey, hasInvert = false) {
  2987. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2988. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2989. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2990. let v = valEl ? valEl.value.trim() : '';
  2991. if (!v) return '';
  2992. if (hasInvert) {
  2993. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2994. if (invEl && invEl.checked) {
  2995. v = '!' + v.replace(/^!/, '');
  2996. }
  2997. }
  2998. return v;
  2999. }
  3000. function toggleMaximizeFilterModal() {
  3001. const win = document.getElementById('filter-modal-window');
  3002. if (!win) return;
  3003. if (win.classList.contains('max-w-[720px]')) {
  3004. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3005. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3006. } else {
  3007. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3008. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3009. }
  3010. }
  3011. function openAddFilterModal() {
  3012. switchFwRuleTab('general');
  3013. const badge = document.getElementById('fw-modal-badge');
  3014. if (badge) badge.innerText = 'New...';
  3015. document.getElementById('filter-modal-id').value = '';
  3016. document.getElementById('filter-modal-enabled').checked = true;
  3017. document.getElementById('filter-modal-comment').value = '';
  3018. document.getElementById('filter-modal-chain').value = 'forward';
  3019. document.getElementById('filter-modal-action').value = 'accept';
  3020. document.getElementById('filter-modal-log').checked = false;
  3021. populateInterfaceSelect('fw-val-iniface');
  3022. populateInterfaceSelect('fw-val-outiface');
  3023. populateAddressListSelect('fw-val-srclist');
  3024. populateAddressListSelect('fw-val-dstlist');
  3025. populateGeoIPSelect('fw-val-srcgeo');
  3026. populateGeoIPSelect('fw-val-dstgeo');
  3027. const allFieldKeys = [
  3028. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3029. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3030. 'routingmark', 'conntype', 'cs', 'natstate',
  3031. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3032. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3033. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3034. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3035. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3036. ];
  3037. allFieldKeys.forEach(k => toggleFwField(k, false));
  3038. resetCurrentRuleCounters();
  3039. toggleFilterActionFields();
  3040. document.getElementById('filter-modal').classList.remove('hidden');
  3041. }
  3042. function openEditFilterModal(id) {
  3043. const r = (state.filterRules || []).find(rule => rule.id === id);
  3044. if (!r) return;
  3045. switchFwRuleTab('general');
  3046. const badge = document.getElementById('fw-modal-badge');
  3047. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3048. document.getElementById('filter-modal-id').value = r.id;
  3049. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3050. document.getElementById('filter-modal-comment').value = r.comment || '';
  3051. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3052. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3053. document.getElementById('filter-modal-log').checked = !!r.log;
  3054. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3055. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3056. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3057. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3058. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3059. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3060. setFwFieldVal('src', r.src_address, true);
  3061. setFwFieldVal('dst', r.dst_address, true);
  3062. setFwFieldVal('srclist', r.src_address_list, true);
  3063. setFwFieldVal('dstlist', r.dst_address_list, true);
  3064. setFwFieldVal('srcgeo', r.src_geoip, true);
  3065. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3066. if (r.protocol && r.protocol !== 'all') {
  3067. setFwFieldVal('proto', r.protocol, true);
  3068. } else {
  3069. toggleFwField('proto', false);
  3070. }
  3071. setFwFieldVal('sport', r.src_port, true);
  3072. setFwFieldVal('dport', r.dst_port, true);
  3073. setFwFieldVal('anyport', r.any_port, true);
  3074. setFwFieldVal('iniface', r.in_interface, true);
  3075. setFwFieldVal('outiface', r.out_interface, true);
  3076. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3077. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3078. setFwFieldVal('pktmark', r.packet_mark, true);
  3079. setFwFieldVal('connmark', r.connection_mark, true);
  3080. setFwFieldVal('routingmark', r.routing_mark, true);
  3081. setFwFieldVal('conntype', r.connection_type, false);
  3082. const states = r.connection_state || [];
  3083. if (states.length > 0) {
  3084. toggleFwField('cs', true);
  3085. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3086. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3087. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3088. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3089. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3090. } else {
  3091. toggleFwField('cs', false);
  3092. }
  3093. const natStates = r.connection_nat_state || [];
  3094. if (natStates.length > 0) {
  3095. toggleFwField('natstate', true);
  3096. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3097. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3098. } else {
  3099. toggleFwField('natstate', false);
  3100. }
  3101. // Advanced tab fields
  3102. setFwFieldVal('layer7', r.layer7_protocol, false);
  3103. setFwFieldVal('content', r.content, false);
  3104. setFwFieldVal('connbytes', r.connection_bytes, false);
  3105. setFwFieldVal('connrate', r.connection_rate, false);
  3106. setFwFieldVal('pcc', r.pcc, false);
  3107. setFwFieldVal('srcmac', r.src_mac_address, true);
  3108. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3109. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3110. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3111. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3112. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3113. setFwFieldVal('tlshost', r.tls_host, false);
  3114. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3115. setFwFieldVal('priority', r.priority, false);
  3116. setFwFieldVal('dscp', r.dscp, false);
  3117. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3118. if (r.tos) {
  3119. const tosEl = document.getElementById('fw-val-tos');
  3120. if (tosEl) tosEl.value = r.tos;
  3121. }
  3122. setFwFieldVal('pktsize', r.packet_size, false);
  3123. setFwFieldVal('random', r.random, false);
  3124. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3125. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3126. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3127. setFwFieldVal('ttl', r.ttl, false);
  3128. // Extra tab fields
  3129. setFwFieldVal('time', r.time, false);
  3130. if (r.days) {
  3131. toggleFwField('days', true);
  3132. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3133. const chk = document.getElementById(`fw-day-${d}`);
  3134. if (chk) chk.checked = r.days.includes(d);
  3135. });
  3136. } else {
  3137. toggleFwField('days', false);
  3138. }
  3139. setFwFieldVal('limit', r.limit, false);
  3140. setFwFieldVal('dstlimit', r.dst_limit, false);
  3141. setFwFieldVal('psd', r.psd, false);
  3142. // Action fields
  3143. if (r.reject_with) {
  3144. const rwEl = document.getElementById('filter-modal-rejectwith');
  3145. if (rwEl) rwEl.value = r.reject_with;
  3146. }
  3147. if (r.jump_target) {
  3148. const jtEl = document.getElementById('filter-modal-jumptarget');
  3149. if (jtEl) jtEl.value = r.jump_target;
  3150. }
  3151. if (r.address_list) {
  3152. const alEl = document.getElementById('filter-modal-action-addrlist');
  3153. if (alEl) alEl.value = r.address_list;
  3154. }
  3155. if (r.address_list_timeout) {
  3156. const toEl = document.getElementById('filter-modal-action-timeout');
  3157. if (toEl) toEl.value = r.address_list_timeout;
  3158. }
  3159. setFwFieldVal('logprefix', r.log_prefix, false);
  3160. // Statistics
  3161. const bEl = document.getElementById('fw-stat-bytes');
  3162. const pEl = document.getElementById('fw-stat-packets');
  3163. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3164. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3165. state.fwLastBytes = r.bytes || 0;
  3166. state.fwLastPackets = r.packets || 0;
  3167. state.fwLastTimestamp = Date.now();
  3168. state.fwStatRateHistory = new Array(30).fill(0);
  3169. state.fwStatPktHistory = new Array(30).fill(0);
  3170. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3171. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3172. toggleFilterActionFields();
  3173. document.getElementById('filter-modal').classList.remove('hidden');
  3174. }
  3175. function closeFilterModal() {
  3176. stopFwStatPolling();
  3177. document.getElementById('filter-modal').classList.add('hidden');
  3178. }
  3179. function toggleFilterActionFields() {
  3180. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3181. const rejectBox = document.getElementById('filter-action-reject-box');
  3182. const jumpBox = document.getElementById('filter-action-jump-box');
  3183. const addrBox = document.getElementById('filter-action-addrlist-box');
  3184. if (rejectBox) {
  3185. if (act === 'reject') rejectBox.classList.remove('hidden');
  3186. else rejectBox.classList.add('hidden');
  3187. }
  3188. if (jumpBox) {
  3189. if (act === 'jump') jumpBox.classList.remove('hidden');
  3190. else jumpBox.classList.add('hidden');
  3191. }
  3192. if (addrBox) {
  3193. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3194. addrBox.classList.remove('hidden');
  3195. } else {
  3196. addrBox.classList.add('hidden');
  3197. }
  3198. }
  3199. if (act === 'log') {
  3200. const logEl = document.getElementById('filter-modal-log');
  3201. if (logEl) logEl.checked = true;
  3202. toggleFwField('logprefix', true);
  3203. }
  3204. }
  3205. function toggleFwLogPrefix() {
  3206. const isLog = document.getElementById('filter-modal-log')?.checked;
  3207. toggleFwField('logprefix', !!isLog);
  3208. }
  3209. function copyFilterRule() {
  3210. document.getElementById('filter-modal-id').value = '';
  3211. const badge = document.getElementById('fw-modal-badge');
  3212. if (badge) badge.innerText = 'New...';
  3213. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3214. }
  3215. function resetCurrentRuleCounters() {
  3216. state.fwStatRateHistory = new Array(30).fill(0);
  3217. state.fwStatPktHistory = new Array(30).fill(0);
  3218. state.fwLastBytes = 0;
  3219. state.fwLastPackets = 0;
  3220. state.fwLastTimestamp = Date.now();
  3221. const bEl = document.getElementById('fw-stat-bytes');
  3222. const pEl = document.getElementById('fw-stat-packets');
  3223. const rEl = document.getElementById('fw-stat-rate');
  3224. const prEl = document.getElementById('fw-stat-pktrate');
  3225. if (bEl) bEl.value = '0 B';
  3226. if (pEl) pEl.value = '0';
  3227. if (rEl) rEl.value = '0 bps';
  3228. if (prEl) prEl.value = '0 p/s';
  3229. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3230. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3231. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3232. }
  3233. async function resetAllFwCounters() {
  3234. try {
  3235. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3236. if (res.ok) {
  3237. resetCurrentRuleCounters();
  3238. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3239. loadFirewall(false);
  3240. }
  3241. } catch (err) {
  3242. showToast('Error', err.message, 'error');
  3243. }
  3244. }
  3245. async function applyFilterRule(closeAfter = false) {
  3246. const id = document.getElementById('filter-modal-id').value;
  3247. const chain = document.getElementById('filter-modal-chain').value;
  3248. const action = document.getElementById('filter-modal-action').value;
  3249. const comment = document.getElementById('filter-modal-comment').value.trim();
  3250. const enabled = document.getElementById('filter-modal-enabled').checked;
  3251. const src = getFwFieldVal('src', true);
  3252. const dst = getFwFieldVal('dst', true);
  3253. const srclist = getFwFieldVal('srclist', true);
  3254. const dstlist = getFwFieldVal('dstlist', true);
  3255. const srcgeo = getFwFieldVal('srcgeo', true);
  3256. const dstgeo = getFwFieldVal('dstgeo', true);
  3257. const proto = getFwFieldVal('proto', true);
  3258. const sport = getFwFieldVal('sport', true);
  3259. const dport = getFwFieldVal('dport', true);
  3260. const anyport = getFwFieldVal('anyport', true);
  3261. const iniface = getFwFieldVal('iniface', true);
  3262. const outiface = getFwFieldVal('outiface', true);
  3263. const inifacelist = getFwFieldVal('inifacelist', true);
  3264. const outifacelist = getFwFieldVal('outifacelist', true);
  3265. const pktmark = getFwFieldVal('pktmark', true);
  3266. const connmark = getFwFieldVal('connmark', true);
  3267. const routingmark = getFwFieldVal('routingmark', true);
  3268. const conntype = getFwFieldVal('conntype', false);
  3269. const states = [];
  3270. const csBox = document.getElementById('fw-field-cs');
  3271. if (csBox && !csBox.classList.contains('hidden')) {
  3272. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3273. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3274. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3275. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3276. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3277. }
  3278. const natStates = [];
  3279. const natBox = document.getElementById('fw-field-natstate');
  3280. if (natBox && !natBox.classList.contains('hidden')) {
  3281. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3282. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3283. }
  3284. const payload = {
  3285. id,
  3286. chain,
  3287. action,
  3288. protocol: proto || 'all',
  3289. src_address: src,
  3290. dst_address: dst,
  3291. src_port: sport,
  3292. dst_port: dport,
  3293. any_port: anyport,
  3294. in_interface: iniface,
  3295. out_interface: outiface,
  3296. in_interface_list: inifacelist,
  3297. out_interface_list: outifacelist,
  3298. packet_mark: pktmark,
  3299. connection_mark: connmark,
  3300. routing_mark: routingmark,
  3301. connection_type: conntype,
  3302. connection_state: states,
  3303. connection_nat_state: natStates,
  3304. src_address_list: srclist,
  3305. dst_address_list: dstlist,
  3306. src_geoip: srcgeo,
  3307. dst_geoip: dstgeo,
  3308. comment,
  3309. disabled: !enabled,
  3310. // Advanced tab
  3311. layer7_protocol: getFwFieldVal('layer7', false),
  3312. content: getFwFieldVal('content', false),
  3313. connection_bytes: getFwFieldVal('connbytes', false),
  3314. connection_rate: getFwFieldVal('connrate', false),
  3315. pcc: getFwFieldVal('pcc', false),
  3316. src_mac_address: getFwFieldVal('srcmac', true),
  3317. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3318. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3319. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3320. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3321. ipsec_policy: getFwFieldVal('ipsec', false),
  3322. tls_host: getFwFieldVal('tlshost', false),
  3323. ingress_priority: getFwFieldVal('ingresspriority', false),
  3324. priority: getFwFieldVal('priority', false),
  3325. dscp: getFwFieldVal('dscp', false),
  3326. tcp_mss: getFwFieldVal('tcpmss', false),
  3327. tos: document.getElementById('fw-val-tos')?.value || '',
  3328. packet_size: getFwFieldVal('pktsize', false),
  3329. random: getFwFieldVal('random', false),
  3330. tcp_flags: getFwFieldVal('tcpflags', false),
  3331. icmp_options: getFwFieldVal('icmpoptions', false),
  3332. ipv4_options: getFwFieldVal('ipv4options', false),
  3333. ttl: getFwFieldVal('ttl', false),
  3334. // Extra tab
  3335. time: getFwFieldVal('time', false),
  3336. limit: getFwFieldVal('limit', false),
  3337. dst_limit: getFwFieldVal('dstlimit', false),
  3338. psd: getFwFieldVal('psd', false),
  3339. // Action tab
  3340. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3341. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3342. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3343. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3344. log: document.getElementById('filter-modal-log')?.checked || false,
  3345. log_prefix: getFwFieldVal('logprefix', false)
  3346. };
  3347. try {
  3348. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3349. method: 'POST',
  3350. headers: { 'Content-Type': 'application/json' },
  3351. body: JSON.stringify(payload)
  3352. });
  3353. if (res.ok) {
  3354. const data = await res.json();
  3355. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3356. loadFirewall(false);
  3357. if (closeAfter) {
  3358. closeFilterModal();
  3359. } else {
  3360. if (data.id) {
  3361. document.getElementById('filter-modal-id').value = data.id;
  3362. const badge = document.getElementById('fw-modal-badge');
  3363. if (badge) badge.innerText = `#${data.id}`;
  3364. }
  3365. }
  3366. } else {
  3367. const err = await res.json();
  3368. showToast('Error', err.message || 'Failed to save rule', 'error');
  3369. }
  3370. } catch (err) {
  3371. showToast('Error', err.message, 'error');
  3372. }
  3373. }
  3374. function submitSaveFilterRule(e) {
  3375. if (e && e.preventDefault) e.preventDefault();
  3376. return applyFilterRule(true);
  3377. }
  3378. function startFwStatPolling() {
  3379. stopFwStatPolling();
  3380. pollRuleStats();
  3381. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3382. }
  3383. function stopFwStatPolling() {
  3384. if (state.fwStatInterval) {
  3385. clearInterval(state.fwStatInterval);
  3386. state.fwStatInterval = null;
  3387. }
  3388. }
  3389. async function pollRuleStats() {
  3390. const id = document.getElementById('filter-modal-id')?.value;
  3391. if (!id) {
  3392. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3393. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3394. return;
  3395. }
  3396. try {
  3397. const res = await fetch(`${API_BASE}/firewall/filter`);
  3398. if (!res.ok) return;
  3399. const rules = await res.json();
  3400. const r = rules.find(x => x.id === id);
  3401. if (!r) return;
  3402. const now = Date.now();
  3403. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3404. state.fwLastTimestamp = now;
  3405. const curBytes = r.bytes || 0;
  3406. const curPackets = r.packets || 0;
  3407. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3408. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3409. state.fwLastBytes = curBytes;
  3410. state.fwLastPackets = curPackets;
  3411. const rateBps = Math.round((deltaBytes * 8) / dt);
  3412. const ratePkt = Math.round(deltaPkts / dt);
  3413. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3414. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3415. state.fwStatRateHistory.push(rateBps);
  3416. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3417. state.fwStatPktHistory.push(ratePkt);
  3418. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3419. const bEl = document.getElementById('fw-stat-bytes');
  3420. const pEl = document.getElementById('fw-stat-packets');
  3421. const rEl = document.getElementById('fw-stat-rate');
  3422. const prEl = document.getElementById('fw-stat-pktrate');
  3423. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3424. if (pEl) pEl.value = curPackets.toLocaleString();
  3425. if (rEl) rEl.value = formatBps(rateBps);
  3426. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3427. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3428. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3429. } catch (e) {
  3430. console.error('Error polling rule stats', e);
  3431. }
  3432. }
  3433. function formatBps(bps) {
  3434. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3435. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3436. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3437. return bps + ' bps';
  3438. }
  3439. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3440. const svg = document.getElementById(svgId);
  3441. if (!svg) return;
  3442. const w = 500;
  3443. const h = 100;
  3444. const paddingRight = 45;
  3445. const graphWidth = w - paddingRight;
  3446. const maxVal = Math.max(5, ...dataArray);
  3447. const currentVal = dataArray[dataArray.length - 1] || 0;
  3448. const leg = document.getElementById(legendId);
  3449. if (leg) {
  3450. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3451. }
  3452. let gridLines = '';
  3453. for (let i = 0; i <= 5; i++) {
  3454. const y = 8 + (i * (h - 18) / 5);
  3455. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3456. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3457. gridLines += `
  3458. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3459. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3460. `;
  3461. }
  3462. const step = graphWidth / (dataArray.length - 1);
  3463. const points = dataArray.map((val, idx) => {
  3464. const x = idx * step;
  3465. const y = (h - 10) - (val / maxVal) * (h - 20);
  3466. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3467. });
  3468. const polylineStr = points.join(' ');
  3469. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3470. svg.innerHTML = `
  3471. ${gridLines}
  3472. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3473. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3474. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3475. `;
  3476. }
  3477. async function moveFilterRule(id, dir) {
  3478. try {
  3479. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3480. method: 'POST',
  3481. headers: { 'Content-Type': 'application/json' },
  3482. body: JSON.stringify({ direction: dir })
  3483. });
  3484. if (res.ok) loadFirewall(false);
  3485. } catch (err) {
  3486. showToast('Error', err.message, 'error');
  3487. }
  3488. }
  3489. async function toggleFilterRuleState(id, disabled) {
  3490. try {
  3491. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3492. method: 'POST',
  3493. headers: { 'Content-Type': 'application/json' },
  3494. body: JSON.stringify({ disabled })
  3495. });
  3496. if (res.ok) loadFirewall(false);
  3497. } catch (err) {
  3498. showToast('Error', err.message, 'error');
  3499. }
  3500. }
  3501. async function deleteFilterRule(id) {
  3502. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3503. try {
  3504. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3505. if (res.ok) {
  3506. showToast('Deleted', 'Filter rule removed', 'success');
  3507. loadFirewall(false);
  3508. }
  3509. } catch (err) {
  3510. showToast('Error', err.message, 'error');
  3511. }
  3512. }
  3513. // ----------------- NAT Rules -----------------
  3514. function renderNATRules() {
  3515. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3516. const tbody = document.getElementById('nat-table-body');
  3517. const empty = document.getElementById('nat-empty');
  3518. if (!tbody) return;
  3519. tbody.innerHTML = '';
  3520. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3521. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3522. if (rules.length === 0) {
  3523. empty?.classList.remove('hidden');
  3524. return;
  3525. }
  3526. empty?.classList.add('hidden');
  3527. rules.forEach((r, idx) => {
  3528. const tr = document.createElement('tr');
  3529. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3530. let toTarget = '-';
  3531. if (r.action === 'jump') {
  3532. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3533. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3534. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3535. } else if (r.action === 'redirect') {
  3536. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3537. } else if (r.action === 'masquerade') {
  3538. 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>`;
  3539. } else if (r.action === 'log') {
  3540. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3541. } else {
  3542. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3543. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3544. }
  3545. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3546. tr.innerHTML = `
  3547. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3548. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3549. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3550. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3551. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3552. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3553. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3554. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3555. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3556. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3557. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3558. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3559. </td>
  3560. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3561. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3562. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3563. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3564. <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>
  3565. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3566. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3567. </td>
  3568. `;
  3569. tbody.appendChild(tr);
  3570. });
  3571. }
  3572. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3573. function switchNATRuleTab(tab) {
  3574. state.activeNATRuleTab = tab;
  3575. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3576. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3577. btn.classList.add('text-slate-400', 'border-transparent');
  3578. });
  3579. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3580. if (activeBtn) {
  3581. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3582. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3583. }
  3584. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3585. const activePane = document.getElementById(`nat-pane-${tab}`);
  3586. if (activePane) activePane.classList.remove('hidden');
  3587. if (tab === 'statistics') {
  3588. startNATStatPolling();
  3589. } else {
  3590. stopNATStatPolling();
  3591. }
  3592. }
  3593. function toggleNATField(fieldKey, expand) {
  3594. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3595. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3596. if (!plusBtn || !fieldBox) return;
  3597. if (expand) {
  3598. plusBtn.classList.add('hidden');
  3599. fieldBox.classList.remove('hidden');
  3600. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3601. if (valInput) valInput.focus();
  3602. } else {
  3603. fieldBox.classList.add('hidden');
  3604. plusBtn.classList.remove('hidden');
  3605. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3606. if (valInput) {
  3607. if (valInput.tagName === 'SELECT') {
  3608. valInput.selectedIndex = 0;
  3609. } else {
  3610. valInput.value = '';
  3611. }
  3612. }
  3613. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3614. if (invInput) invInput.checked = false;
  3615. if (fieldKey === 'days') {
  3616. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3617. const el = document.getElementById(`nat-day-${d}`);
  3618. if (el) el.checked = true;
  3619. });
  3620. }
  3621. }
  3622. }
  3623. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3624. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3625. toggleNATField(fieldKey, true);
  3626. let strVal = String(value);
  3627. if (hasInvert) {
  3628. const inv = strVal.startsWith('!');
  3629. if (inv) strVal = strVal.slice(1);
  3630. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3631. if (invEl) invEl.checked = inv;
  3632. }
  3633. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3634. if (valEl) valEl.value = strVal;
  3635. } else {
  3636. toggleNATField(fieldKey, false);
  3637. }
  3638. }
  3639. function getNATFieldVal(fieldKey, hasInvert = false) {
  3640. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3641. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3642. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3643. let v = valEl ? valEl.value.trim() : '';
  3644. if (!v) return '';
  3645. if (hasInvert) {
  3646. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3647. if (invEl && invEl.checked) {
  3648. v = '!' + v.replace(/^!/, '');
  3649. }
  3650. }
  3651. return v;
  3652. }
  3653. function toggleMaximizeNATModal() {
  3654. const win = document.getElementById('nat-modal-window');
  3655. if (!win) return;
  3656. if (win.classList.contains('max-w-[720px]')) {
  3657. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3658. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3659. } else {
  3660. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3661. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3662. }
  3663. }
  3664. function handleNATChainChange() {
  3665. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3666. const actSel = document.getElementById('nat-modal-action');
  3667. if (actSel) {
  3668. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3669. actSel.value = 'masquerade';
  3670. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3671. actSel.value = 'dst-nat';
  3672. }
  3673. }
  3674. toggleNATActionFields();
  3675. }
  3676. function toggleNATActionFields() {
  3677. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3678. const rowAddr = document.getElementById('nat-row-toaddr');
  3679. const rowPort = document.getElementById('nat-row-toport');
  3680. const jumpBox = document.getElementById('nat-action-jump-box');
  3681. const addrBox = document.getElementById('nat-action-addrlist-box');
  3682. // Hide all dynamic rows first
  3683. if (rowAddr) rowAddr.classList.add('hidden');
  3684. if (rowPort) rowPort.classList.add('hidden');
  3685. if (jumpBox) jumpBox.classList.add('hidden');
  3686. if (addrBox) addrBox.classList.add('hidden');
  3687. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3688. if (rowAddr) rowAddr.classList.remove('hidden');
  3689. if (rowPort) rowPort.classList.remove('hidden');
  3690. } else if (act === 'redirect' || act === 'masquerade') {
  3691. if (rowPort) rowPort.classList.remove('hidden');
  3692. } else if (act === 'jump') {
  3693. if (jumpBox) jumpBox.classList.remove('hidden');
  3694. } else if (act.includes('address-list') || act.includes('address list')) {
  3695. if (addrBox) addrBox.classList.remove('hidden');
  3696. }
  3697. if (act === 'log') {
  3698. const logEl = document.getElementById('nat-modal-log');
  3699. if (logEl) logEl.checked = true;
  3700. toggleNATField('logprefix', true);
  3701. }
  3702. }
  3703. function toggleNATLogPrefix() {
  3704. const isLog = document.getElementById('nat-modal-log')?.checked;
  3705. toggleNATField('logprefix', !!isLog);
  3706. }
  3707. function openAddNATModal() {
  3708. switchNATRuleTab('general');
  3709. const badge = document.getElementById('nat-modal-badge');
  3710. if (badge) badge.innerText = 'New...';
  3711. document.getElementById('nat-modal-id').value = '';
  3712. document.getElementById('nat-modal-enabled').checked = true;
  3713. document.getElementById('nat-modal-comment').value = '';
  3714. document.getElementById('nat-modal-chain').value = 'srcnat';
  3715. document.getElementById('nat-modal-action').value = 'masquerade';
  3716. document.getElementById('nat-modal-toaddr').value = '';
  3717. document.getElementById('nat-modal-toport').value = '';
  3718. document.getElementById('nat-modal-log').checked = false;
  3719. populateInterfaceSelect('nat-val-iniface');
  3720. populateInterfaceSelect('nat-val-outiface');
  3721. populateAddressListSelect('nat-val-srclist');
  3722. populateAddressListSelect('nat-val-dstlist');
  3723. populateGeoIPSelect('nat-val-srcgeo');
  3724. populateGeoIPSelect('nat-val-dstgeo');
  3725. const allFieldKeys = [
  3726. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3727. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3728. 'routingmark', 'conntype',
  3729. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3730. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3731. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3732. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3733. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3734. ];
  3735. allFieldKeys.forEach(k => toggleNATField(k, false));
  3736. resetCurrentNATRuleCounters();
  3737. toggleNATActionFields();
  3738. document.getElementById('nat-modal').classList.remove('hidden');
  3739. }
  3740. function openEditNATModal(id) {
  3741. const r = (state.natRules || []).find(rule => rule.id === id);
  3742. if (!r) return;
  3743. switchNATRuleTab('general');
  3744. const badge = document.getElementById('nat-modal-badge');
  3745. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3746. document.getElementById('nat-modal-id').value = r.id;
  3747. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3748. document.getElementById('nat-modal-comment').value = r.comment || '';
  3749. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3750. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3751. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3752. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3753. document.getElementById('nat-modal-log').checked = !!r.log;
  3754. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3755. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3756. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3757. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3758. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3759. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3760. setNATFieldVal('src', r.src_address, true);
  3761. setNATFieldVal('dst', r.dst_address, true);
  3762. setNATFieldVal('srclist', r.src_address_list, true);
  3763. setNATFieldVal('dstlist', r.dst_address_list, true);
  3764. setNATFieldVal('srcgeo', r.src_geoip, true);
  3765. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3766. if (r.protocol && r.protocol !== 'all') {
  3767. setNATFieldVal('proto', r.protocol, true);
  3768. } else {
  3769. toggleNATField('proto', false);
  3770. }
  3771. setNATFieldVal('sport', r.src_port, true);
  3772. setNATFieldVal('dport', r.dst_port, true);
  3773. setNATFieldVal('anyport', r.any_port, true);
  3774. setNATFieldVal('iniface', r.in_interface, true);
  3775. setNATFieldVal('outiface', r.out_interface, true);
  3776. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3777. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3778. setNATFieldVal('pktmark', r.packet_mark, true);
  3779. setNATFieldVal('connmark', r.connection_mark, true);
  3780. setNATFieldVal('routingmark', r.routing_mark, true);
  3781. setNATFieldVal('conntype', r.connection_type, false);
  3782. // Advanced tab fields
  3783. setNATFieldVal('layer7', r.layer7_protocol, false);
  3784. setNATFieldVal('content', r.content, false);
  3785. setNATFieldVal('connbytes', r.connection_bytes, false);
  3786. setNATFieldVal('connrate', r.connection_rate, false);
  3787. setNATFieldVal('pcc', r.pcc, false);
  3788. setNATFieldVal('srcmac', r.src_mac_address, true);
  3789. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3790. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3791. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3792. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3793. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3794. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3795. setNATFieldVal('priority', r.priority, false);
  3796. setNATFieldVal('dscp', r.dscp, false);
  3797. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3798. if (r.tos) {
  3799. const tosEl = document.getElementById('nat-val-tos');
  3800. if (tosEl) tosEl.value = r.tos;
  3801. }
  3802. setNATFieldVal('pktsize', r.packet_size, false);
  3803. setNATFieldVal('random', r.random, false);
  3804. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3805. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3806. setNATFieldVal('ttl', r.ttl, false);
  3807. // Extra tab fields
  3808. setNATFieldVal('time', r.time, false);
  3809. if (r.days) {
  3810. toggleNATField('days', true);
  3811. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3812. const chk = document.getElementById(`nat-day-${d}`);
  3813. if (chk) chk.checked = r.days.includes(d);
  3814. });
  3815. } else {
  3816. toggleNATField('days', false);
  3817. }
  3818. setNATFieldVal('limit', r.limit, false);
  3819. setNATFieldVal('dstlimit', r.dst_limit, false);
  3820. setNATFieldVal('psd', r.psd, false);
  3821. // Action fields
  3822. if (r.jump_target) {
  3823. const jtEl = document.getElementById('nat-modal-jumptarget');
  3824. if (jtEl) jtEl.value = r.jump_target;
  3825. }
  3826. if (r.address_list) {
  3827. const alEl = document.getElementById('nat-modal-action-addrlist');
  3828. if (alEl) alEl.value = r.address_list;
  3829. }
  3830. if (r.address_list_timeout) {
  3831. const toEl = document.getElementById('nat-modal-action-timeout');
  3832. if (toEl) toEl.value = r.address_list_timeout;
  3833. }
  3834. setNATFieldVal('logprefix', r.log_prefix, false);
  3835. // Statistics
  3836. const bEl = document.getElementById('nat-stat-bytes');
  3837. const pEl = document.getElementById('nat-stat-packets');
  3838. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3839. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3840. state.natLastBytes = r.bytes || 0;
  3841. state.natLastPackets = r.packets || 0;
  3842. state.natLastTimestamp = Date.now();
  3843. state.natStatRateHistory = new Array(30).fill(0);
  3844. state.natStatPktHistory = new Array(30).fill(0);
  3845. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3846. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3847. toggleNATActionFields();
  3848. document.getElementById('nat-modal').classList.remove('hidden');
  3849. }
  3850. function closeNATModal() {
  3851. stopNATStatPolling();
  3852. document.getElementById('nat-modal').classList.add('hidden');
  3853. }
  3854. function copyNATRule() {
  3855. document.getElementById('nat-modal-id').value = '';
  3856. const badge = document.getElementById('nat-modal-badge');
  3857. if (badge) badge.innerText = 'New...';
  3858. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3859. }
  3860. function resetCurrentNATRuleCounters() {
  3861. state.natStatRateHistory = new Array(30).fill(0);
  3862. state.natStatPktHistory = new Array(30).fill(0);
  3863. state.natLastBytes = 0;
  3864. state.natLastPackets = 0;
  3865. state.natLastTimestamp = Date.now();
  3866. const bEl = document.getElementById('nat-stat-bytes');
  3867. const pEl = document.getElementById('nat-stat-packets');
  3868. const rEl = document.getElementById('nat-stat-rate');
  3869. const prEl = document.getElementById('nat-stat-pktrate');
  3870. if (bEl) bEl.value = '0 B';
  3871. if (pEl) pEl.value = '0';
  3872. if (rEl) rEl.value = '0 bps';
  3873. if (prEl) prEl.value = '0 p/s';
  3874. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3875. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3876. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3877. }
  3878. async function applyNATRule(closeAfter = false) {
  3879. const id = document.getElementById('nat-modal-id').value;
  3880. const chain = document.getElementById('nat-modal-chain').value;
  3881. const action = document.getElementById('nat-modal-action').value;
  3882. const comment = document.getElementById('nat-modal-comment').value.trim();
  3883. const enabled = document.getElementById('nat-modal-enabled').checked;
  3884. const src = getNATFieldVal('src', true);
  3885. const dst = getNATFieldVal('dst', true);
  3886. const srclist = getNATFieldVal('srclist', true);
  3887. const dstlist = getNATFieldVal('dstlist', true);
  3888. const srcgeo = getNATFieldVal('srcgeo', true);
  3889. const dstgeo = getNATFieldVal('dstgeo', true);
  3890. const proto = getNATFieldVal('proto', true);
  3891. const sport = getNATFieldVal('sport', true);
  3892. const dport = getNATFieldVal('dport', true);
  3893. const anyport = getNATFieldVal('anyport', true);
  3894. const iniface = getNATFieldVal('iniface', true);
  3895. const outiface = getNATFieldVal('outiface', true);
  3896. const inifacelist = getNATFieldVal('inifacelist', true);
  3897. const outifacelist = getNATFieldVal('outifacelist', true);
  3898. const pktmark = getNATFieldVal('pktmark', true);
  3899. const connmark = getNATFieldVal('connmark', true);
  3900. const routingmark = getNATFieldVal('routingmark', true);
  3901. const conntype = getNATFieldVal('conntype', false);
  3902. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3903. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3904. const payload = {
  3905. id,
  3906. chain,
  3907. action,
  3908. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3909. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3910. protocol: proto || 'all',
  3911. src_address: src,
  3912. dst_address: dst,
  3913. src_port: sport,
  3914. dst_port: dport,
  3915. any_port: anyport,
  3916. in_interface: iniface,
  3917. out_interface: outiface,
  3918. in_interface_list: inifacelist,
  3919. out_interface_list: outifacelist,
  3920. packet_mark: pktmark,
  3921. connection_mark: connmark,
  3922. routing_mark: routingmark,
  3923. connection_type: conntype,
  3924. src_address_list: srclist,
  3925. dst_address_list: dstlist,
  3926. src_geoip: srcgeo,
  3927. dst_geoip: dstgeo,
  3928. comment,
  3929. disabled: !enabled,
  3930. // Advanced tab
  3931. layer7_protocol: getNATFieldVal('layer7', false),
  3932. content: getNATFieldVal('content', false),
  3933. connection_bytes: getNATFieldVal('connbytes', false),
  3934. connection_rate: getNATFieldVal('connrate', false),
  3935. pcc: getNATFieldVal('pcc', false),
  3936. src_mac_address: getNATFieldVal('srcmac', true),
  3937. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3938. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3939. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3940. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3941. ipsec_policy: getNATFieldVal('ipsec', false),
  3942. ingress_priority: getNATFieldVal('ingresspriority', false),
  3943. priority: getNATFieldVal('priority', false),
  3944. dscp: getNATFieldVal('dscp', false),
  3945. tcp_mss: getNATFieldVal('tcpmss', false),
  3946. tos: document.getElementById('nat-val-tos')?.value || '',
  3947. packet_size: getNATFieldVal('pktsize', false),
  3948. random: getNATFieldVal('random', false),
  3949. icmp_options: getNATFieldVal('icmpoptions', false),
  3950. ipv4_options: getNATFieldVal('ipv4options', false),
  3951. ttl: getNATFieldVal('ttl', false),
  3952. // Extra tab
  3953. time: getNATFieldVal('time', false),
  3954. limit: getNATFieldVal('limit', false),
  3955. dst_limit: getNATFieldVal('dstlimit', false),
  3956. psd: getNATFieldVal('psd', false),
  3957. // Action tab
  3958. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3959. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3960. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3961. log: document.getElementById('nat-modal-log')?.checked || false,
  3962. log_prefix: getNATFieldVal('logprefix', false)
  3963. };
  3964. try {
  3965. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3966. method: 'POST',
  3967. headers: { 'Content-Type': 'application/json' },
  3968. body: JSON.stringify(payload)
  3969. });
  3970. if (res.ok) {
  3971. const data = await res.json();
  3972. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3973. loadFirewall(false);
  3974. if (closeAfter) {
  3975. closeNATModal();
  3976. } else {
  3977. if (data.id) {
  3978. document.getElementById('nat-modal-id').value = data.id;
  3979. const badge = document.getElementById('nat-modal-badge');
  3980. if (badge) badge.innerText = `#${data.id}`;
  3981. }
  3982. }
  3983. } else {
  3984. const err = await res.json();
  3985. showToast('Error', err.message || 'Failed to save rule', 'error');
  3986. }
  3987. } catch (err) {
  3988. showToast('Error', err.message, 'error');
  3989. }
  3990. }
  3991. function submitSaveNATRule(e) {
  3992. if (e && e.preventDefault) e.preventDefault();
  3993. return applyNATRule(true);
  3994. }
  3995. function startNATStatPolling() {
  3996. stopNATStatPolling();
  3997. pollNATRuleStats();
  3998. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3999. }
  4000. function stopNATStatPolling() {
  4001. if (state.natStatInterval) {
  4002. clearInterval(state.natStatInterval);
  4003. state.natStatInterval = null;
  4004. }
  4005. }
  4006. async function pollNATRuleStats() {
  4007. const id = document.getElementById('nat-modal-id')?.value;
  4008. if (!id) {
  4009. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4010. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4011. return;
  4012. }
  4013. try {
  4014. const res = await fetch(`${API_BASE}/firewall/nat`);
  4015. if (!res.ok) return;
  4016. const rules = await res.json();
  4017. const r = rules.find(x => x.id === id);
  4018. if (!r) return;
  4019. const now = Date.now();
  4020. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4021. state.natLastTimestamp = now;
  4022. const curBytes = r.bytes || 0;
  4023. const curPackets = r.packets || 0;
  4024. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4025. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4026. state.natLastBytes = curBytes;
  4027. state.natLastPackets = curPackets;
  4028. const rateBps = Math.round((deltaBytes * 8) / dt);
  4029. const ratePkt = Math.round(deltaPkts / dt);
  4030. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4031. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4032. state.natStatRateHistory.push(rateBps);
  4033. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4034. state.natStatPktHistory.push(ratePkt);
  4035. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4036. const bEl = document.getElementById('nat-stat-bytes');
  4037. const pEl = document.getElementById('nat-stat-packets');
  4038. const rEl = document.getElementById('nat-stat-rate');
  4039. const prEl = document.getElementById('nat-stat-pktrate');
  4040. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4041. if (pEl) pEl.value = curPackets.toLocaleString();
  4042. if (rEl) rEl.value = formatBps(rateBps);
  4043. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4044. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4045. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4046. } catch (e) {
  4047. console.error('Error polling NAT rule stats', e);
  4048. }
  4049. }
  4050. async function moveNATRule(id, dir) {
  4051. try {
  4052. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4053. method: 'POST',
  4054. headers: { 'Content-Type': 'application/json' },
  4055. body: JSON.stringify({ direction: dir })
  4056. });
  4057. if (res.ok) loadFirewall(false);
  4058. } catch (err) {
  4059. showToast('Error', err.message, 'error');
  4060. }
  4061. }
  4062. async function toggleNATRuleState(id, disabled) {
  4063. try {
  4064. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4065. method: 'POST',
  4066. headers: { 'Content-Type': 'application/json' },
  4067. body: JSON.stringify({ disabled })
  4068. });
  4069. if (res.ok) loadFirewall(false);
  4070. } catch (err) {
  4071. showToast('Error', err.message, 'error');
  4072. }
  4073. }
  4074. async function deleteNATRule(id) {
  4075. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4076. try {
  4077. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4078. if (res.ok) {
  4079. showToast('Deleted', 'NAT rule removed', 'success');
  4080. loadFirewall(false);
  4081. }
  4082. } catch (err) {
  4083. showToast('Error', err.message, 'error');
  4084. }
  4085. }
  4086. // ----------------- Mangle Rules -----------------
  4087. function renderMangleRules() {
  4088. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4089. const tbody = document.getElementById('mangle-table-body');
  4090. const empty = document.getElementById('mangle-empty');
  4091. if (!tbody) return;
  4092. tbody.innerHTML = '';
  4093. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4094. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4095. if (rules.length === 0) {
  4096. empty?.classList.remove('hidden');
  4097. return;
  4098. }
  4099. empty?.classList.add('hidden');
  4100. rules.forEach((r, idx) => {
  4101. const tr = document.createElement('tr');
  4102. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4103. let markVal = '<span class="text-slate-500">-</span>';
  4104. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4105. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4106. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4107. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4108. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4109. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4110. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4111. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4112. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4113. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4114. 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>`;
  4115. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4116. tr.innerHTML = `
  4117. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4118. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4119. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4120. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4121. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4122. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4123. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4124. <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>
  4125. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4126. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4127. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4128. </td>
  4129. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4130. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4131. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4132. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4133. <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>
  4134. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4135. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4136. </td>
  4137. `;
  4138. tbody.appendChild(tr);
  4139. });
  4140. }
  4141. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4142. function switchMangleRuleTab(tab) {
  4143. state.activeMangleRuleTab = tab;
  4144. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4145. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4146. btn.classList.add('text-slate-400', 'border-transparent');
  4147. });
  4148. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4149. if (activeBtn) {
  4150. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4151. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4152. }
  4153. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4154. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4155. if (activePane) activePane.classList.remove('hidden');
  4156. if (tab === 'statistics') {
  4157. startMangleStatPolling();
  4158. } else {
  4159. stopMangleStatPolling();
  4160. }
  4161. }
  4162. function toggleMangleField(fieldKey, expand) {
  4163. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4164. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4165. if (!plusBtn || !fieldBox) return;
  4166. if (expand) {
  4167. plusBtn.classList.add('hidden');
  4168. fieldBox.classList.remove('hidden');
  4169. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4170. if (valInput) valInput.focus();
  4171. } else {
  4172. fieldBox.classList.add('hidden');
  4173. plusBtn.classList.remove('hidden');
  4174. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4175. if (valInput) {
  4176. if (valInput.tagName === 'SELECT') {
  4177. valInput.selectedIndex = 0;
  4178. } else {
  4179. valInput.value = '';
  4180. }
  4181. }
  4182. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4183. if (invInput) invInput.checked = false;
  4184. if (fieldKey === 'cs') {
  4185. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4186. const el = document.getElementById(id);
  4187. if (el) el.checked = false;
  4188. });
  4189. }
  4190. if (fieldKey === 'natstate') {
  4191. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4192. const el = document.getElementById(id);
  4193. if (el) el.checked = false;
  4194. });
  4195. }
  4196. }
  4197. }
  4198. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4199. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4200. toggleMangleField(fieldKey, true);
  4201. let strVal = String(value);
  4202. if (hasInvert) {
  4203. const inv = strVal.startsWith('!');
  4204. if (inv) strVal = strVal.slice(1);
  4205. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4206. if (invEl) invEl.checked = inv;
  4207. }
  4208. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4209. if (valEl) valEl.value = strVal;
  4210. } else {
  4211. toggleMangleField(fieldKey, false);
  4212. }
  4213. }
  4214. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4215. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4216. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4217. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4218. let v = valEl ? valEl.value.trim() : '';
  4219. if (!v) return '';
  4220. if (hasInvert) {
  4221. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4222. if (invEl && invEl.checked) {
  4223. v = '!' + v.replace(/^!/, '');
  4224. }
  4225. }
  4226. return v;
  4227. }
  4228. function toggleMaximizeMangleModal() {
  4229. const win = document.getElementById('mangle-modal-window');
  4230. if (!win) return;
  4231. if (win.classList.contains('max-w-[720px]')) {
  4232. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4233. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4234. } else {
  4235. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4236. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4237. }
  4238. }
  4239. function toggleMangleActionFields() {
  4240. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4241. // Hide all dynamic rows first
  4242. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4243. const el = document.getElementById(`mangle-row-${id}`);
  4244. if (el) el.classList.add('hidden');
  4245. });
  4246. const jumpBox = document.getElementById('mangle-action-jump-box');
  4247. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4248. if (jumpBox) jumpBox.classList.add('hidden');
  4249. if (addrBox) addrBox.classList.add('hidden');
  4250. // Activate matching rows
  4251. if (act === 'mark-connection') {
  4252. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4253. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4254. } else if (act === 'mark-routing') {
  4255. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4256. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4257. } else if (act === 'mark-packet') {
  4258. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4259. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4260. } else if (act === 'change-mss') {
  4261. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4262. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4263. } else if (act === 'change-dscp') {
  4264. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4265. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4266. } else if (act === 'change-ttl') {
  4267. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4268. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4269. } else if (act === 'set-priority') {
  4270. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4271. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4272. } else if (act === 'route') {
  4273. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4274. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4275. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4276. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4277. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4278. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4279. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4280. } else if (act === 'jump') {
  4281. if (jumpBox) jumpBox.classList.remove('hidden');
  4282. } else if (act.includes('address-list') || act.includes('address list')) {
  4283. if (addrBox) addrBox.classList.remove('hidden');
  4284. }
  4285. if (act === 'log') {
  4286. const logEl = document.getElementById('mangle-modal-log');
  4287. if (logEl) logEl.checked = true;
  4288. toggleMangleField('logprefix', true);
  4289. }
  4290. }
  4291. function toggleMangleLogPrefix() {
  4292. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4293. toggleMangleField('logprefix', !!isLog);
  4294. }
  4295. const allMangleFieldKeys = [
  4296. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4297. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4298. 'routingmark', 'conntype', 'cs', 'natstate',
  4299. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4300. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4301. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4302. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4303. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4304. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4305. ];
  4306. function openAddMangleModal() {
  4307. switchMangleRuleTab('general');
  4308. const badge = document.getElementById('mangle-modal-badge');
  4309. if (badge) badge.innerText = 'New...';
  4310. document.getElementById('mangle-modal-id').value = '';
  4311. document.getElementById('mangle-modal-enabled').checked = true;
  4312. document.getElementById('mangle-modal-comment').value = '';
  4313. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4314. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4315. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4316. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4317. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4318. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4319. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4320. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4321. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4322. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4323. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4324. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4325. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4326. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4327. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4328. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4329. populateInterfaceSelect('mangle-val-iniface');
  4330. populateInterfaceSelect('mangle-val-outiface');
  4331. populateAddressListSelect('mangle-val-srclist');
  4332. populateAddressListSelect('mangle-val-dstlist');
  4333. populateGeoIPSelect('mangle-val-srcgeo');
  4334. populateGeoIPSelect('mangle-val-dstgeo');
  4335. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4336. resetCurrentMangleRuleCounters();
  4337. toggleMangleActionFields();
  4338. document.getElementById('mangle-modal').classList.remove('hidden');
  4339. }
  4340. function openEditMangleModal(id) {
  4341. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4342. if (!r) return;
  4343. switchMangleRuleTab('general');
  4344. const badge = document.getElementById('mangle-modal-badge');
  4345. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4346. document.getElementById('mangle-modal-id').value = r.id;
  4347. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4348. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4349. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4350. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4351. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4352. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4353. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4354. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4355. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4356. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4357. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4358. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4359. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4360. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4361. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4362. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4363. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4364. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4365. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4366. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4367. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4368. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4369. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4370. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4371. setMangleFieldVal('src', r.src_address, true);
  4372. setMangleFieldVal('dst', r.dst_address, true);
  4373. setMangleFieldVal('srclist', r.src_address_list, true);
  4374. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4375. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4376. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4377. if (r.protocol && r.protocol !== 'all') {
  4378. setMangleFieldVal('proto', r.protocol, true);
  4379. } else {
  4380. toggleMangleField('proto', false);
  4381. }
  4382. setMangleFieldVal('sport', r.src_port, true);
  4383. setMangleFieldVal('dport', r.dst_port, true);
  4384. setMangleFieldVal('anyport', r.any_port, true);
  4385. setMangleFieldVal('iniface', r.in_interface, true);
  4386. setMangleFieldVal('outiface', r.out_interface, true);
  4387. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4388. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4389. setMangleFieldVal('pktmark', r.packet_mark, true);
  4390. setMangleFieldVal('connmark', r.connection_mark, true);
  4391. setMangleFieldVal('routingmark', r.routing_mark, true);
  4392. setMangleFieldVal('conntype', r.connection_type, false);
  4393. // Connection State
  4394. const states = r.connection_state || [];
  4395. if (states.length > 0) {
  4396. toggleMangleField('cs', true);
  4397. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4398. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4399. if (el) el.checked = states.includes(s);
  4400. });
  4401. } else {
  4402. toggleMangleField('cs', false);
  4403. }
  4404. // Connection NAT State
  4405. const natStates = r.connection_nat_state || [];
  4406. if (natStates.length > 0) {
  4407. toggleMangleField('natstate', true);
  4408. ['srcnat', 'dstnat'].forEach(s => {
  4409. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4410. if (el) el.checked = natStates.includes(s);
  4411. });
  4412. } else {
  4413. toggleMangleField('natstate', false);
  4414. }
  4415. // Advanced tab fields
  4416. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4417. setMangleFieldVal('content', r.content, false);
  4418. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4419. setMangleFieldVal('connrate', r.connection_rate, false);
  4420. setMangleFieldVal('pcc', r.pcc, false);
  4421. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4422. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4423. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4424. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4425. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4426. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4427. setMangleFieldVal('tlshost', r.tls_host, false);
  4428. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4429. setMangleFieldVal('priority', r.priority, false);
  4430. setMangleFieldVal('dscp', r.dscp, false);
  4431. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4432. if (r.tos) {
  4433. const tosEl = document.getElementById('mangle-val-tos');
  4434. if (tosEl) tosEl.value = r.tos;
  4435. }
  4436. setMangleFieldVal('pktsize', r.packet_size, false);
  4437. setMangleFieldVal('random', r.random, false);
  4438. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4439. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4440. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4441. setMangleFieldVal('ttl', r.ttl, false);
  4442. // Extra tab fields
  4443. setMangleFieldVal('nth', r.nth, false);
  4444. setMangleFieldVal('connlimit', r.connection_limit, false);
  4445. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4446. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4447. setMangleFieldVal('hotspot', r.hotspot, false);
  4448. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4449. setMangleFieldVal('limit', r.limit, false);
  4450. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4451. setMangleFieldVal('time', r.time, false);
  4452. setMangleFieldVal('psd', r.psd, false);
  4453. // Action fields
  4454. if (r.jump_target) {
  4455. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4456. if (jtEl) jtEl.value = r.jump_target;
  4457. }
  4458. if (r.address_list) {
  4459. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4460. if (alEl) alEl.value = r.address_list;
  4461. }
  4462. if (r.address_list_timeout) {
  4463. const toEl = document.getElementById('mangle-modal-action-timeout');
  4464. if (toEl) toEl.value = r.address_list_timeout;
  4465. }
  4466. setMangleFieldVal('logprefix', r.log_prefix, false);
  4467. // Statistics
  4468. const bEl = document.getElementById('mangle-stat-bytes');
  4469. const pEl = document.getElementById('mangle-stat-packets');
  4470. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4471. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4472. state.mangleLastBytes = r.bytes || 0;
  4473. state.mangleLastPackets = r.packets || 0;
  4474. state.mangleLastTimestamp = Date.now();
  4475. state.mangleStatRateHistory = new Array(30).fill(0);
  4476. state.mangleStatPktHistory = new Array(30).fill(0);
  4477. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4478. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4479. toggleMangleActionFields();
  4480. document.getElementById('mangle-modal').classList.remove('hidden');
  4481. }
  4482. function closeMangleModal() {
  4483. stopMangleStatPolling();
  4484. document.getElementById('mangle-modal').classList.add('hidden');
  4485. }
  4486. function copyMangleRule() {
  4487. document.getElementById('mangle-modal-id').value = '';
  4488. const badge = document.getElementById('mangle-modal-badge');
  4489. if (badge) badge.innerText = 'New...';
  4490. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4491. }
  4492. function resetCurrentMangleRuleCounters() {
  4493. state.mangleStatRateHistory = new Array(30).fill(0);
  4494. state.mangleStatPktHistory = new Array(30).fill(0);
  4495. state.mangleLastBytes = 0;
  4496. state.mangleLastPackets = 0;
  4497. state.mangleLastTimestamp = Date.now();
  4498. const bEl = document.getElementById('mangle-stat-bytes');
  4499. const pEl = document.getElementById('mangle-stat-packets');
  4500. const rEl = document.getElementById('mangle-stat-rate');
  4501. const prEl = document.getElementById('mangle-stat-pktrate');
  4502. if (bEl) bEl.value = '0 B';
  4503. if (pEl) pEl.value = '0';
  4504. if (rEl) rEl.value = '0 bps';
  4505. if (prEl) prEl.value = '0 p/s';
  4506. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4507. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4508. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4509. }
  4510. async function applyMangleRule(closeAfter = false) {
  4511. const id = document.getElementById('mangle-modal-id').value;
  4512. const chain = document.getElementById('mangle-modal-chain').value;
  4513. const action = document.getElementById('mangle-modal-action').value;
  4514. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4515. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4516. const src = getMangleFieldVal('src', true);
  4517. const dst = getMangleFieldVal('dst', true);
  4518. const srclist = getMangleFieldVal('srclist', true);
  4519. const dstlist = getMangleFieldVal('dstlist', true);
  4520. const srcgeo = getMangleFieldVal('srcgeo', true);
  4521. const dstgeo = getMangleFieldVal('dstgeo', true);
  4522. const proto = getMangleFieldVal('proto', true);
  4523. const sport = getMangleFieldVal('sport', true);
  4524. const dport = getMangleFieldVal('dport', true);
  4525. const anyport = getMangleFieldVal('anyport', true);
  4526. const iniface = getMangleFieldVal('iniface', true);
  4527. const outiface = getMangleFieldVal('outiface', true);
  4528. const inifacelist = getMangleFieldVal('inifacelist', true);
  4529. const outifacelist = getMangleFieldVal('outifacelist', true);
  4530. const pktmark = getMangleFieldVal('pktmark', true);
  4531. const connmark = getMangleFieldVal('connmark', true);
  4532. const routingmark = getMangleFieldVal('routingmark', true);
  4533. const conntype = getMangleFieldVal('conntype', false);
  4534. const states = [];
  4535. const csBox = document.getElementById('mangle-field-cs');
  4536. if (csBox && !csBox.classList.contains('hidden')) {
  4537. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4538. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4539. });
  4540. }
  4541. const natStates = [];
  4542. const natBox = document.getElementById('mangle-field-natstate');
  4543. if (natBox && !natBox.classList.contains('hidden')) {
  4544. ['srcnat', 'dstnat'].forEach(s => {
  4545. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4546. });
  4547. }
  4548. const payload = {
  4549. id,
  4550. chain,
  4551. action,
  4552. protocol: proto || 'all',
  4553. src_address: src,
  4554. dst_address: dst,
  4555. src_port: sport,
  4556. dst_port: dport,
  4557. any_port: anyport,
  4558. in_interface: iniface,
  4559. out_interface: outiface,
  4560. in_interface_list: inifacelist,
  4561. out_interface_list: outifacelist,
  4562. packet_mark: pktmark,
  4563. connection_mark: connmark,
  4564. routing_mark: routingmark,
  4565. connection_type: conntype,
  4566. connection_state: states,
  4567. connection_nat_state: natStates,
  4568. src_address_list: srclist,
  4569. dst_address_list: dstlist,
  4570. src_geoip: srcgeo,
  4571. dst_geoip: dstgeo,
  4572. comment,
  4573. disabled: !enabled,
  4574. // Advanced tab
  4575. layer7_protocol: getMangleFieldVal('layer7', false),
  4576. content: getMangleFieldVal('content', false),
  4577. connection_bytes: getMangleFieldVal('connbytes', false),
  4578. connection_rate: getMangleFieldVal('connrate', false),
  4579. pcc: getMangleFieldVal('pcc', false),
  4580. src_mac_address: getMangleFieldVal('srcmac', true),
  4581. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4582. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4583. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4584. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4585. ipsec_policy: getMangleFieldVal('ipsec', false),
  4586. tls_host: getMangleFieldVal('tlshost', false),
  4587. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4588. priority: getMangleFieldVal('priority', false),
  4589. dscp: getMangleFieldVal('dscp', false),
  4590. tcp_mss: getMangleFieldVal('tcpmss', false),
  4591. tos: document.getElementById('mangle-val-tos')?.value || '',
  4592. packet_size: getMangleFieldVal('pktsize', false),
  4593. random: getMangleFieldVal('random', false),
  4594. tcp_flags: getMangleFieldVal('tcpflags', false),
  4595. icmp_options: getMangleFieldVal('icmpoptions', false),
  4596. ipv4_options: getMangleFieldVal('ipv4options', false),
  4597. ttl: getMangleFieldVal('ttl', false),
  4598. // Extra tab
  4599. nth: getMangleFieldVal('nth', false),
  4600. connection_limit: getMangleFieldVal('connlimit', false),
  4601. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4602. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4603. hotspot: getMangleFieldVal('hotspot', false),
  4604. ip_fragment: getMangleFieldVal('ipfragment', false),
  4605. limit: getMangleFieldVal('limit', false),
  4606. dst_limit: getMangleFieldVal('dstlimit', false),
  4607. time: getMangleFieldVal('time', false),
  4608. psd: getMangleFieldVal('psd', false),
  4609. // Action tab
  4610. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4611. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4612. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4613. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4614. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4615. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4616. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4617. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4618. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4619. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4620. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4621. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4622. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4623. log: document.getElementById('mangle-modal-log')?.checked || false,
  4624. log_prefix: getMangleFieldVal('logprefix', false)
  4625. };
  4626. try {
  4627. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4628. method: 'POST',
  4629. headers: { 'Content-Type': 'application/json' },
  4630. body: JSON.stringify(payload)
  4631. });
  4632. if (res.ok) {
  4633. const data = await res.json();
  4634. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4635. loadFirewall(false);
  4636. if (closeAfter) {
  4637. closeMangleModal();
  4638. } else {
  4639. if (data.id) {
  4640. document.getElementById('mangle-modal-id').value = data.id;
  4641. const badge = document.getElementById('mangle-modal-badge');
  4642. if (badge) badge.innerText = `#${data.id}`;
  4643. }
  4644. }
  4645. } else {
  4646. const err = await res.json();
  4647. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4648. }
  4649. } catch (err) {
  4650. showToast('Error', err.message, 'error');
  4651. }
  4652. }
  4653. function submitSaveMangleRule(e) {
  4654. if (e && e.preventDefault) e.preventDefault();
  4655. return applyMangleRule(true);
  4656. }
  4657. function startMangleStatPolling() {
  4658. stopMangleStatPolling();
  4659. pollMangleRuleStats();
  4660. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4661. }
  4662. function stopMangleStatPolling() {
  4663. if (state.mangleStatInterval) {
  4664. clearInterval(state.mangleStatInterval);
  4665. state.mangleStatInterval = null;
  4666. }
  4667. }
  4668. async function pollMangleRuleStats() {
  4669. const id = document.getElementById('mangle-modal-id')?.value;
  4670. if (!id) {
  4671. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4672. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4673. return;
  4674. }
  4675. try {
  4676. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4677. if (!res.ok) return;
  4678. const rules = await res.json();
  4679. const r = rules.find(x => x.id === id);
  4680. if (!r) return;
  4681. const now = Date.now();
  4682. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4683. state.mangleLastTimestamp = now;
  4684. const curBytes = r.bytes || 0;
  4685. const curPackets = r.packets || 0;
  4686. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4687. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4688. state.mangleLastBytes = curBytes;
  4689. state.mangleLastPackets = curPackets;
  4690. const rateBps = Math.round((deltaBytes * 8) / dt);
  4691. const ratePkt = Math.round(deltaPkts / dt);
  4692. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4693. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4694. state.mangleStatRateHistory.push(rateBps);
  4695. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4696. state.mangleStatPktHistory.push(ratePkt);
  4697. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4698. const bEl = document.getElementById('mangle-stat-bytes');
  4699. const pEl = document.getElementById('mangle-stat-packets');
  4700. const rEl = document.getElementById('mangle-stat-rate');
  4701. const prEl = document.getElementById('mangle-stat-pktrate');
  4702. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4703. if (pEl) pEl.value = curPackets.toLocaleString();
  4704. if (rEl) rEl.value = formatBps(rateBps);
  4705. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4706. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4707. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4708. } catch (e) {
  4709. console.error('Error polling Mangle rule stats', e);
  4710. }
  4711. }
  4712. async function moveMangleRule(id, dir) {
  4713. try {
  4714. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4715. method: 'POST',
  4716. headers: { 'Content-Type': 'application/json' },
  4717. body: JSON.stringify({ direction: dir })
  4718. });
  4719. if (res.ok) loadFirewall(false);
  4720. } catch (err) {
  4721. showToast('Error', err.message, 'error');
  4722. }
  4723. }
  4724. async function toggleMangleRuleState(id, disabled) {
  4725. try {
  4726. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4727. method: 'POST',
  4728. headers: { 'Content-Type': 'application/json' },
  4729. body: JSON.stringify({ disabled })
  4730. });
  4731. if (res.ok) loadFirewall(false);
  4732. } catch (err) {
  4733. showToast('Error', err.message, 'error');
  4734. }
  4735. }
  4736. async function deleteMangleRule(id) {
  4737. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4738. try {
  4739. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4740. if (res.ok) {
  4741. showToast('Deleted', 'Mangle rule removed', 'success');
  4742. loadFirewall(false);
  4743. }
  4744. } catch (err) {
  4745. showToast('Error', err.message, 'error');
  4746. }
  4747. }
  4748. // ----------------- Address Lists -----------------
  4749. function renderAddressLists() {
  4750. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4751. const tbody = document.getElementById('addrlist-table-body');
  4752. const empty = document.getElementById('addrlist-empty');
  4753. if (!tbody) return;
  4754. tbody.innerHTML = '';
  4755. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4756. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4757. // Update filter select
  4758. const sel = document.getElementById('addrlist-filter-name');
  4759. if (sel) {
  4760. const cur = sel.value;
  4761. sel.innerHTML = '<option value="">All Lists</option>';
  4762. const set = new Set((state.addressLists || []).map(a => a.name));
  4763. set.forEach(n => {
  4764. const opt = document.createElement('option');
  4765. opt.value = n;
  4766. opt.innerText = n;
  4767. if (n === cur) opt.selected = true;
  4768. sel.appendChild(opt);
  4769. });
  4770. }
  4771. if (entries.length === 0) {
  4772. empty?.classList.remove('hidden');
  4773. return;
  4774. }
  4775. empty?.classList.add('hidden');
  4776. entries.forEach((e, idx) => {
  4777. const tr = document.createElement('tr');
  4778. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4779. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4780. tr.innerHTML = `
  4781. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4782. <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>
  4783. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4784. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4785. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4786. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4787. <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>
  4788. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4789. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4790. </td>
  4791. `;
  4792. tbody.appendChild(tr);
  4793. });
  4794. populateCommonAddrListDatalist();
  4795. }
  4796. function openAddAddrListModal() {
  4797. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4798. document.getElementById('addrlist-modal-id').value = '';
  4799. document.getElementById('addrlist-modal-name').value = '';
  4800. document.getElementById('addrlist-modal-addr').value = '';
  4801. document.getElementById('addrlist-modal-comment').value = '';
  4802. document.getElementById('addrlist-modal-disabled').checked = false;
  4803. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4804. if (submitBtn) submitBtn.innerText = 'Add to List';
  4805. document.getElementById('addrlist-modal').classList.remove('hidden');
  4806. }
  4807. function openEditAddrListModal(id) {
  4808. const e = (state.addressLists || []).find(item => item.id === id);
  4809. if (!e) return;
  4810. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4811. document.getElementById('addrlist-modal-id').value = e.id;
  4812. document.getElementById('addrlist-modal-name').value = e.name;
  4813. document.getElementById('addrlist-modal-addr').value = e.address;
  4814. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4815. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4816. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4817. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4818. document.getElementById('addrlist-modal').classList.remove('hidden');
  4819. }
  4820. function closeAddrListModal() {
  4821. document.getElementById('addrlist-modal').classList.add('hidden');
  4822. }
  4823. async function submitSaveAddrList(e) {
  4824. e.preventDefault();
  4825. const id = document.getElementById('addrlist-modal-id').value;
  4826. const name = document.getElementById('addrlist-modal-name').value.trim();
  4827. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4828. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4829. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4830. try {
  4831. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4832. method: 'POST',
  4833. headers: { 'Content-Type': 'application/json' },
  4834. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4835. });
  4836. if (res.ok) {
  4837. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4838. closeAddrListModal();
  4839. loadFirewall(false);
  4840. } else {
  4841. const err = await res.json();
  4842. showToast('Error', err.message || 'Failed to save address list', 'error');
  4843. }
  4844. } catch (err) {
  4845. showToast('Error', err.message, 'error');
  4846. }
  4847. }
  4848. async function toggleAddrListState(id, disabled) {
  4849. try {
  4850. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4851. method: 'POST',
  4852. headers: { 'Content-Type': 'application/json' },
  4853. body: JSON.stringify({ disabled })
  4854. });
  4855. if (res.ok) {
  4856. loadFirewall(false);
  4857. }
  4858. } catch (err) {
  4859. showToast('Error', err.message, 'error');
  4860. }
  4861. }
  4862. async function deleteAddrList(id) {
  4863. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4864. try {
  4865. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4866. if (res.ok) {
  4867. showToast('Deleted', 'Address list item removed', 'info');
  4868. loadFirewall(false);
  4869. }
  4870. } catch (err) {
  4871. showToast('Error', err.message, 'error');
  4872. }
  4873. }
  4874. // ----------------- Geo-Location IP Management -----------------
  4875. async function loadGeoIP() {
  4876. try {
  4877. const [statusRes, countriesRes] = await Promise.all([
  4878. fetch(`${API_BASE}/firewall/geoip/status`),
  4879. fetch(`${API_BASE}/firewall/geoip/countries`)
  4880. ]);
  4881. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4882. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4883. updateGeoHeader();
  4884. renderGeoCountries();
  4885. } catch (err) {
  4886. console.error('Failed to load GeoIP:', err);
  4887. }
  4888. }
  4889. function getGeoUsageMap() {
  4890. const usage = {};
  4891. const checkRule = (r, type) => {
  4892. ['src_geoip', 'dst_geoip'].forEach(field => {
  4893. let val = (r && r[field]) || '';
  4894. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4895. if (code) {
  4896. if (!usage[code]) usage[code] = [];
  4897. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4898. if (!usage[code].includes(label)) usage[code].push(label);
  4899. }
  4900. });
  4901. };
  4902. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4903. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4904. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4905. return usage;
  4906. }
  4907. function updateGeoHeader() {
  4908. const s = state.geoStatus || {};
  4909. const statusBadge = document.getElementById('geo-status-badge');
  4910. if (statusBadge) {
  4911. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4912. statusBadge.className = s.auto_update
  4913. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4914. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4915. }
  4916. const intervalLabel = document.getElementById('geo-interval-label');
  4917. if (intervalLabel) {
  4918. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4919. }
  4920. const usageMap = getGeoUsageMap();
  4921. const inUseCount = Object.keys(usageMap).length;
  4922. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4923. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4924. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4925. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4926. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4927. if (lastSyncEl) {
  4928. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4929. const d = new Date(s.last_updated);
  4930. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4931. } else {
  4932. lastSyncEl.innerText = 'Never (Sync Pending)';
  4933. }
  4934. }
  4935. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4936. if (nextSyncEl) {
  4937. if (s.next_update && !s.next_update.startsWith('0001')) {
  4938. const d = new Date(s.next_update);
  4939. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4940. } else {
  4941. nextSyncEl.innerText = '-';
  4942. }
  4943. }
  4944. const badge = document.getElementById('fw-badge-geo');
  4945. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4946. }
  4947. function renderGeoCountries() {
  4948. const tbody = document.getElementById('geo-table-body');
  4949. const empty = document.getElementById('geo-empty');
  4950. if (!tbody) return;
  4951. tbody.innerHTML = '';
  4952. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4953. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4954. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4955. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4956. const usageMap = getGeoUsageMap();
  4957. const countries = (state.geoCountries || []).filter(c => {
  4958. const isUsed = !!usageMap[c.code];
  4959. if (inUseOnly && !isUsed) return false;
  4960. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4961. if (continent && c.continent !== continent) return false;
  4962. if (q) {
  4963. const matchCode = c.code.toLowerCase().includes(q);
  4964. const matchName = c.name.toLowerCase().includes(q);
  4965. if (!matchCode && !matchName) return false;
  4966. }
  4967. return true;
  4968. });
  4969. if (countries.length === 0) {
  4970. empty?.classList.remove('hidden');
  4971. return;
  4972. }
  4973. empty?.classList.add('hidden');
  4974. countries.forEach(c => {
  4975. const tr = document.createElement('tr');
  4976. const isUsed = !!usageMap[c.code];
  4977. const rulesUsing = usageMap[c.code] || [];
  4978. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4979. let statusHtml = '';
  4980. if (isUsed) {
  4981. 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>`;
  4982. } else if (c.subnet_count > 0) {
  4983. 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>';
  4984. } else {
  4985. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4986. }
  4987. tr.innerHTML = `
  4988. <td class="py-2.5 px-3 text-center">
  4989. <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'}">
  4990. ${c.code}
  4991. </span>
  4992. </td>
  4993. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4994. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4995. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4996. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4997. </td>
  4998. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4999. <td class="py-2.5 px-3">
  5000. ${statusHtml}
  5001. </td>
  5002. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5003. <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>
  5004. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5005. </td>
  5006. `;
  5007. tbody.appendChild(tr);
  5008. });
  5009. }
  5010. function quickFilterGeo(preset) {
  5011. const searchInput = document.getElementById('geo-search-input');
  5012. const continentSel = document.getElementById('geo-continent-filter');
  5013. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5014. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5015. if (searchInput) searchInput.value = '';
  5016. if (continentSel) continentSel.value = '';
  5017. if (inUseCheck) inUseCheck.checked = false;
  5018. if (cachedCheck) cachedCheck.checked = false;
  5019. if (preset === 'GR') {
  5020. if (searchInput) searchInput.value = 'Greece';
  5021. } else if (preset === 'Europe') {
  5022. if (continentSel) continentSel.value = 'Europe';
  5023. } else if (preset === 'HIGHRISK') {
  5024. if (searchInput) searchInput.value = 'China';
  5025. }
  5026. renderGeoCountries();
  5027. }
  5028. async function toggleGeoCountry(code, enabled) {
  5029. try {
  5030. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5031. method: 'POST',
  5032. headers: { 'Content-Type': 'application/json' },
  5033. body: JSON.stringify({ enabled })
  5034. });
  5035. if (res.ok) {
  5036. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5037. loadGeoIP();
  5038. } else {
  5039. const err = await res.json();
  5040. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5041. }
  5042. } catch (err) {
  5043. showToast('Error', err.message, 'error');
  5044. }
  5045. }
  5046. async function updateGeoCountry(code) {
  5047. try {
  5048. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5049. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5050. if (res.ok) {
  5051. const data = await res.json();
  5052. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5053. loadGeoIP();
  5054. } else {
  5055. const err = await res.json();
  5056. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5057. }
  5058. } catch (err) {
  5059. showToast('Error', err.message, 'error');
  5060. }
  5061. }
  5062. async function triggerGeoUpdateNow() {
  5063. const spinner = document.getElementById('geo-update-spinner');
  5064. if (spinner) spinner.classList.remove('hidden');
  5065. try {
  5066. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5067. if (res.ok) {
  5068. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5069. setTimeout(() => {
  5070. loadGeoIP();
  5071. if (spinner) spinner.classList.add('hidden');
  5072. }, 2500);
  5073. } else {
  5074. const err = await res.json();
  5075. showToast('Notice', err.message || 'Update in progress', 'info');
  5076. if (spinner) spinner.classList.add('hidden');
  5077. }
  5078. } catch (err) {
  5079. showToast('Error', err.message, 'error');
  5080. if (spinner) spinner.classList.add('hidden');
  5081. }
  5082. }
  5083. async function applyGeoPreset(preset) {
  5084. try {
  5085. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5086. method: 'POST',
  5087. headers: { 'Content-Type': 'application/json' },
  5088. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5089. });
  5090. if (res.ok) {
  5091. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5092. loadGeoIP();
  5093. }
  5094. } catch (err) {
  5095. showToast('Error', err.message, 'error');
  5096. }
  5097. }
  5098. function openGeoIntervalModal() {
  5099. const s = state.geoStatus || {};
  5100. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5101. const sel = document.getElementById('geo-cfg-interval');
  5102. const customBox = document.getElementById('geo-cfg-custom-box');
  5103. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5104. const curHours = s.interval_hours || 24;
  5105. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5106. if (matchOption) {
  5107. sel.value = String(curHours);
  5108. customBox.classList.add('hidden');
  5109. } else {
  5110. sel.value = 'custom';
  5111. customHoursInput.value = curHours;
  5112. customBox.classList.remove('hidden');
  5113. }
  5114. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5115. }
  5116. function closeGeoIntervalModal() {
  5117. document.getElementById('geo-interval-modal').classList.add('hidden');
  5118. }
  5119. function toggleCustomGeoInterval() {
  5120. const val = document.getElementById('geo-cfg-interval').value;
  5121. const customBox = document.getElementById('geo-cfg-custom-box');
  5122. if (val === 'custom') {
  5123. customBox.classList.remove('hidden');
  5124. } else {
  5125. customBox.classList.add('hidden');
  5126. }
  5127. }
  5128. async function submitGeoIntervalSettings(e) {
  5129. e.preventDefault();
  5130. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5131. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5132. let hours = 24;
  5133. if (intervalVal === 'custom') {
  5134. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5135. } else {
  5136. hours = parseInt(intervalVal, 10) || 24;
  5137. }
  5138. try {
  5139. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5140. method: 'POST',
  5141. headers: { 'Content-Type': 'application/json' },
  5142. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5143. });
  5144. if (res.ok) {
  5145. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5146. closeGeoIntervalModal();
  5147. loadGeoIP();
  5148. } else {
  5149. const err = await res.json();
  5150. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5151. }
  5152. } catch (err) {
  5153. showToast('Error', err.message, 'error');
  5154. }
  5155. }
  5156. async function viewGeoSubnets(code, name) {
  5157. if (!name) {
  5158. const found = (state.geoCountries || []).find(x => x.code === code);
  5159. name = found ? found.name : code;
  5160. }
  5161. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5162. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5163. const listEl = document.getElementById('geo-subnets-list');
  5164. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5165. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5166. try {
  5167. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5168. if (res.ok) {
  5169. const data = await res.json();
  5170. const subnets = data.subnets || [];
  5171. if (subnets.length === 0) {
  5172. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5173. } else {
  5174. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5175. }
  5176. } else {
  5177. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5178. }
  5179. } catch (err) {
  5180. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5181. }
  5182. }
  5183. function closeGeoSubnetsModal() {
  5184. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5185. }
  5186. // ----------------- Active Connections Tracking -----------------
  5187. async function loadConnections() {
  5188. try {
  5189. const res = await fetch(`${API_BASE}/firewall/connections`);
  5190. const data = await res.json();
  5191. state.connections = Array.isArray(data) ? data : [];
  5192. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5193. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5194. renderConnections();
  5195. } catch (err) {
  5196. console.error('Failed to load connections:', err);
  5197. }
  5198. }
  5199. function renderConnections() {
  5200. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5201. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5202. const tbody = document.getElementById('conns-table-body');
  5203. const empty = document.getElementById('conns-empty');
  5204. if (!tbody) return;
  5205. tbody.innerHTML = '';
  5206. const conns = (state.connections || []).filter(c => {
  5207. if (protoFilter && c.protocol !== protoFilter) return false;
  5208. if (search) {
  5209. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5210. if (!line.includes(search)) return false;
  5211. }
  5212. return true;
  5213. });
  5214. if (conns.length === 0) {
  5215. empty?.classList.remove('hidden');
  5216. return;
  5217. }
  5218. empty?.classList.add('hidden');
  5219. conns.slice(0, 150).forEach(c => {
  5220. const tr = document.createElement('tr');
  5221. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5222. let stateColor = 'text-slate-400';
  5223. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5224. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5225. tr.innerHTML = `
  5226. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5227. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5228. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5229. <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>
  5230. <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>
  5231. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5232. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5233. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5234. <td class="py-2.5 px-3 text-right font-sans">
  5235. <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>
  5236. </td>
  5237. `;
  5238. tbody.appendChild(tr);
  5239. });
  5240. }
  5241. async function killConnection(protocol, src, sport, dst, dport) {
  5242. try {
  5243. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5244. method: 'POST',
  5245. headers: { 'Content-Type': 'application/json' },
  5246. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5247. });
  5248. if (res.ok) {
  5249. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5250. loadConnections();
  5251. }
  5252. } catch (err) {
  5253. showToast('Error', err.message, 'error');
  5254. }
  5255. }
  5256. async function resetFirewallCounters() {
  5257. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5258. try {
  5259. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5260. if (res.ok) {
  5261. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5262. loadFirewall(false);
  5263. }
  5264. } catch (err) {
  5265. showToast('Error', err.message, 'error');
  5266. }
  5267. }
  5268. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5269. function switchRoutesSubTab(tab) {
  5270. state.routesSubTab = tab;
  5271. const tabs = ['routes', 'rules', 'tables'];
  5272. tabs.forEach(t => {
  5273. const panel = document.getElementById(`routes-subtab-${t}`);
  5274. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5275. if (panel) {
  5276. if (t === tab) panel.classList.remove('hidden');
  5277. else panel.classList.add('hidden');
  5278. }
  5279. if (btn) {
  5280. if (t === tab) {
  5281. 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';
  5282. } else {
  5283. 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';
  5284. }
  5285. }
  5286. });
  5287. setTimeout(initTableSorting, 50);
  5288. }
  5289. async function loadRoutes() {
  5290. try {
  5291. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5292. fetch(`${API_BASE}/routes`),
  5293. fetch(`${API_BASE}/routing/rules`),
  5294. fetch(`${API_BASE}/routing/tables`)
  5295. ]);
  5296. if (routesRes.ok) state.routes = await routesRes.json();
  5297. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5298. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5299. const bRoutes = document.getElementById('routes-badge-routes');
  5300. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5301. const showSystem = document.getElementById('prule-show-system')?.checked;
  5302. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5303. const bRules = document.getElementById('routes-badge-rules');
  5304. if (bRules) bRules.innerText = userRules.length;
  5305. const bTables = document.getElementById('routes-badge-tables');
  5306. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5307. const bRoutesCount = document.getElementById('badge-routes-count');
  5308. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5309. renderRoutesList();
  5310. renderPolicyRules();
  5311. renderRoutingTables();
  5312. } catch (err) {
  5313. console.error('Failed to load routing:', err);
  5314. }
  5315. }
  5316. function renderRoutesList() {
  5317. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5318. const tbody = document.getElementById('routes-table-body');
  5319. const empty = document.getElementById('routes-empty');
  5320. if (!tbody) return;
  5321. tbody.innerHTML = '';
  5322. // Update table filter select
  5323. const sel = document.getElementById('routes-filter-table');
  5324. if (sel) {
  5325. const cur = sel.value;
  5326. sel.innerHTML = '<option value="">All Tables</option>';
  5327. (state.routingTables || []).forEach(t => {
  5328. const opt = document.createElement('option');
  5329. opt.value = t.name;
  5330. opt.innerText = t.name;
  5331. if (t.name === cur) opt.selected = true;
  5332. sel.appendChild(opt);
  5333. });
  5334. }
  5335. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5336. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5337. if (routes.length === 0) {
  5338. empty?.classList.remove('hidden');
  5339. return;
  5340. }
  5341. empty?.classList.add('hidden');
  5342. routes.forEach(r => {
  5343. const tr = document.createElement('tr');
  5344. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5345. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5346. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5347. let flags = '';
  5348. if (r.dynamic) flags += 'D';
  5349. if (r.active) flags += 'A';
  5350. if (r.connect) flags += 'C';
  5351. if (r.static) flags += 'S';
  5352. if (r.disabled) flags += 'X';
  5353. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5354. tr.innerHTML = `
  5355. <td class="py-2.5 px-3 text-center">
  5356. <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'}">
  5357. ${flags || '-'}
  5358. </span>
  5359. </td>
  5360. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5361. <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>
  5362. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5363. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5364. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5365. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5366. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5367. ${r.static ? `
  5368. <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>
  5369. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5370. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5371. ` : `
  5372. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5373. `}
  5374. </td>
  5375. `;
  5376. tbody.appendChild(tr);
  5377. });
  5378. }
  5379. function openAddRouteModal() {
  5380. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5381. document.getElementById('route-modal-id').value = '';
  5382. document.getElementById('route-modal-old-dst').value = '';
  5383. document.getElementById('route-modal-old-gw').value = '';
  5384. document.getElementById('route-modal-old-distance').value = '';
  5385. document.getElementById('route-modal-old-table').value = '';
  5386. document.getElementById('route-modal-old-iface').value = '';
  5387. const dstInput = document.getElementById('route-modal-dst');
  5388. const gwInput = document.getElementById('route-modal-gw');
  5389. const distInput = document.getElementById('route-modal-distance');
  5390. const ifaceSelect = document.getElementById('route-modal-iface');
  5391. const tableSelect = document.getElementById('route-modal-table');
  5392. const commentInput = document.getElementById('route-modal-comment');
  5393. const disCheck = document.getElementById('route-modal-disabled');
  5394. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5395. dstInput.disabled = false;
  5396. dstInput.value = '0.0.0.0/0';
  5397. gwInput.disabled = false;
  5398. gwInput.value = '';
  5399. distInput.disabled = false;
  5400. distInput.value = '1';
  5401. ifaceSelect.disabled = false;
  5402. tableSelect.disabled = false;
  5403. commentInput.disabled = false;
  5404. commentInput.value = '';
  5405. disCheck.disabled = false;
  5406. disCheck.checked = false;
  5407. if (saveBtn) saveBtn.classList.remove('hidden');
  5408. populateInterfaceSelect('route-modal-iface');
  5409. // Populate tables
  5410. tableSelect.innerHTML = '';
  5411. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5412. const opt = document.createElement('option');
  5413. opt.value = t.name;
  5414. opt.innerText = t.name;
  5415. if (t.name === 'main') opt.selected = true;
  5416. tableSelect.appendChild(opt);
  5417. });
  5418. document.getElementById('route-modal').classList.remove('hidden');
  5419. }
  5420. function openEditRouteModal(id) {
  5421. const r = (state.routes || []).find(route => route.id === id);
  5422. if (!r) return;
  5423. const isStatic = !!r.static;
  5424. document.getElementById('route-modal-title').innerText = isStatic
  5425. ? `Edit Route: ${r.dst_address}`
  5426. : `Route Properties (Read Only): ${r.dst_address}`;
  5427. document.getElementById('route-modal-id').value = r.id;
  5428. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5429. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5430. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5431. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5432. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5433. const dstInput = document.getElementById('route-modal-dst');
  5434. const gwInput = document.getElementById('route-modal-gw');
  5435. const distInput = document.getElementById('route-modal-distance');
  5436. const ifaceSelect = document.getElementById('route-modal-iface');
  5437. const tableSelect = document.getElementById('route-modal-table');
  5438. const commentInput = document.getElementById('route-modal-comment');
  5439. const disCheck = document.getElementById('route-modal-disabled');
  5440. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5441. dstInput.value = r.dst_address;
  5442. gwInput.value = r.gateway || '';
  5443. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5444. commentInput.value = r.comment || '';
  5445. disCheck.checked = !!r.disabled;
  5446. dstInput.disabled = !isStatic;
  5447. gwInput.disabled = !isStatic;
  5448. distInput.disabled = !isStatic;
  5449. ifaceSelect.disabled = !isStatic;
  5450. tableSelect.disabled = !isStatic;
  5451. commentInput.disabled = !isStatic;
  5452. disCheck.disabled = !isStatic;
  5453. if (saveBtn) {
  5454. if (isStatic) {
  5455. saveBtn.classList.remove('hidden');
  5456. } else {
  5457. saveBtn.classList.add('hidden');
  5458. }
  5459. }
  5460. populateInterfaceSelect('route-modal-iface', r.interface);
  5461. tableSelect.innerHTML = '';
  5462. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5463. const opt = document.createElement('option');
  5464. opt.value = t.name;
  5465. opt.innerText = t.name;
  5466. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5467. tableSelect.appendChild(opt);
  5468. });
  5469. document.getElementById('route-modal').classList.remove('hidden');
  5470. }
  5471. function closeRouteModal() {
  5472. document.getElementById('route-modal').classList.add('hidden');
  5473. }
  5474. async function submitSaveRoute(e) {
  5475. e.preventDefault();
  5476. const id = document.getElementById('route-modal-id').value;
  5477. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5478. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5479. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5480. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5481. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5482. const dst = document.getElementById('route-modal-dst').value.trim();
  5483. const gw = document.getElementById('route-modal-gw').value.trim();
  5484. const table = document.getElementById('route-modal-table').value;
  5485. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5486. const iface = document.getElementById('route-modal-iface').value;
  5487. const comment = document.getElementById('route-modal-comment').value.trim();
  5488. const disabled = document.getElementById('route-modal-disabled').checked;
  5489. if (!dst) {
  5490. showToast('Error', 'Destination address is required', 'error');
  5491. return;
  5492. }
  5493. if (!gw && !iface) {
  5494. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5495. return;
  5496. }
  5497. const payload = {
  5498. id,
  5499. old_dst_address: oldDst,
  5500. old_gateway: oldGw,
  5501. old_routing_table: oldTable,
  5502. old_interface: oldIface,
  5503. dst_address: dst,
  5504. gateway: gw || iface,
  5505. routing_table: table,
  5506. distance,
  5507. interface: iface,
  5508. comment,
  5509. disabled
  5510. };
  5511. if (oldDistStr !== undefined && oldDistStr !== '') {
  5512. payload.old_distance = parseInt(oldDistStr, 10);
  5513. }
  5514. try {
  5515. const res = await fetch(`${API_BASE}/routes`, {
  5516. method: 'POST',
  5517. headers: { 'Content-Type': 'application/json' },
  5518. body: JSON.stringify(payload)
  5519. });
  5520. if (res.ok) {
  5521. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5522. closeRouteModal();
  5523. loadRoutes();
  5524. } else {
  5525. const err = await res.json();
  5526. showToast('Error', err.message || 'Failed to save route', 'error');
  5527. }
  5528. } catch (err) {
  5529. showToast('Error', err.message, 'error');
  5530. }
  5531. }
  5532. async function toggleRouteState(id, disabled) {
  5533. try {
  5534. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5535. method: 'POST',
  5536. headers: { 'Content-Type': 'application/json' },
  5537. body: JSON.stringify({ disabled })
  5538. });
  5539. if (res.ok) loadRoutes();
  5540. } catch (err) {
  5541. showToast('Error', err.message, 'error');
  5542. }
  5543. }
  5544. async function deleteRoute(id) {
  5545. if (!confirm('Are you sure you want to delete this route?')) return;
  5546. try {
  5547. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5548. if (res.ok) {
  5549. showToast('Deleted', 'Route removed', 'success');
  5550. loadRoutes();
  5551. }
  5552. } catch (err) {
  5553. showToast('Error', err.message, 'error');
  5554. }
  5555. }
  5556. // ----------------- Policy Rules (/ip route rule) -----------------
  5557. function renderPolicyRules() {
  5558. const tbody = document.getElementById('rules-table-body');
  5559. const empty = document.getElementById('rules-empty');
  5560. if (!tbody) return;
  5561. tbody.innerHTML = '';
  5562. const showSystem = document.getElementById('prule-show-system')?.checked;
  5563. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5564. const countBadge = document.getElementById('rules-count-badge');
  5565. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5566. const bRules = document.getElementById('routes-badge-rules');
  5567. if (bRules) bRules.innerText = filtered.length;
  5568. if (filtered.length === 0) {
  5569. empty?.classList.remove('hidden');
  5570. return;
  5571. }
  5572. empty?.classList.add('hidden');
  5573. filtered.forEach(pr => {
  5574. const isSys = pr.is_default || pr.is_system;
  5575. const tr = document.createElement('tr');
  5576. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5577. tr.innerHTML = `
  5578. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5579. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5580. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5581. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5582. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5583. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5584. <td class="py-2.5 px-3 text-right font-sans">
  5585. ${!pr.is_default ? `
  5586. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5587. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5588. </td>
  5589. `;
  5590. tbody.appendChild(tr);
  5591. });
  5592. }
  5593. function openAddPolicyRuleModal() {
  5594. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5595. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5596. document.getElementById('prule-modal-mark').value = '';
  5597. document.getElementById('prule-modal-src').value = '';
  5598. document.getElementById('prule-modal-dst').value = '';
  5599. const sel = document.getElementById('prule-modal-table');
  5600. sel.innerHTML = '';
  5601. (state.routingTables || []).forEach(t => {
  5602. const opt = document.createElement('option');
  5603. opt.value = t.name;
  5604. opt.innerText = t.name;
  5605. sel.appendChild(opt);
  5606. });
  5607. document.getElementById('prule-modal').classList.remove('hidden');
  5608. }
  5609. function closePolicyRuleModal() {
  5610. document.getElementById('prule-modal').classList.add('hidden');
  5611. }
  5612. async function submitSavePolicyRule(e) {
  5613. e.preventDefault();
  5614. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5615. const mark = document.getElementById('prule-modal-mark').value.trim();
  5616. const src = document.getElementById('prule-modal-src').value.trim();
  5617. const dst = document.getElementById('prule-modal-dst').value.trim();
  5618. const table = document.getElementById('prule-modal-table').value;
  5619. const action = document.getElementById('prule-modal-action').value;
  5620. try {
  5621. const res = await fetch(`${API_BASE}/routing/rules`, {
  5622. method: 'POST',
  5623. headers: { 'Content-Type': 'application/json' },
  5624. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5625. });
  5626. if (res.ok) {
  5627. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5628. closePolicyRuleModal();
  5629. loadRoutes();
  5630. } else {
  5631. const err = await res.json();
  5632. showToast('Error', err.message, 'error');
  5633. }
  5634. } catch (err) {
  5635. showToast('Error', err.message, 'error');
  5636. }
  5637. }
  5638. async function deletePolicyRule(id) {
  5639. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5640. try {
  5641. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5642. if (res.ok) {
  5643. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5644. loadRoutes();
  5645. }
  5646. } catch (err) {
  5647. showToast('Error', err.message, 'error');
  5648. }
  5649. }
  5650. // ----------------- Routing Tables -----------------
  5651. function renderRoutingTables() {
  5652. const tbody = document.getElementById('tables-table-body');
  5653. if (!tbody) return;
  5654. tbody.innerHTML = '';
  5655. (state.routingTables || []).forEach(t => {
  5656. const tr = document.createElement('tr');
  5657. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5658. tr.innerHTML = `
  5659. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5660. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5661. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5662. `;
  5663. tbody.appendChild(tr);
  5664. });
  5665. }
  5666. function openAddTableModal() {
  5667. document.getElementById('table-modal-name').value = '';
  5668. document.getElementById('table-modal-id').value = '';
  5669. document.getElementById('table-modal-comment').value = '';
  5670. document.getElementById('table-modal').classList.remove('hidden');
  5671. }
  5672. function closeTableModal() {
  5673. document.getElementById('table-modal').classList.add('hidden');
  5674. }
  5675. async function submitSaveTable(e) {
  5676. e.preventDefault();
  5677. const name = document.getElementById('table-modal-name').value.trim();
  5678. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5679. const comment = document.getElementById('table-modal-comment').value.trim();
  5680. try {
  5681. const res = await fetch(`${API_BASE}/routing/tables`, {
  5682. method: 'POST',
  5683. headers: { 'Content-Type': 'application/json' },
  5684. body: JSON.stringify({ name, table_id: id, comment })
  5685. });
  5686. if (res.ok) {
  5687. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5688. closeTableModal();
  5689. loadRoutes();
  5690. } else {
  5691. const err = await res.json();
  5692. showToast('Error', err.message, 'error');
  5693. }
  5694. } catch (err) {
  5695. showToast('Error', err.message, 'error');
  5696. }
  5697. }
  5698. async function loadDebianConfig() {
  5699. const view = document.getElementById('debian-config-view');
  5700. view.innerText = 'Generating live configuration...';
  5701. try {
  5702. const res = await fetch(`${API_BASE}/debian/config`);
  5703. const data = await res.json();
  5704. view.innerText = data.content || '# Empty config';
  5705. } catch (err) {
  5706. view.innerText = 'Failed to generate Debian network config.';
  5707. }
  5708. }
  5709. async function saveDebianConfig() {
  5710. try {
  5711. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5712. const data = await res.json();
  5713. if (res.ok) {
  5714. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5715. loadDebianConfig();
  5716. }
  5717. } catch (err) {
  5718. showToast('Error', err.message, 'error');
  5719. }
  5720. }
  5721. function showToast(title, message, type = 'info') {
  5722. const container = document.getElementById('toast-container');
  5723. const toast = document.createElement('div');
  5724. const borderColors = {
  5725. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5726. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5727. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5728. };
  5729. 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}`;
  5730. toast.innerHTML = `
  5731. <div class="flex-1">
  5732. <div class="font-bold text-xs text-white">${title}</div>
  5733. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5734. </div>
  5735. `;
  5736. container.appendChild(toast);
  5737. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5738. setTimeout(() => {
  5739. toast.classList.add('opacity-0', 'translate-y-2');
  5740. setTimeout(() => toast.remove(), 300);
  5741. }, 4000);
  5742. }
  5743. function formatTraffic(bytesPerSec) {
  5744. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5745. const kb = bytesPerSec / 1024;
  5746. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5747. const mb = kb / 1024;
  5748. return `${mb.toFixed(2)} MB/s`;
  5749. }
  5750. function toggleSidebar() {
  5751. const sb = document.getElementById('sidebar');
  5752. sb.classList.toggle('-translate-x-full');
  5753. }
  5754. // ======================== EoIP (Ethernet over IP) ========================
  5755. async function loadEoIP(populate = true) {
  5756. try {
  5757. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5758. const data = await res.json();
  5759. state.eoipTunnels = Array.isArray(data) ? data : [];
  5760. const badge = document.getElementById('eoip-count-badge');
  5761. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5762. const sideBadge = document.getElementById('badge-eoip-count');
  5763. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5764. renderEoIPTunnels();
  5765. } catch (err) {
  5766. console.error('Failed to load EoIP:', err);
  5767. }
  5768. }
  5769. function renderEoIPTunnels() {
  5770. const tbody = document.getElementById('eoip-table-body');
  5771. const empty = document.getElementById('eoip-empty');
  5772. if (!tbody) return;
  5773. tbody.innerHTML = '';
  5774. const tunnels = state.eoipTunnels || [];
  5775. if (tunnels.length === 0) {
  5776. empty?.classList.remove('hidden');
  5777. return;
  5778. }
  5779. empty?.classList.add('hidden');
  5780. tunnels.forEach(t => {
  5781. const tr = document.createElement('tr');
  5782. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5783. tr.innerHTML = `
  5784. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5785. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5786. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5787. <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>
  5788. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5789. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5790. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5791. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5792. <td class="py-2.5 px-3 font-mono text-[11px]">
  5793. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5794. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5795. </td>
  5796. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5797. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5798. <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>
  5799. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5800. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5801. </td>
  5802. `;
  5803. tbody.appendChild(tr);
  5804. });
  5805. }
  5806. function openAddEoIPModal() {
  5807. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5808. document.getElementById('eoip-modal-id').value = '';
  5809. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5810. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5811. document.getElementById('eoip-modal-remote').value = '';
  5812. document.getElementById('eoip-modal-ip').value = '';
  5813. document.getElementById('eoip-modal-local').value = '';
  5814. document.getElementById('eoip-modal-mac').value = '';
  5815. document.getElementById('eoip-modal-mtu').value = '1500';
  5816. document.getElementById('eoip-modal-comment').value = '';
  5817. document.getElementById('eoip-modal-clampmss').checked = true;
  5818. document.getElementById('eoip-modal-disabled').checked = false;
  5819. document.getElementById('eoip-modal').classList.remove('hidden');
  5820. }
  5821. function openEditEoIPModal(id) {
  5822. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5823. if (!t) return;
  5824. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5825. document.getElementById('eoip-modal-id').value = t.id;
  5826. document.getElementById('eoip-modal-name').value = t.name;
  5827. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5828. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5829. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5830. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5831. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5832. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5833. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5834. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5835. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5836. document.getElementById('eoip-modal').classList.remove('hidden');
  5837. }
  5838. function closeEoIPModal() {
  5839. document.getElementById('eoip-modal').classList.add('hidden');
  5840. }
  5841. async function submitSaveEoIP(e) {
  5842. e.preventDefault();
  5843. const id = document.getElementById('eoip-modal-id').value;
  5844. const name = document.getElementById('eoip-modal-name').value.trim();
  5845. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5846. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5847. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5848. const local = document.getElementById('eoip-modal-local').value.trim();
  5849. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5850. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5851. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5852. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5853. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5854. try {
  5855. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5856. method: 'POST',
  5857. headers: { 'Content-Type': 'application/json' },
  5858. body: JSON.stringify({
  5859. id,
  5860. name,
  5861. tunnel_id: tunnelId,
  5862. remote_address: remote,
  5863. ip_address: ipAddress,
  5864. local_address: local,
  5865. mac_address: mac,
  5866. mtu,
  5867. clamp_mss: clampMss,
  5868. comment,
  5869. disabled
  5870. })
  5871. });
  5872. if (res.ok) {
  5873. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5874. closeEoIPModal();
  5875. loadEoIP(false);
  5876. fetchData(false);
  5877. } else {
  5878. const err = await res.json();
  5879. showToast('Error', err.message, 'error');
  5880. }
  5881. } catch (err) {
  5882. showToast('Error', err.message, 'error');
  5883. }
  5884. }
  5885. async function toggleEoIPState(id, disabled) {
  5886. try {
  5887. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5888. method: 'POST',
  5889. headers: { 'Content-Type': 'application/json' },
  5890. body: JSON.stringify({ disabled })
  5891. });
  5892. if (res.ok) {
  5893. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5894. loadEoIP(false);
  5895. fetchData(false);
  5896. }
  5897. } catch (err) {
  5898. showToast('Error', err.message, 'error');
  5899. }
  5900. }
  5901. async function deleteEoIP(id) {
  5902. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5903. try {
  5904. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5905. if (res.ok) {
  5906. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5907. loadEoIP(false);
  5908. fetchData(false);
  5909. }
  5910. } catch (err) {
  5911. showToast('Error', err.message, 'error');
  5912. }
  5913. }
  5914. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  5915. async function loadAeroTUN(populate = true) {
  5916. try {
  5917. const [tunnelsRes, statsRes] = await Promise.all([
  5918. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  5919. fetch(`${API_BASE}/vpn/aerotun/stats`)
  5920. ]);
  5921. if (tunnelsRes.ok) {
  5922. const data = await tunnelsRes.json();
  5923. state.aerotunTunnels = Array.isArray(data) ? data : [];
  5924. }
  5925. if (statsRes.ok) {
  5926. state.aerotunStats = await statsRes.json();
  5927. }
  5928. const countBadge = document.getElementById('aerotun-count-badge');
  5929. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  5930. const sideBadge = document.getElementById('badge-aerotun-count');
  5931. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  5932. renderAeroTUN();
  5933. } catch (err) {
  5934. console.error('Failed to load AeroTUN:', err);
  5935. }
  5936. }
  5937. function renderAeroTUN() {
  5938. const tbody = document.getElementById('aerotun-table-body');
  5939. const empty = document.getElementById('aerotun-empty');
  5940. // Update summary cards
  5941. const stats = state.aerotunStats || {};
  5942. const tunnels = state.aerotunTunnels || [];
  5943. const statActive = document.getElementById('aerotun-stat-active');
  5944. if (statActive) {
  5945. const activeCount = tunnels.filter(t => t.running).length;
  5946. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  5947. }
  5948. const statSaved = document.getElementById('aerotun-stat-saved');
  5949. if (statSaved) {
  5950. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  5951. }
  5952. const statRatio = document.getElementById('aerotun-stat-ratio');
  5953. if (statRatio) {
  5954. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  5955. }
  5956. const statTraffic = document.getElementById('aerotun-stat-traffic');
  5957. if (statTraffic) {
  5958. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  5959. }
  5960. if (!tbody) return;
  5961. tbody.innerHTML = '';
  5962. if (tunnels.length === 0) {
  5963. empty?.classList.remove('hidden');
  5964. return;
  5965. }
  5966. empty?.classList.add('hidden');
  5967. tunnels.forEach(t => {
  5968. const tr = document.createElement('tr');
  5969. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5970. const modeBadge = t.mode === 'server'
  5971. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  5972. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  5973. const endpointInfo = t.mode === 'server'
  5974. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  5975. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  5976. const compBadge = t.compression
  5977. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  5978. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  5979. const activePeer = t.active_peer_endpoint
  5980. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  5981. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  5982. const rawRx = formatBytes(t.rx_bytes || 0);
  5983. const rawTx = formatBytes(t.tx_bytes || 0);
  5984. const wireRx = formatBytes(t.wire_bytes_in || 0);
  5985. const wireTx = formatBytes(t.wire_bytes_out || 0);
  5986. tr.innerHTML = `
  5987. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5988. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  5989. <span>${escapeHtml(t.name)}</span>
  5990. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  5991. </td>
  5992. <td class="py-2.5 px-3">${modeBadge}</td>
  5993. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  5994. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  5995. <td class="py-2.5 px-3">${compBadge}</td>
  5996. <td class="py-2.5 px-3">${activePeer}</td>
  5997. <td class="py-2.5 px-3 font-mono text-[11px]">
  5998. <span class="text-emerald-400">↓ ${rawRx}</span>
  5999. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6000. </td>
  6001. <td class="py-2.5 px-3 font-mono text-[11px]">
  6002. <span class="text-slate-400">↓ ${wireRx}</span>
  6003. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6004. </td>
  6005. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6006. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6007. ${t.running
  6008. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6009. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6010. }
  6011. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6012. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6013. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6014. </td>
  6015. `;
  6016. tbody.appendChild(tr);
  6017. });
  6018. }
  6019. function onAeroTUNModeChange() {
  6020. const mode = document.getElementById('aerotun-modal-mode').value;
  6021. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6022. const portInput = document.getElementById('aerotun-modal-port');
  6023. if (mode === 'server') {
  6024. if (!portInput.value) portInput.value = '51830';
  6025. endpointInput.placeholder = 'Optional / learned roaming peer';
  6026. } else {
  6027. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6028. if (!portInput.value) portInput.value = '';
  6029. }
  6030. }
  6031. async function generateAeroTUNKey() {
  6032. try {
  6033. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6034. if (res.ok) {
  6035. const data = await res.json();
  6036. document.getElementById('aerotun-modal-psk').value = data.key;
  6037. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6038. }
  6039. } catch (err) {
  6040. const arr = new Uint8Array(32);
  6041. crypto.getRandomValues(arr);
  6042. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6043. document.getElementById('aerotun-modal-psk').value = hex;
  6044. }
  6045. }
  6046. function openAddAeroTUNModal() {
  6047. const tunnels = state.aerotunTunnels || [];
  6048. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6049. document.getElementById('aerotun-modal-id').value = '';
  6050. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6051. document.getElementById('aerotun-modal-mode').value = 'server';
  6052. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6053. document.getElementById('aerotun-modal-endpoint').value = '';
  6054. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6055. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6056. document.getElementById('aerotun-modal-psk').value = '';
  6057. document.getElementById('aerotun-modal-mtu').value = '1420';
  6058. document.getElementById('aerotun-modal-comment').value = '';
  6059. document.getElementById('aerotun-modal-compression').checked = true;
  6060. document.getElementById('aerotun-modal-defroute').checked = false;
  6061. document.getElementById('aerotun-modal-disabled').checked = false;
  6062. generateAeroTUNKey();
  6063. onAeroTUNModeChange();
  6064. document.getElementById('aerotun-modal').classList.remove('hidden');
  6065. }
  6066. function openEditAeroTUNModal(id) {
  6067. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6068. if (!t) return;
  6069. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6070. document.getElementById('aerotun-modal-id').value = t.id;
  6071. document.getElementById('aerotun-modal-name').value = t.name;
  6072. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6073. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6074. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6075. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6076. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6077. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6078. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6079. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6080. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6081. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6082. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6083. onAeroTUNModeChange();
  6084. document.getElementById('aerotun-modal').classList.remove('hidden');
  6085. }
  6086. function closeAeroTUNModal() {
  6087. document.getElementById('aerotun-modal').classList.add('hidden');
  6088. }
  6089. async function submitSaveAeroTUN(e) {
  6090. e.preventDefault();
  6091. const id = document.getElementById('aerotun-modal-id').value;
  6092. const name = document.getElementById('aerotun-modal-name').value.trim();
  6093. const mode = document.getElementById('aerotun-modal-mode').value;
  6094. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6095. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6096. const local = document.getElementById('aerotun-modal-local').value.trim();
  6097. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6098. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6099. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6100. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6101. const compression = document.getElementById('aerotun-modal-compression').checked;
  6102. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6103. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6104. if (mode === 'client' && !endpoint) {
  6105. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6106. return;
  6107. }
  6108. if (!psk) {
  6109. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6110. return;
  6111. }
  6112. try {
  6113. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6114. method: 'POST',
  6115. headers: { 'Content-Type': 'application/json' },
  6116. body: JSON.stringify({
  6117. id,
  6118. name,
  6119. mode,
  6120. listen_port: port,
  6121. remote_endpoint: endpoint,
  6122. local_address: local,
  6123. peer_address: peer,
  6124. psk,
  6125. mtu,
  6126. compression,
  6127. default_route: defaultRoute,
  6128. comment,
  6129. disabled
  6130. })
  6131. });
  6132. if (res.ok) {
  6133. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6134. closeAeroTUNModal();
  6135. loadAeroTUN(false);
  6136. fetchData(false);
  6137. } else {
  6138. const err = await res.text();
  6139. showToast('Error Saving Tunnel', err, 'error');
  6140. }
  6141. } catch (err) {
  6142. showToast('Network Error', err.message, 'error');
  6143. }
  6144. }
  6145. async function startAeroTUNTunnel(id) {
  6146. try {
  6147. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6148. if (res.ok) {
  6149. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6150. loadAeroTUN(false);
  6151. fetchData(false);
  6152. } else {
  6153. const err = await res.text();
  6154. showToast('Failed to Start', err, 'error');
  6155. }
  6156. } catch (err) {
  6157. showToast('Error', err.message, 'error');
  6158. }
  6159. }
  6160. async function stopAeroTUNTunnel(id) {
  6161. try {
  6162. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6163. if (res.ok) {
  6164. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6165. loadAeroTUN(false);
  6166. fetchData(false);
  6167. } else {
  6168. const err = await res.text();
  6169. showToast('Failed to Stop', err, 'error');
  6170. }
  6171. } catch (err) {
  6172. showToast('Error', err.message, 'error');
  6173. }
  6174. }
  6175. async function toggleAeroTUNState(id, disabled) {
  6176. try {
  6177. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6178. method: 'POST',
  6179. headers: { 'Content-Type': 'application/json' },
  6180. body: JSON.stringify({ disabled })
  6181. });
  6182. if (res.ok) {
  6183. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6184. loadAeroTUN(false);
  6185. fetchData(false);
  6186. }
  6187. } catch (err) {
  6188. showToast('Error', err.message, 'error');
  6189. }
  6190. }
  6191. async function deleteAeroTUN(id) {
  6192. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6193. try {
  6194. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6195. if (res.ok) {
  6196. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6197. loadAeroTUN(false);
  6198. fetchData(false);
  6199. }
  6200. } catch (err) {
  6201. showToast('Error', err.message, 'error');
  6202. }
  6203. }
  6204. // ======================== PPP Central Hub & Servers ========================
  6205. function switchPPPSubTab(tab) {
  6206. state.pppSubTab = tab;
  6207. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6208. tabs.forEach(t => {
  6209. const panel = document.getElementById(`ppp-subtab-${t}`);
  6210. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6211. if (panel) {
  6212. if (t === tab) panel.classList.remove('hidden');
  6213. else panel.classList.add('hidden');
  6214. }
  6215. if (btn) {
  6216. if (t === tab) {
  6217. 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';
  6218. } else {
  6219. 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';
  6220. }
  6221. }
  6222. });
  6223. const addBtn = document.getElementById('ppp-primary-add-btn');
  6224. if (addBtn) {
  6225. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6226. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6227. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6228. else addBtn.innerHTML = '<span>Save Config</span>';
  6229. }
  6230. if (tab === 'active') loadPPPSessions();
  6231. }
  6232. function openCurrentPPPModal() {
  6233. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6234. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6235. else if (state.pppSubTab === 'active') loadPPPSessions();
  6236. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6237. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6238. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6239. }
  6240. async function loadPPP(populateDropdowns = true) {
  6241. await Promise.all([
  6242. loadPPPSecrets(),
  6243. loadPPPProfiles(),
  6244. loadPPPServers(),
  6245. loadPPPSessions()
  6246. ]);
  6247. }
  6248. async function loadPPPSecrets() {
  6249. try {
  6250. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6251. const data = await res.json();
  6252. state.pppSecrets = Array.isArray(data) ? data : [];
  6253. const b = document.getElementById('ppp-badge-secrets');
  6254. if (b) b.innerText = state.pppSecrets.length;
  6255. const b2 = document.getElementById('secrets-count-badge');
  6256. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6257. renderPPPSecrets();
  6258. } catch (err) {
  6259. console.error('Failed to load PPP secrets:', err);
  6260. }
  6261. }
  6262. function renderPPPSecrets() {
  6263. const tbody = document.getElementById('secrets-table-body');
  6264. const empty = document.getElementById('secrets-empty');
  6265. if (!tbody) return;
  6266. tbody.innerHTML = '';
  6267. const secrets = state.pppSecrets || [];
  6268. if (secrets.length === 0) {
  6269. empty?.classList.remove('hidden');
  6270. return;
  6271. }
  6272. empty?.classList.add('hidden');
  6273. secrets.forEach(s => {
  6274. const tr = document.createElement('tr');
  6275. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6276. tr.innerHTML = `
  6277. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6278. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6279. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6280. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6281. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6282. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6283. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6284. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6285. <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>
  6286. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6287. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6288. </td>
  6289. `;
  6290. tbody.appendChild(tr);
  6291. });
  6292. }
  6293. async function loadPPPProfiles() {
  6294. try {
  6295. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6296. const data = await res.json();
  6297. state.pppProfiles = Array.isArray(data) ? data : [];
  6298. const b = document.getElementById('ppp-badge-profiles');
  6299. if (b) b.innerText = state.pppProfiles.length;
  6300. const b2 = document.getElementById('profiles-count-badge');
  6301. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6302. // Populate profile selects across modals
  6303. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6304. selects.forEach(sid => {
  6305. const el = document.getElementById(sid);
  6306. if (!el) return;
  6307. const cur = el.value;
  6308. el.innerHTML = '';
  6309. state.pppProfiles.forEach(p => {
  6310. const opt = document.createElement('option');
  6311. opt.value = p.name;
  6312. opt.innerText = `${p.name} (${p.remote_address})`;
  6313. if (p.name === cur) opt.selected = true;
  6314. el.appendChild(opt);
  6315. });
  6316. });
  6317. renderPPPProfiles();
  6318. } catch (err) {
  6319. console.error('Failed to load PPP profiles:', err);
  6320. }
  6321. }
  6322. function renderPPPProfiles() {
  6323. const tbody = document.getElementById('profiles-table-body');
  6324. if (!tbody) return;
  6325. tbody.innerHTML = '';
  6326. (state.pppProfiles || []).forEach(p => {
  6327. const isDefault = p.name.startsWith('default');
  6328. const tr = document.createElement('tr');
  6329. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6330. tr.innerHTML = `
  6331. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6332. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6333. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6334. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6335. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6336. <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>
  6337. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6338. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6339. ${!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>`}
  6340. </td>
  6341. `;
  6342. tbody.appendChild(tr);
  6343. });
  6344. }
  6345. async function loadPPPServers() {
  6346. try {
  6347. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6348. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6349. fetch(`${API_BASE}/vpn/servers/pptp`),
  6350. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6351. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6352. ]);
  6353. if (pppoeRes.ok) {
  6354. state.pppoeServer = await pppoeRes.json();
  6355. const s = state.pppoeServer;
  6356. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6357. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6358. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6359. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6360. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6361. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6362. const pill = document.getElementById('pppoe-server-status-pill');
  6363. if (pill) {
  6364. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6365. 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';
  6366. }
  6367. setDotBadge('ppp-badge-pppoe-state', s.running);
  6368. }
  6369. if (pptpRes.ok) {
  6370. state.pptpServer = await pptpRes.json();
  6371. const s = state.pptpServer;
  6372. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6373. document.getElementById('pptp-server-port').value = s.port || 1723;
  6374. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6375. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6376. const pill = document.getElementById('pptp-server-status-pill');
  6377. if (pill) {
  6378. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6379. 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';
  6380. }
  6381. setDotBadge('ppp-badge-pptp-state', s.running);
  6382. }
  6383. if (l2tpRes.ok) {
  6384. state.l2tpServer = await l2tpRes.json();
  6385. const s = state.l2tpServer;
  6386. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6387. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6388. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6389. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6390. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6391. const pill = document.getElementById('l2tp-server-status-pill');
  6392. if (pill) {
  6393. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6394. 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';
  6395. }
  6396. setDotBadge('ppp-badge-l2tp-state', s.running);
  6397. }
  6398. if (ipsecRes.ok) {
  6399. state.ipsecServer = await ipsecRes.json();
  6400. const s = state.ipsecServer;
  6401. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6402. if (modalEn) modalEn.checked = !!s.enabled;
  6403. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6404. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6405. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6406. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6407. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6408. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6409. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6410. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6411. const pill = document.getElementById('modal-ipsec-server-status');
  6412. if (pill) {
  6413. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6414. 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';
  6415. }
  6416. }
  6417. } catch (err) {
  6418. console.error('Failed to load VPN servers:', err);
  6419. }
  6420. }
  6421. async function loadPPPSessions() {
  6422. try {
  6423. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6424. const data = await res.json();
  6425. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6426. const b = document.getElementById('ppp-badge-active');
  6427. if (b) b.innerText = state.pppActiveSessions.length;
  6428. const sideB = document.getElementById('badge-ppp-sessions');
  6429. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6430. renderPPPSessions();
  6431. } catch (err) {
  6432. console.error('Failed to load active PPP sessions:', err);
  6433. }
  6434. }
  6435. function renderPPPSessions() {
  6436. const tbody = document.getElementById('active-ppp-table-body');
  6437. const empty = document.getElementById('active-ppp-empty');
  6438. if (!tbody) return;
  6439. tbody.innerHTML = '';
  6440. const list = state.pppActiveSessions || [];
  6441. if (list.length === 0) {
  6442. empty?.classList.remove('hidden');
  6443. return;
  6444. }
  6445. empty?.classList.add('hidden');
  6446. list.forEach(s => {
  6447. const tr = document.createElement('tr');
  6448. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6449. tr.innerHTML = `
  6450. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6451. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6452. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6453. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6454. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6455. <td class="py-2.5 px-3 text-[11px]">
  6456. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6457. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6458. </td>
  6459. <td class="py-2.5 px-3 text-right font-sans">
  6460. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6461. </td>
  6462. `;
  6463. tbody.appendChild(tr);
  6464. });
  6465. }
  6466. async function disconnectPPPSession(iface) {
  6467. if (!confirm(`Disconnect session ${iface}?`)) return;
  6468. try {
  6469. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6470. if (res.ok) {
  6471. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6472. loadPPPSessions();
  6473. }
  6474. } catch (err) {
  6475. showToast('Error', err.message, 'error');
  6476. }
  6477. }
  6478. // PPP Secret Modal handlers
  6479. function openAddPPPSecretModal() {
  6480. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6481. document.getElementById('secret-modal-id').value = '';
  6482. document.getElementById('secret-modal-name').value = '';
  6483. document.getElementById('secret-modal-password').value = '';
  6484. document.getElementById('secret-modal-service').value = 'any';
  6485. document.getElementById('secret-modal-profile').value = 'default';
  6486. document.getElementById('secret-modal-local').value = '';
  6487. document.getElementById('secret-modal-remote').value = '';
  6488. document.getElementById('secret-modal-comment').value = '';
  6489. document.getElementById('secret-modal-disabled').checked = false;
  6490. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6491. }
  6492. function openEditPPPSecretModal(id) {
  6493. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6494. if (!s) return;
  6495. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6496. document.getElementById('secret-modal-id').value = s.id;
  6497. document.getElementById('secret-modal-name').value = s.name;
  6498. document.getElementById('secret-modal-password').value = s.password;
  6499. document.getElementById('secret-modal-service').value = s.service || 'any';
  6500. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6501. document.getElementById('secret-modal-local').value = s.local_address || '';
  6502. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6503. document.getElementById('secret-modal-comment').value = s.comment || '';
  6504. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6505. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6506. }
  6507. function closePPPSecretModal() {
  6508. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6509. }
  6510. async function submitSavePPPSecret(e) {
  6511. e.preventDefault();
  6512. const id = document.getElementById('secret-modal-id').value;
  6513. const name = document.getElementById('secret-modal-name').value.trim();
  6514. const password = document.getElementById('secret-modal-password').value.trim();
  6515. const service = document.getElementById('secret-modal-service').value;
  6516. const profile = document.getElementById('secret-modal-profile').value;
  6517. const local = document.getElementById('secret-modal-local').value.trim();
  6518. const remote = document.getElementById('secret-modal-remote').value.trim();
  6519. const comment = document.getElementById('secret-modal-comment').value.trim();
  6520. const disabled = document.getElementById('secret-modal-disabled').checked;
  6521. try {
  6522. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6523. method: 'POST',
  6524. headers: { 'Content-Type': 'application/json' },
  6525. body: JSON.stringify({
  6526. id,
  6527. name,
  6528. password,
  6529. service,
  6530. profile,
  6531. local_address: local,
  6532. remote_address: remote,
  6533. comment,
  6534. disabled
  6535. })
  6536. });
  6537. if (res.ok) {
  6538. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6539. closePPPSecretModal();
  6540. loadPPPSecrets();
  6541. } else {
  6542. const err = await res.json();
  6543. showToast('Error', err.message, 'error');
  6544. }
  6545. } catch (err) {
  6546. showToast('Error', err.message, 'error');
  6547. }
  6548. }
  6549. async function togglePPPSecretState(id, disabled) {
  6550. try {
  6551. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6552. method: 'POST',
  6553. headers: { 'Content-Type': 'application/json' },
  6554. body: JSON.stringify({ disabled })
  6555. });
  6556. if (res.ok) {
  6557. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6558. loadPPPSecrets();
  6559. }
  6560. } catch (err) {
  6561. showToast('Error', err.message, 'error');
  6562. }
  6563. }
  6564. async function deletePPPSecret(id) {
  6565. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6566. try {
  6567. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6568. if (res.ok) {
  6569. showToast('Deleted', 'Secret account removed', 'success');
  6570. loadPPPSecrets();
  6571. }
  6572. } catch (err) {
  6573. showToast('Error', err.message, 'error');
  6574. }
  6575. }
  6576. // PPP Profile Modal handlers
  6577. function openAddPPPProfileModal() {
  6578. document.getElementById('profile-modal-name').value = '';
  6579. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6580. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6581. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6582. document.getElementById('profile-modal-encryption').value = 'required';
  6583. document.getElementById('profile-modal-onlyone').checked = true;
  6584. document.getElementById('profile-modal-comment').value = '';
  6585. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6586. }
  6587. function closePPPProfileModal() {
  6588. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6589. }
  6590. async function submitSavePPPProfile(e) {
  6591. e.preventDefault();
  6592. const name = document.getElementById('profile-modal-name').value.trim();
  6593. const local = document.getElementById('profile-modal-local').value.trim();
  6594. const remote = document.getElementById('profile-modal-remote').value.trim();
  6595. const dns = document.getElementById('profile-modal-dns').value.trim();
  6596. const enc = document.getElementById('profile-modal-encryption').value;
  6597. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6598. const comment = document.getElementById('profile-modal-comment').value.trim();
  6599. try {
  6600. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6601. method: 'POST',
  6602. headers: { 'Content-Type': 'application/json' },
  6603. body: JSON.stringify({
  6604. id: name,
  6605. name,
  6606. local_address: local,
  6607. remote_address: remote,
  6608. dns_servers: dns,
  6609. use_encryption: enc,
  6610. only_one: onlyone,
  6611. comment
  6612. })
  6613. });
  6614. if (res.ok) {
  6615. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6616. closePPPProfileModal();
  6617. loadPPPProfiles();
  6618. } else {
  6619. const err = await res.json();
  6620. showToast('Error', err.message, 'error');
  6621. }
  6622. } catch (err) {
  6623. showToast('Error', err.message, 'error');
  6624. }
  6625. }
  6626. async function deletePPPProfile(name) {
  6627. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6628. try {
  6629. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6630. if (res.ok) {
  6631. showToast('Deleted', 'Profile removed', 'success');
  6632. loadPPPProfiles();
  6633. } else {
  6634. const err = await res.json();
  6635. showToast('Error', err.message, 'error');
  6636. }
  6637. } catch (err) {
  6638. showToast('Error', err.message, 'error');
  6639. }
  6640. }
  6641. // Server Config submissions
  6642. async function savePPPoEServerConfig(e) {
  6643. e.preventDefault();
  6644. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6645. const name = document.getElementById('pppoe-server-name').value.trim();
  6646. const iface = document.getElementById('pppoe-server-iface').value;
  6647. const profile = document.getElementById('pppoe-server-profile').value;
  6648. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6649. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6650. try {
  6651. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6652. method: 'POST',
  6653. headers: { 'Content-Type': 'application/json' },
  6654. body: JSON.stringify({
  6655. enabled,
  6656. service_name: name,
  6657. interface: iface,
  6658. default_profile: profile,
  6659. max_mtu: mtu,
  6660. max_mru: mtu,
  6661. one_session_per_host: onesession
  6662. })
  6663. });
  6664. if (res.ok) {
  6665. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6666. loadPPPServers();
  6667. fetchData(false);
  6668. } else {
  6669. const err = await res.json();
  6670. showToast('Error', err.message, 'error');
  6671. }
  6672. } catch (err) {
  6673. showToast('Error', err.message, 'error');
  6674. }
  6675. }
  6676. async function savePPTPServerConfig(e) {
  6677. e.preventDefault();
  6678. const enabled = document.getElementById('pptp-server-enabled').checked;
  6679. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6680. const profile = document.getElementById('pptp-server-profile').value;
  6681. const mppe = document.getElementById('pptp-server-mppe').checked;
  6682. try {
  6683. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6684. method: 'POST',
  6685. headers: { 'Content-Type': 'application/json' },
  6686. body: JSON.stringify({
  6687. enabled,
  6688. port,
  6689. default_profile: profile,
  6690. require_mppe: mppe
  6691. })
  6692. });
  6693. if (res.ok) {
  6694. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6695. loadPPPServers();
  6696. fetchData(false);
  6697. } else {
  6698. const err = await res.json();
  6699. showToast('Error', err.message, 'error');
  6700. }
  6701. } catch (err) {
  6702. showToast('Error', err.message, 'error');
  6703. }
  6704. }
  6705. async function saveL2TPServerConfig(e) {
  6706. e.preventDefault();
  6707. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6708. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6709. const profile = document.getElementById('l2tp-server-profile').value;
  6710. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6711. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6712. try {
  6713. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6714. method: 'POST',
  6715. headers: { 'Content-Type': 'application/json' },
  6716. body: JSON.stringify({
  6717. enabled,
  6718. port,
  6719. default_profile: profile,
  6720. use_ipsec: useipsec,
  6721. ipsec_secret: psk
  6722. })
  6723. });
  6724. if (res.ok) {
  6725. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6726. loadPPPServers();
  6727. fetchData(false);
  6728. } else {
  6729. const err = await res.json();
  6730. showToast('Error', err.message, 'error');
  6731. }
  6732. } catch (err) {
  6733. showToast('Error', err.message, 'error');
  6734. }
  6735. }
  6736. // IPSec Server Modal
  6737. function openIPSecServerModal() {
  6738. loadPPPServers();
  6739. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6740. }
  6741. function closeIPSecServerModal() {
  6742. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6743. }
  6744. async function submitSaveIPSecServer(e) {
  6745. e.preventDefault();
  6746. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6747. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6748. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6749. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6750. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6751. try {
  6752. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6753. method: 'POST',
  6754. headers: { 'Content-Type': 'application/json' },
  6755. body: JSON.stringify({
  6756. enabled,
  6757. preshared_key: psk,
  6758. pool_address: pool,
  6759. dns_servers: dns,
  6760. local_subnet: subnet
  6761. })
  6762. });
  6763. if (res.ok) {
  6764. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6765. closeIPSecServerModal();
  6766. loadPPPServers();
  6767. fetchData(false);
  6768. } else {
  6769. const err = await res.json();
  6770. showToast('Error', err.message, 'error');
  6771. }
  6772. } catch (err) {
  6773. showToast('Error', err.message, 'error');
  6774. }
  6775. }
  6776. // WireGuard Client Config Viewer
  6777. let currentWGClientConf = '';
  6778. async function openWGClientConfModal(iface, clientIP) {
  6779. try {
  6780. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6781. method: 'POST',
  6782. headers: { 'Content-Type': 'application/json' },
  6783. body: JSON.stringify({
  6784. interface: iface,
  6785. address: clientIP || '10.10.0.2/32',
  6786. dns: '1.1.1.1, 8.8.8.8'
  6787. })
  6788. });
  6789. if (res.ok) {
  6790. const data = await res.json();
  6791. currentWGClientConf = data.config;
  6792. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6793. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6794. } else {
  6795. const err = await res.json();
  6796. showToast('Error', err.message, 'error');
  6797. }
  6798. } catch (err) {
  6799. showToast('Error', err.message, 'error');
  6800. }
  6801. }
  6802. function closeWGClientConfModal() {
  6803. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6804. }
  6805. function copyWGClientConf() {
  6806. if (!currentWGClientConf) return;
  6807. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6808. }
  6809. function downloadWGClientConf() {
  6810. if (!currentWGClientConf) return;
  6811. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6812. const a = document.createElement('a');
  6813. a.href = URL.createObjectURL(blob);
  6814. a.download = 'wireguard-client.conf';
  6815. document.body.appendChild(a);
  6816. a.click();
  6817. document.body.removeChild(a);
  6818. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6819. }
  6820. // =========================================================================
  6821. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6822. // =========================================================================
  6823. state.activeDynSubTab = 'bgp-peers';
  6824. state.activeBgpSubTab = 'bgp-peers';
  6825. state.activeOspfTab = 'instances';
  6826. state.bgpInstance = null;
  6827. state.bgpPeers = [];
  6828. state.bgpNets = [];
  6829. state.bgpRoutes = [];
  6830. state.ospfInstance = null;
  6831. state.ospfInstances = [];
  6832. state.ospfAreas = [];
  6833. state.ospfAreaRanges = [];
  6834. state.ospfTemplates = [];
  6835. state.ospfLiveInterfaces = [];
  6836. state.ospfStaticNbrs = [];
  6837. state.ospfNeighbors = [];
  6838. state.ospfLSA = [];
  6839. state.ospfRoutes = [];
  6840. state.selectedOspfRow = {
  6841. instances: null,
  6842. areas: null,
  6843. 'area-ranges': null,
  6844. templates: null,
  6845. interfaces: null,
  6846. 'static-nbrs': null,
  6847. neighbors: null,
  6848. lsa: null,
  6849. };
  6850. state.ospfSort = {
  6851. instances: { col: 'name', asc: true },
  6852. areas: { col: 'name', asc: true },
  6853. ranges: { col: 'area', asc: true },
  6854. templates: { col: 'interfaces', asc: true },
  6855. live_ifaces: { col: 'interface', asc: true },
  6856. snbrs: { col: 'address', asc: true },
  6857. neighbors: { col: 'address', asc: true },
  6858. lsa: { col: 'instance', asc: true },
  6859. };
  6860. function switchBgpSubTab(subTab) {
  6861. state.activeBgpSubTab = subTab;
  6862. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6863. tabs.forEach(t => {
  6864. const el = document.getElementById(`dyn-subtab-${t}`);
  6865. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6866. if (el) el.classList.toggle('hidden', t !== subTab);
  6867. if (btn) {
  6868. if (t === subTab) {
  6869. 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';
  6870. } else {
  6871. 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';
  6872. }
  6873. }
  6874. });
  6875. }
  6876. function switchOspfTab(tabName) {
  6877. state.activeOspfTab = tabName;
  6878. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6879. tabs.forEach(t => {
  6880. const pane = document.getElementById(`ospf-pane-${t}`);
  6881. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6882. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6883. if (btn) {
  6884. if (t === tabName) {
  6885. 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';
  6886. } else {
  6887. 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';
  6888. }
  6889. }
  6890. });
  6891. }
  6892. function switchOspfSubTab(tab) {
  6893. // Legacy alias
  6894. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6895. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6896. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6897. else switchOspfTab('instances');
  6898. }
  6899. function switchDynSubTab(subTab) {
  6900. if (subTab.startsWith('bgp')) {
  6901. if (state.activeTab !== 'bgp') navigate('bgp');
  6902. switchBgpSubTab(subTab);
  6903. } else if (subTab.startsWith('ospf')) {
  6904. if (state.activeTab !== 'ospf') navigate('ospf');
  6905. switchOspfTab('instances');
  6906. }
  6907. }
  6908. async function loadDynamicRouting(showToastMsg = false) {
  6909. try {
  6910. const fetchSafeJson = async (url) => {
  6911. try {
  6912. const r = await fetch(url);
  6913. return r.ok ? await r.json() : null;
  6914. } catch (e) {
  6915. return null;
  6916. }
  6917. };
  6918. const [
  6919. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6920. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6921. selectRules, commLists, asLists
  6922. ] = await Promise.all([
  6923. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6924. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6925. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6926. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6927. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6928. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6929. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6930. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6931. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6932. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6933. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6934. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6935. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6936. fetchSafeJson(`${API_BASE}/routing/filters`),
  6937. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6938. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6939. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6940. ]);
  6941. if (sum) state.dynSummary = sum;
  6942. if (bgpInst) state.bgpInstance = bgpInst;
  6943. if (bgpPeers) state.bgpPeers = bgpPeers;
  6944. if (bgpNets) state.bgpNets = bgpNets;
  6945. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6946. if (ospfInsts) state.ospfInstances = ospfInsts;
  6947. if (ospfAreas) state.ospfAreas = ospfAreas;
  6948. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6949. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6950. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6951. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6952. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6953. if (ospfLsa) state.ospfLSA = ospfLsa;
  6954. if (filters) state.routingFilters = filters;
  6955. if (selectRules) state.routingSelectRules = selectRules;
  6956. if (commLists) state.routingCommunityLists = commLists;
  6957. if (asLists) state.routingASLists = asLists;
  6958. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6959. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6960. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6961. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6962. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6963. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6964. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6965. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6966. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6967. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6968. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6969. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6970. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6971. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6972. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6973. } catch (err) {
  6974. console.error('Failed to load dynamic routing:', err);
  6975. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6976. }
  6977. }
  6978. async function loadOspfAll() {
  6979. await loadDynamicRouting(true);
  6980. }
  6981. function renderBgpStatusPill() {
  6982. const pill = document.getElementById('bgp-live-status-pill');
  6983. if (!pill) return;
  6984. const inst = state.bgpInstance;
  6985. if (!inst || !inst.enabled) {
  6986. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6987. pill.innerText = 'BGP DISABLED';
  6988. } else if (inst.running) {
  6989. 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';
  6990. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6991. } else {
  6992. 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';
  6993. pill.innerText = 'BGP STARTING...';
  6994. }
  6995. }
  6996. function renderBgpPeers() {
  6997. const tbody = document.getElementById('bgp-peers-table-body');
  6998. if (!tbody) return;
  6999. const empty = document.getElementById('bgp-peers-empty');
  7000. const countBadge = document.getElementById('bgp-peers-count-badge');
  7001. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7002. const peers = state.bgpPeers || [];
  7003. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7004. if (navBadge) navBadge.innerText = peers.length;
  7005. if (peers.length === 0) {
  7006. tbody.innerHTML = '';
  7007. if (empty) empty.classList.remove('hidden');
  7008. return;
  7009. }
  7010. if (empty) empty.classList.add('hidden');
  7011. tbody.innerHTML = peers.map(p => {
  7012. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7013. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7014. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7015. let stateBadge = '';
  7016. if (p.disabled) {
  7017. 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>';
  7018. } else if (p.state === 'Established') {
  7019. 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>';
  7020. } else if (p.state === 'Connect' || p.state === 'Active') {
  7021. 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>`;
  7022. } else {
  7023. 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>`;
  7024. }
  7025. return `
  7026. <tr class="hover:bg-slate-800/40 transition">
  7027. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7028. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7029. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7030. <td class="py-2.5 px-3">
  7031. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7032. ${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>`}
  7033. </td>
  7034. <td class="py-2.5 px-3">${stateBadge}</td>
  7035. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7036. <td class="py-2.5 px-3 text-slate-300">
  7037. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7038. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7039. </td>
  7040. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7041. ${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> ` : ''}
  7042. ${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>` : ''}
  7043. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7044. </td>
  7045. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7046. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7047. <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'}">
  7048. ${p.disabled ? 'Enable' : 'Disable'}
  7049. </button>
  7050. <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">
  7051. Edit
  7052. </button>
  7053. <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">
  7054. Delete
  7055. </button>
  7056. </td>
  7057. </tr>
  7058. `;
  7059. }).join('');
  7060. }
  7061. function renderBgpNetworks() {
  7062. const tbody = document.getElementById('bgp-nets-table-body');
  7063. if (!tbody) return;
  7064. const empty = document.getElementById('bgp-nets-empty');
  7065. const countBadge = document.getElementById('bgp-nets-count-badge');
  7066. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7067. const nets = state.bgpNets || [];
  7068. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7069. if (navBadge) navBadge.innerText = nets.length;
  7070. if (nets.length === 0) {
  7071. tbody.innerHTML = '';
  7072. if (empty) empty.classList.remove('hidden');
  7073. return;
  7074. }
  7075. if (empty) empty.classList.add('hidden');
  7076. tbody.innerHTML = nets.map(n => `
  7077. <tr class="hover:bg-slate-800/40 transition">
  7078. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7079. <td class="py-2.5 px-3">
  7080. ${n.disabled
  7081. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7082. : '<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>'}
  7083. </td>
  7084. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7085. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7086. <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">
  7087. Delete
  7088. </button>
  7089. </td>
  7090. </tr>
  7091. `).join('');
  7092. }
  7093. function renderBgpRoutes() {
  7094. const tbody = document.getElementById('bgp-routes-table-body');
  7095. if (!tbody) return;
  7096. const empty = document.getElementById('bgp-routes-empty');
  7097. const countBadge = document.getElementById('bgp-routes-count-badge');
  7098. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7099. const routes = state.bgpRoutes || [];
  7100. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7101. if (navBadge) navBadge.innerText = routes.length;
  7102. if (routes.length === 0) {
  7103. tbody.innerHTML = '';
  7104. if (empty) empty.classList.remove('hidden');
  7105. return;
  7106. }
  7107. if (empty) empty.classList.add('hidden');
  7108. tbody.innerHTML = routes.map(r => `
  7109. <tr class="hover:bg-slate-800/40 transition">
  7110. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7111. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7112. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7113. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7114. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7115. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7116. </tr>
  7117. `).join('');
  7118. }
  7119. // =========================================================================
  7120. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7121. // =========================================================================
  7122. function sortOspfTable(tab, col) {
  7123. if (!state.ospfSort) state.ospfSort = {};
  7124. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7125. if (state.ospfSort[tab].col === col) {
  7126. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7127. } else {
  7128. state.ospfSort[tab].col = col;
  7129. state.ospfSort[tab].asc = true;
  7130. }
  7131. const asc = state.ospfSort[tab].asc;
  7132. let list = [];
  7133. if (tab === 'instances') list = state.ospfInstances || [];
  7134. else if (tab === 'areas') list = state.ospfAreas || [];
  7135. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7136. else if (tab === 'templates') list = state.ospfTemplates || [];
  7137. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7138. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7139. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7140. else if (tab === 'lsa') list = state.ospfLSA || [];
  7141. list.sort((a, b) => {
  7142. let valA = a[col] ?? '';
  7143. let valB = b[col] ?? '';
  7144. if (typeof valA === 'number' && typeof valB === 'number') {
  7145. return asc ? valA - valB : valB - valA;
  7146. }
  7147. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7148. });
  7149. if (tab === 'instances') renderOspfInstances();
  7150. else if (tab === 'areas') renderOspfAreas();
  7151. else if (tab === 'ranges') renderOspfAreaRanges();
  7152. else if (tab === 'templates') renderOspfTemplates();
  7153. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7154. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7155. else if (tab === 'neighbors') renderOspfNeighbors();
  7156. else if (tab === 'lsa') renderOspfLSA();
  7157. }
  7158. function selectOspfRow(tab, id) {
  7159. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7160. state.selectedOspfRow[tab] = id;
  7161. if (tab === 'instances') {
  7162. renderOspfInstances();
  7163. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7164. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7165. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7166. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7167. if (btnEn) btnEn.disabled = false;
  7168. if (btnDis) btnDis.disabled = false;
  7169. if (btnRem) btnRem.disabled = false;
  7170. if (btnCom) btnCom.disabled = false;
  7171. } else if (tab === 'areas') {
  7172. renderOspfAreas();
  7173. const btnEn = document.getElementById('btn-ospf-area-enable');
  7174. const btnDis = document.getElementById('btn-ospf-area-disable');
  7175. const btnRem = document.getElementById('btn-ospf-area-remove');
  7176. const btnCom = document.getElementById('btn-ospf-area-comment');
  7177. if (btnEn) btnEn.disabled = false;
  7178. if (btnDis) btnDis.disabled = false;
  7179. if (btnRem) btnRem.disabled = false;
  7180. if (btnCom) btnCom.disabled = false;
  7181. } else if (tab === 'ranges') {
  7182. renderOspfAreaRanges();
  7183. const btnEn = document.getElementById('btn-ospf-range-enable');
  7184. const btnDis = document.getElementById('btn-ospf-range-disable');
  7185. const btnRem = document.getElementById('btn-ospf-range-remove');
  7186. const btnCom = document.getElementById('btn-ospf-range-comment');
  7187. if (btnEn) btnEn.disabled = false;
  7188. if (btnDis) btnDis.disabled = false;
  7189. if (btnRem) btnRem.disabled = false;
  7190. if (btnCom) btnCom.disabled = false;
  7191. } else if (tab === 'templates') {
  7192. renderOspfTemplates();
  7193. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7194. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7195. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7196. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7197. if (btnEn) btnEn.disabled = false;
  7198. if (btnDis) btnDis.disabled = false;
  7199. if (btnRem) btnRem.disabled = false;
  7200. if (btnCom) btnCom.disabled = false;
  7201. } else if (tab === 'snbrs') {
  7202. renderOspfStaticNbrs();
  7203. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7204. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7205. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7206. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7207. if (btnEn) btnEn.disabled = false;
  7208. if (btnDis) btnDis.disabled = false;
  7209. if (btnRem) btnRem.disabled = false;
  7210. if (btnCom) btnCom.disabled = false;
  7211. }
  7212. }
  7213. // TAB 1: INSTANCES
  7214. function renderOspfInstances() {
  7215. const tbody = document.getElementById('ospf-instances-table-body');
  7216. if (!tbody) return;
  7217. const countEl = document.getElementById('ospf-instances-footer-count');
  7218. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7219. let list = state.ospfInstances || [];
  7220. if (filter) {
  7221. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7222. }
  7223. if (countEl) countEl.innerText = list.length;
  7224. const selId = state.selectedOspfRow?.instances;
  7225. tbody.innerHTML = list.map((inst, idx) => {
  7226. const isSel = inst.id === selId;
  7227. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7228. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7229. return `
  7230. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7231. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7232. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7233. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7234. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7235. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7236. </td>
  7237. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7238. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7239. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7240. </tr>
  7241. `;
  7242. }).join('');
  7243. }
  7244. // TAB 2: AREAS
  7245. function renderOspfAreas() {
  7246. const tbody = document.getElementById('ospf-areas-table-body');
  7247. if (!tbody) return;
  7248. const countEl = document.getElementById('ospf-areas-footer-count');
  7249. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7250. let list = state.ospfAreas || [];
  7251. if (filter) {
  7252. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7253. }
  7254. if (countEl) countEl.innerText = list.length;
  7255. const selId = state.selectedOspfRow?.areas;
  7256. tbody.innerHTML = list.map((a, idx) => {
  7257. const isSel = a.id === selId;
  7258. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7259. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7260. return `
  7261. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7262. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7263. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7264. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7265. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7266. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7267. </td>
  7268. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7269. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7270. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7271. </tr>
  7272. `;
  7273. }).join('');
  7274. }
  7275. // TAB 3: AREA RANGES
  7276. function renderOspfAreaRanges() {
  7277. const tbody = document.getElementById('ospf-ranges-table-body');
  7278. if (!tbody) return;
  7279. const countEl = document.getElementById('ospf-ranges-footer-count');
  7280. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7281. let list = state.ospfAreaRanges || [];
  7282. if (filter) {
  7283. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7284. }
  7285. if (countEl) countEl.innerText = list.length;
  7286. const selId = state.selectedOspfRow?.['area-ranges'];
  7287. tbody.innerHTML = list.map((r, idx) => {
  7288. const isSel = r.id === selId;
  7289. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7290. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7291. return `
  7292. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7293. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7294. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7295. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7296. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7297. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7298. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7299. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7300. </tr>
  7301. `;
  7302. }).join('');
  7303. }
  7304. // TAB 4: INTERFACE TEMPLATES
  7305. function renderOspfTemplates() {
  7306. const tbody = document.getElementById('ospf-templates-table-body');
  7307. if (!tbody) return;
  7308. const countEl = document.getElementById('ospf-templates-footer-count');
  7309. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7310. let list = state.ospfTemplates || [];
  7311. if (filter) {
  7312. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7313. }
  7314. if (countEl) countEl.innerText = list.length;
  7315. const selId = state.selectedOspfRow?.templates;
  7316. tbody.innerHTML = list.map((t, idx) => {
  7317. const isSel = t.id === selId;
  7318. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7319. const ifaces = t.interfaces || t.interface || 'all';
  7320. const nets = t.networks || t.network || '';
  7321. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7322. return `
  7323. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7324. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7325. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7326. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7327. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7328. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7329. </td>
  7330. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7331. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7332. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7333. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7334. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7335. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7336. </tr>
  7337. `;
  7338. }).join('');
  7339. }
  7340. // TAB 5: LIVE INTERFACES
  7341. function renderOspfLiveInterfaces() {
  7342. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7343. if (!tbody) return;
  7344. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7345. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7346. let list = state.ospfLiveInterfaces || [];
  7347. if (filter) {
  7348. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7349. }
  7350. if (countEl) countEl.innerText = list.length;
  7351. tbody.innerHTML = list.map(i => `
  7352. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7353. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7354. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7355. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7356. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7357. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7358. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7359. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7360. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7361. </tr>
  7362. `).join('');
  7363. }
  7364. // TAB 6: STATIC NEIGHBORS
  7365. function renderOspfStaticNbrs() {
  7366. const tbody = document.getElementById('ospf-snbrs-table-body');
  7367. if (!tbody) return;
  7368. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7369. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7370. let list = state.ospfStaticNbrs || [];
  7371. if (filter) {
  7372. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7373. }
  7374. if (countEl) countEl.innerText = list.length;
  7375. const selId = state.selectedOspfRow?.['static-nbrs'];
  7376. tbody.innerHTML = list.map((n, idx) => {
  7377. const isSel = n.id === selId;
  7378. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7379. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7380. return `
  7381. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7382. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7383. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7384. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7385. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7386. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7387. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7388. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7389. </tr>
  7390. `;
  7391. }).join('');
  7392. }
  7393. // TAB 7: LIVE NEIGHBORS
  7394. function renderOspfNeighbors() {
  7395. const tbody = document.getElementById('ospf-neighbors-table-body');
  7396. if (!tbody) return;
  7397. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7398. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7399. let list = state.ospfNeighbors || [];
  7400. if (filter) {
  7401. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7402. }
  7403. if (countEl) countEl.innerText = list.length;
  7404. tbody.innerHTML = list.map(n => `
  7405. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7406. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7407. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7408. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7409. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7410. </td>
  7411. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7412. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7413. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7414. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7415. </tr>
  7416. `).join('');
  7417. }
  7418. // TAB 8: LINK-STATE DATABASE (LSA)
  7419. function renderOspfLSA() {
  7420. const tbody = document.getElementById('ospf-lsa-table-body');
  7421. if (!tbody) return;
  7422. const countEl = document.getElementById('ospf-lsa-footer-count');
  7423. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7424. let list = state.ospfLSA || [];
  7425. if (filter) {
  7426. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7427. }
  7428. if (countEl) countEl.innerText = list.length;
  7429. tbody.innerHTML = list.map(l => `
  7430. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7431. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7432. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7433. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7434. </td>
  7435. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7436. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7437. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7438. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7439. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7440. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7441. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7442. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7443. </tr>
  7444. `).join('');
  7445. }
  7446. function renderOspfStatusPill() {
  7447. // Maintained for backward compatibility
  7448. const pill = document.getElementById('ospf-live-status-pill');
  7449. if (!pill) return;
  7450. 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';
  7451. pill.innerText = 'OSPF ACTIVE';
  7452. }
  7453. function renderOspfInterfaces() {
  7454. renderOspfTemplates();
  7455. }
  7456. function renderOspfRoutes() {
  7457. // Routes retained in background
  7458. }
  7459. // BGP Modals & Actions
  7460. function openBgpInstanceModal() {
  7461. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7462. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7463. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7464. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7465. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7466. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7467. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7468. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7469. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7470. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7471. }
  7472. function closeBgpInstanceModal() {
  7473. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7474. }
  7475. async function submitBgpInstance(e) {
  7476. e.preventDefault();
  7477. const payload = {
  7478. enabled: document.getElementById('modal-bgp-enabled').checked,
  7479. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7480. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7481. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7482. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7483. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7484. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7485. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7486. };
  7487. try {
  7488. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7489. method: 'POST',
  7490. headers: { 'Content-Type': 'application/json' },
  7491. body: JSON.stringify(payload)
  7492. });
  7493. if (res.ok) {
  7494. closeBgpInstanceModal();
  7495. showToast('Success', 'BGP instance configuration updated', 'success');
  7496. loadDynamicRouting();
  7497. } else {
  7498. const err = await res.json();
  7499. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7500. }
  7501. } catch (err) {
  7502. showToast('Error', err.message, 'error');
  7503. }
  7504. }
  7505. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7506. function switchBgpPeerModalTab(tab) {
  7507. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7508. tabs.forEach(t => {
  7509. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7510. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7511. if (t === tab) {
  7512. if (pane) pane.classList.remove('hidden');
  7513. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7514. } else {
  7515. if (pane) pane.classList.add('hidden');
  7516. 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';
  7517. }
  7518. });
  7519. }
  7520. function addOutputNetworkRow(val = '') {
  7521. const container = document.getElementById('modal-bgp-output-networks-container');
  7522. if (!container) return;
  7523. const row = document.createElement('div');
  7524. row.className = 'flex items-center gap-2 output-net-row';
  7525. row.innerHTML = `
  7526. <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">
  7527. <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>
  7528. `;
  7529. container.appendChild(row);
  7530. }
  7531. function parseBgpTime(val) {
  7532. if (!val) return 0;
  7533. val = String(val).trim();
  7534. if (val.includes(':')) {
  7535. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7536. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7537. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7538. }
  7539. return parseInt(val, 10) || 0;
  7540. }
  7541. function formatBgpTime(secs) {
  7542. if (!secs || secs <= 0) return '00:00:00';
  7543. const h = Math.floor(secs / 3600);
  7544. const m = Math.floor((secs % 3600) / 60);
  7545. const s = secs % 60;
  7546. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7547. }
  7548. function populateBgpRoutingTables() {
  7549. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7550. if (!sel) return;
  7551. const cur = sel.value || 'main';
  7552. sel.innerHTML = '<option value="main">main</option>';
  7553. (state.routingTables || []).forEach(t => {
  7554. if (t.name !== 'main') {
  7555. const opt = document.createElement('option');
  7556. opt.value = t.name;
  7557. opt.innerText = t.name;
  7558. sel.appendChild(opt);
  7559. }
  7560. });
  7561. sel.value = cur;
  7562. }
  7563. function openAddBgpPeerModal() {
  7564. document.getElementById('bgp-peer-form').reset();
  7565. document.getElementById('modal-bgp-peer-id').value = '';
  7566. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7567. // General Tab
  7568. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7569. document.getElementById('modal-bgp-peer-comment').value = '';
  7570. document.getElementById('modal-bgp-peer-name').value = '';
  7571. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7572. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7573. document.getElementById('modal-bgp-peer-local-as').value = '';
  7574. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7575. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7576. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7577. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7578. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7579. document.getElementById('modal-bgp-peer-router-id').value = '';
  7580. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7581. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7582. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7583. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7584. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7585. document.getElementById('modal-bgp-peer-local-port').value = '';
  7586. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7587. document.getElementById('modal-bgp-peer-password').value = '';
  7588. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7589. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7590. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7591. document.getElementById('modal-bgp-peer-connect').checked = true;
  7592. document.getElementById('modal-bgp-peer-listen').checked = true;
  7593. // Extra Tab
  7594. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7595. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7596. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7597. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7598. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7599. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7600. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7601. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7602. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7603. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7604. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7605. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7606. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7607. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7608. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7609. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7610. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7611. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7612. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7613. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7614. // Attributes Tab
  7615. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7616. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7617. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7618. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7619. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7620. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7621. // Filter Tab
  7622. populateFilterChainsDatalist();
  7623. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7624. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7625. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7626. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7627. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7628. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7629. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7630. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7631. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7632. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7633. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7634. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7635. populateBgpRoutingTables();
  7636. const container = document.getElementById('modal-bgp-output-networks-container');
  7637. if (container) {
  7638. container.innerHTML = '';
  7639. addOutputNetworkRow('');
  7640. }
  7641. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7642. if (removeBtn) removeBtn.classList.add('hidden');
  7643. switchBgpPeerModalTab('general');
  7644. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7645. }
  7646. function populateFilterChainsDatalist() {
  7647. const dl = document.getElementById('filter-chains-list');
  7648. if (!dl) return;
  7649. const chains = new Set();
  7650. (state.routingFilters || []).forEach(f => {
  7651. if (f.chain) chains.add(f.chain);
  7652. });
  7653. if (chains.size === 0) {
  7654. chains.add('awmn');
  7655. chains.add('bgp-in');
  7656. chains.add('bgp-out');
  7657. }
  7658. dl.innerHTML = '';
  7659. chains.forEach(c => {
  7660. const opt = document.createElement('option');
  7661. opt.value = c;
  7662. dl.appendChild(opt);
  7663. });
  7664. }
  7665. function openEditBgpPeerModal(id) {
  7666. const p = (state.bgpPeers || []).find(item => item.id === id);
  7667. if (!p) return;
  7668. populateBgpRoutingTables();
  7669. populateFilterChainsDatalist();
  7670. document.getElementById('modal-bgp-peer-id').value = p.id;
  7671. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7672. // General Tab
  7673. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7674. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7675. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7676. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7677. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7678. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7679. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7680. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7681. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7682. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7683. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7684. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7685. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7686. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7687. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7688. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7689. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7690. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7691. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7692. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7693. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7694. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7695. // Extra Tab
  7696. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7697. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7698. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7699. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7700. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7701. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7702. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7703. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7704. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7705. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7706. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7707. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7708. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7709. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  7710. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7711. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7712. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7713. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7714. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7715. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7716. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7717. // Attributes Tab
  7718. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7719. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7720. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7721. 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;
  7722. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7723. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7724. // Filter Tab
  7725. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7726. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7727. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7728. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  7729. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  7730. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7731. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  7732. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  7733. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7734. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7735. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7736. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7737. // Output Networks
  7738. const container = document.getElementById('modal-bgp-output-networks-container');
  7739. if (container) {
  7740. container.innerHTML = '';
  7741. if (p.output_networks && p.output_networks.length > 0) {
  7742. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7743. } else {
  7744. addOutputNetworkRow('');
  7745. }
  7746. }
  7747. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7748. if (removeBtn) removeBtn.classList.remove('hidden');
  7749. switchBgpPeerModalTab('general');
  7750. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7751. }
  7752. function copyCurrentBgpPeer() {
  7753. document.getElementById('modal-bgp-peer-id').value = '';
  7754. const nameEl = document.getElementById('modal-bgp-peer-name');
  7755. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7756. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7757. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7758. if (removeBtn) removeBtn.classList.add('hidden');
  7759. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7760. }
  7761. function removeCurrentBgpPeer() {
  7762. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7763. if (!id) return;
  7764. deleteBgpPeer(id);
  7765. closeBgpPeerModal();
  7766. }
  7767. function closeBgpPeerModal() {
  7768. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7769. }
  7770. function getBgpPeerFormData() {
  7771. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7772. const outputNetworks = [];
  7773. netInputs.forEach(inp => {
  7774. const v = inp.value.trim();
  7775. if (v) outputNetworks.push(v);
  7776. });
  7777. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7778. return {
  7779. id: document.getElementById('modal-bgp-peer-id').value,
  7780. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7781. enabled: enabled,
  7782. disabled: !enabled,
  7783. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7784. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7785. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7786. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7787. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7788. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7789. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7790. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7791. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7792. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7793. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7794. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7795. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7796. password: document.getElementById('modal-bgp-peer-password').value,
  7797. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7798. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7799. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7800. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7801. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7802. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7803. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7804. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7805. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7806. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7807. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7808. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7809. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7810. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7811. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7812. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7813. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7814. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7815. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7816. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7817. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7818. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7819. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7820. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7821. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7822. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7823. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7824. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7825. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7826. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7827. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7828. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7829. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7830. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7831. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7832. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7833. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7834. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7835. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7836. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7837. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7838. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7839. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7840. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7841. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7842. output_networks: outputNetworks
  7843. };
  7844. }
  7845. async function submitBgpPeer(e) {
  7846. if (e) e.preventDefault();
  7847. const payload = getBgpPeerFormData();
  7848. try {
  7849. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7850. method: 'POST',
  7851. headers: { 'Content-Type': 'application/json' },
  7852. body: JSON.stringify(payload)
  7853. });
  7854. if (res.ok) {
  7855. closeBgpPeerModal();
  7856. showToast('Success', 'BGP Connection saved', 'success');
  7857. loadDynamicRouting();
  7858. } else {
  7859. const err = await res.json();
  7860. showToast('Error', err.error || 'Failed to save peer', 'error');
  7861. }
  7862. } catch (err) {
  7863. showToast('Error', err.message, 'error');
  7864. }
  7865. }
  7866. async function applyBgpPeerModal(e) {
  7867. if (e) e.preventDefault();
  7868. const payload = getBgpPeerFormData();
  7869. try {
  7870. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7871. method: 'POST',
  7872. headers: { 'Content-Type': 'application/json' },
  7873. body: JSON.stringify(payload)
  7874. });
  7875. if (res.ok) {
  7876. const data = await res.json();
  7877. if (data.peer && data.peer.id) {
  7878. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7879. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7880. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7881. }
  7882. showToast('Applied', 'BGP Connection applied', 'success');
  7883. loadDynamicRouting();
  7884. } else {
  7885. const err = await res.json();
  7886. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7887. }
  7888. } catch (err) {
  7889. showToast('Error', err.message, 'error');
  7890. }
  7891. }
  7892. async function deleteBgpPeer(id) {
  7893. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7894. try {
  7895. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7896. if (res.ok) {
  7897. showToast('Deleted', 'BGP peer removed', 'success');
  7898. loadDynamicRouting();
  7899. }
  7900. } catch (err) {
  7901. showToast('Error', err.message, 'error');
  7902. }
  7903. }
  7904. async function toggleBgpPeerState(id, disabled) {
  7905. try {
  7906. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7907. method: 'POST',
  7908. headers: { 'Content-Type': 'application/json' },
  7909. body: JSON.stringify({ disabled })
  7910. });
  7911. if (res.ok) {
  7912. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7913. loadDynamicRouting();
  7914. }
  7915. } catch (err) {
  7916. showToast('Error', err.message, 'error');
  7917. }
  7918. }
  7919. function openAddBgpNetworkModal() {
  7920. document.getElementById('bgp-network-form').reset();
  7921. document.getElementById('modal-bgp-net-id').value = '';
  7922. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7923. }
  7924. function closeBgpNetworkModal() {
  7925. document.getElementById('bgp-network-modal').classList.add('hidden');
  7926. }
  7927. async function submitBgpNetwork(e) {
  7928. e.preventDefault();
  7929. const payload = {
  7930. id: document.getElementById('modal-bgp-net-id').value,
  7931. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7932. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7933. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7934. };
  7935. try {
  7936. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7937. method: 'POST',
  7938. headers: { 'Content-Type': 'application/json' },
  7939. body: JSON.stringify(payload)
  7940. });
  7941. if (res.ok) {
  7942. closeBgpNetworkModal();
  7943. showToast('Success', 'BGP network advertisement saved', 'success');
  7944. loadDynamicRouting();
  7945. } else {
  7946. const err = await res.json();
  7947. showToast('Error', err.error || 'Failed to save network', 'error');
  7948. }
  7949. } catch (err) {
  7950. showToast('Error', err.message, 'error');
  7951. }
  7952. }
  7953. async function deleteBgpNetwork(id) {
  7954. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7955. try {
  7956. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7957. if (res.ok) {
  7958. showToast('Deleted', 'Network advertisement removed', 'success');
  7959. loadDynamicRouting();
  7960. }
  7961. } catch (err) {
  7962. showToast('Error', err.message, 'error');
  7963. }
  7964. }
  7965. // =========================================================================
  7966. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7967. // =========================================================================
  7968. // --- 1. OSPF INSTANCE ---
  7969. function openOspfInstanceModal(id = null) {
  7970. const isEdit = !!id;
  7971. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7972. id: '',
  7973. name: 'Default',
  7974. version: 2,
  7975. vrf: 'main',
  7976. router_id: '192.168.131.56',
  7977. routing_table: 'main',
  7978. enabled: true,
  7979. redistribute_connected: false,
  7980. redistribute_static: true,
  7981. redistribute_bgp: false,
  7982. comment: ''
  7983. };
  7984. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7985. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7986. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7987. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7988. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7989. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7990. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7991. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7992. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7993. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7994. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7995. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7996. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7997. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7998. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7999. }
  8000. function openEditOspfInstanceModal(id) {
  8001. openOspfInstanceModal(id);
  8002. }
  8003. function closeOspfInstanceModal() {
  8004. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8005. }
  8006. async function submitOspfInstance(e) {
  8007. if (e) e.preventDefault();
  8008. const payload = {
  8009. id: document.getElementById('modal-ospf-inst-id').value,
  8010. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8011. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8012. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8013. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8014. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8015. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8016. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8017. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8018. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8019. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8020. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8021. };
  8022. try {
  8023. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8024. method: 'POST',
  8025. headers: { 'Content-Type': 'application/json' },
  8026. body: JSON.stringify(payload)
  8027. });
  8028. if (res.ok) {
  8029. closeOspfInstanceModal();
  8030. showToast('Saved', 'OSPF instance updated', 'success');
  8031. loadDynamicRouting();
  8032. } else {
  8033. const err = await res.json();
  8034. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8035. }
  8036. } catch (err) {
  8037. showToast('Error', err.message, 'error');
  8038. }
  8039. }
  8040. function applyOspfInstanceForm() {
  8041. submitOspfInstance(null);
  8042. }
  8043. function copyOspfInstance() {
  8044. document.getElementById('modal-ospf-inst-id').value = '';
  8045. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8046. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8047. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8048. }
  8049. async function deleteCurrentOspfInstance() {
  8050. const id = document.getElementById('modal-ospf-inst-id').value;
  8051. if (!id) return;
  8052. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8053. try {
  8054. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8055. if (res.ok) {
  8056. closeOspfInstanceModal();
  8057. showToast('Removed', 'OSPF instance deleted', 'success');
  8058. loadDynamicRouting();
  8059. }
  8060. } catch (err) {
  8061. showToast('Error', err.message, 'error');
  8062. }
  8063. }
  8064. async function enableSelectedOspfInstance() {
  8065. const id = state.selectedOspfRow?.instances;
  8066. if (!id) return;
  8067. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8068. method: 'POST',
  8069. headers: { 'Content-Type': 'application/json' },
  8070. body: JSON.stringify({ disabled: false })
  8071. });
  8072. loadDynamicRouting();
  8073. }
  8074. async function disableSelectedOspfInstance() {
  8075. const id = state.selectedOspfRow?.instances;
  8076. if (!id) return;
  8077. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8078. method: 'POST',
  8079. headers: { 'Content-Type': 'application/json' },
  8080. body: JSON.stringify({ disabled: true })
  8081. });
  8082. loadDynamicRouting();
  8083. }
  8084. async function removeSelectedOspfInstance() {
  8085. const id = state.selectedOspfRow?.instances;
  8086. if (!id) return;
  8087. if (!confirm('Delete selected OSPF instance?')) return;
  8088. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8089. loadDynamicRouting();
  8090. }
  8091. async function promptCommentOspfInstance() {
  8092. const id = state.selectedOspfRow?.instances;
  8093. if (!id) return;
  8094. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8095. if (!inst) return;
  8096. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8097. if (comment === null) return;
  8098. inst.comment = comment;
  8099. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8100. method: 'POST',
  8101. headers: { 'Content-Type': 'application/json' },
  8102. body: JSON.stringify(inst)
  8103. });
  8104. loadDynamicRouting();
  8105. }
  8106. // --- 2. OSPF AREA ---
  8107. function populateOspfAreaDropdowns() {
  8108. const instSelect = document.getElementById('modal-ospf-area-instance');
  8109. if (instSelect) {
  8110. const cur = instSelect.value;
  8111. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8112. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8113. if (cur) instSelect.value = cur;
  8114. }
  8115. }
  8116. function openOspfAreaModal(id = null) {
  8117. const isEdit = !!id;
  8118. populateOspfAreaDropdowns();
  8119. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8120. id: '',
  8121. name: 'Default',
  8122. instance: 'Default',
  8123. area_id: '0.0.0.0',
  8124. area_type: 'default',
  8125. default_cost: 1,
  8126. no_summaries: false,
  8127. disabled: false,
  8128. comment: ''
  8129. };
  8130. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8131. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8132. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8133. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8134. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8135. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8136. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8137. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8138. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8139. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8140. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8141. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8142. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8143. }
  8144. function openEditOspfAreaModal(id) {
  8145. openOspfAreaModal(id);
  8146. }
  8147. function closeOspfAreaModal() {
  8148. document.getElementById('ospf-area-modal').classList.add('hidden');
  8149. }
  8150. async function submitOspfArea(e) {
  8151. if (e) e.preventDefault();
  8152. const payload = {
  8153. id: document.getElementById('modal-ospf-area-id').value,
  8154. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8155. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8156. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8157. area_type: document.getElementById('modal-ospf-area-type').value,
  8158. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8159. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8160. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8161. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8162. };
  8163. try {
  8164. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8165. method: 'POST',
  8166. headers: { 'Content-Type': 'application/json' },
  8167. body: JSON.stringify(payload)
  8168. });
  8169. if (res.ok) {
  8170. closeOspfAreaModal();
  8171. showToast('Saved', 'OSPF area saved', 'success');
  8172. loadDynamicRouting();
  8173. } else {
  8174. const err = await res.json();
  8175. showToast('Error', err.error || 'Failed to save area', 'error');
  8176. }
  8177. } catch (err) {
  8178. showToast('Error', err.message, 'error');
  8179. }
  8180. }
  8181. function applyOspfAreaForm() {
  8182. submitOspfArea(null);
  8183. }
  8184. function copyOspfArea() {
  8185. document.getElementById('modal-ospf-area-id').value = '';
  8186. document.getElementById('modal-ospf-area-name').value += '-copy';
  8187. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8188. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8189. }
  8190. async function deleteCurrentOspfArea() {
  8191. const id = document.getElementById('modal-ospf-area-id').value;
  8192. if (!id) return;
  8193. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8194. try {
  8195. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8196. if (res.ok) {
  8197. closeOspfAreaModal();
  8198. showToast('Removed', 'OSPF area deleted', 'success');
  8199. loadDynamicRouting();
  8200. }
  8201. } catch (err) {
  8202. showToast('Error', err.message, 'error');
  8203. }
  8204. }
  8205. async function enableSelectedOspfArea() {
  8206. const id = state.selectedOspfRow?.areas;
  8207. if (!id) return;
  8208. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8209. method: 'POST',
  8210. headers: { 'Content-Type': 'application/json' },
  8211. body: JSON.stringify({ disabled: false })
  8212. });
  8213. loadDynamicRouting();
  8214. }
  8215. async function disableSelectedOspfArea() {
  8216. const id = state.selectedOspfRow?.areas;
  8217. if (!id) return;
  8218. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8219. method: 'POST',
  8220. headers: { 'Content-Type': 'application/json' },
  8221. body: JSON.stringify({ disabled: true })
  8222. });
  8223. loadDynamicRouting();
  8224. }
  8225. async function removeSelectedOspfArea() {
  8226. const id = state.selectedOspfRow?.areas;
  8227. if (!id) return;
  8228. if (!confirm('Delete selected OSPF area?')) return;
  8229. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8230. loadDynamicRouting();
  8231. }
  8232. async function promptCommentOspfArea() {
  8233. const id = state.selectedOspfRow?.areas;
  8234. if (!id) return;
  8235. const area = (state.ospfAreas || []).find(a => a.id === id);
  8236. if (!area) return;
  8237. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8238. if (comment === null) return;
  8239. area.comment = comment;
  8240. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8241. method: 'POST',
  8242. headers: { 'Content-Type': 'application/json' },
  8243. body: JSON.stringify(area)
  8244. });
  8245. loadDynamicRouting();
  8246. }
  8247. // --- 3. OSPF AREA RANGE ---
  8248. function populateAreaRangeDropdowns() {
  8249. const select = document.getElementById('modal-ospf-range-area');
  8250. if (select) {
  8251. const cur = select.value;
  8252. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8253. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8254. if (cur) select.value = cur;
  8255. }
  8256. }
  8257. function openOspfAreaRangeModal(id = null) {
  8258. const isEdit = !!id;
  8259. populateAreaRangeDropdowns();
  8260. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8261. id: '',
  8262. area: 'Default',
  8263. prefix: '',
  8264. cost: 1,
  8265. advertise: true,
  8266. disabled: false,
  8267. comment: ''
  8268. };
  8269. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8270. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8271. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8272. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8273. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8274. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8275. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8276. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8277. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8278. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8279. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8280. }
  8281. function openEditOspfAreaRangeModal(id) {
  8282. openOspfAreaRangeModal(id);
  8283. }
  8284. function closeOspfAreaRangeModal() {
  8285. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8286. }
  8287. async function submitOspfAreaRange(e) {
  8288. if (e) e.preventDefault();
  8289. const payload = {
  8290. id: document.getElementById('modal-ospf-range-id').value,
  8291. area: document.getElementById('modal-ospf-range-area').value,
  8292. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8293. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8294. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8295. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8296. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8297. };
  8298. try {
  8299. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8300. method: 'POST',
  8301. headers: { 'Content-Type': 'application/json' },
  8302. body: JSON.stringify(payload)
  8303. });
  8304. if (res.ok) {
  8305. closeOspfAreaRangeModal();
  8306. showToast('Saved', 'Area range saved', 'success');
  8307. loadDynamicRouting();
  8308. } else {
  8309. const err = await res.json();
  8310. showToast('Error', err.error || 'Failed to save area range', 'error');
  8311. }
  8312. } catch (err) {
  8313. showToast('Error', err.message, 'error');
  8314. }
  8315. }
  8316. function applyOspfAreaRangeForm() {
  8317. submitOspfAreaRange(null);
  8318. }
  8319. async function deleteCurrentOspfAreaRange() {
  8320. const id = document.getElementById('modal-ospf-range-id').value;
  8321. if (!id) return;
  8322. if (!confirm('Delete this area range?')) return;
  8323. try {
  8324. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8325. closeOspfAreaRangeModal();
  8326. showToast('Removed', 'Area range removed', 'success');
  8327. loadDynamicRouting();
  8328. } catch (err) {
  8329. showToast('Error', err.message, 'error');
  8330. }
  8331. }
  8332. async function enableSelectedOspfAreaRange() {
  8333. const id = state.selectedOspfRow?.['area-ranges'];
  8334. if (!id) return;
  8335. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8336. if (!r) return;
  8337. r.disabled = false;
  8338. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8339. loadDynamicRouting();
  8340. }
  8341. async function disableSelectedOspfAreaRange() {
  8342. const id = state.selectedOspfRow?.['area-ranges'];
  8343. if (!id) return;
  8344. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8345. if (!r) return;
  8346. r.disabled = true;
  8347. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8348. loadDynamicRouting();
  8349. }
  8350. async function removeSelectedOspfAreaRange() {
  8351. const id = state.selectedOspfRow?.['area-ranges'];
  8352. if (!id) return;
  8353. if (!confirm('Delete selected area range?')) return;
  8354. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8355. loadDynamicRouting();
  8356. }
  8357. async function promptCommentOspfAreaRange() {
  8358. const id = state.selectedOspfRow?.['area-ranges'];
  8359. if (!id) return;
  8360. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8361. if (!r) return;
  8362. const comment = prompt('Enter comment for area range:', r.comment || '');
  8363. if (comment === null) return;
  8364. r.comment = comment;
  8365. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8366. loadDynamicRouting();
  8367. }
  8368. // --- 4. OSPF INTERFACE TEMPLATE ---
  8369. function switchOspfTemplateTab(tab) {
  8370. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8371. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8372. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8373. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8374. if (tab === 'general') {
  8375. if (tabGen) tabGen.classList.remove('hidden');
  8376. if (tabAuth) tabAuth.classList.add('hidden');
  8377. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8378. 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';
  8379. } else {
  8380. if (tabGen) tabGen.classList.add('hidden');
  8381. if (tabAuth) tabAuth.classList.remove('hidden');
  8382. 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';
  8383. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8384. }
  8385. }
  8386. function populateTemplateAreaDropdowns() {
  8387. const select = document.getElementById('modal-ospf-tmpl-area');
  8388. if (select) {
  8389. const cur = select.value;
  8390. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8391. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8392. if (cur) select.value = cur;
  8393. }
  8394. }
  8395. function openOspfTemplateModal(id = null) {
  8396. const isEdit = !!id;
  8397. populateTemplateAreaDropdowns();
  8398. switchOspfTemplateTab('general');
  8399. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8400. id: '',
  8401. interfaces: '',
  8402. area: 'Default',
  8403. networks: '',
  8404. network_type: 'broadcast',
  8405. cost: 1,
  8406. priority: 128,
  8407. passive: false,
  8408. hello_interval: 10,
  8409. dead_interval: 40,
  8410. auth: 'none',
  8411. auth_key: '',
  8412. disabled: false,
  8413. comment: ''
  8414. };
  8415. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8416. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8417. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8418. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8419. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8420. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8421. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8422. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8423. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8424. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8425. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8426. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8427. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8428. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8429. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8430. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8431. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8432. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8433. }
  8434. function openEditOspfTemplateModal(id) {
  8435. openOspfTemplateModal(id);
  8436. }
  8437. function closeOspfTemplateModal() {
  8438. document.getElementById('ospf-template-modal').classList.add('hidden');
  8439. }
  8440. async function submitOspfTemplate(e) {
  8441. if (e) e.preventDefault();
  8442. const payload = {
  8443. id: document.getElementById('modal-ospf-tmpl-id').value,
  8444. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8445. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8446. area: document.getElementById('modal-ospf-tmpl-area').value,
  8447. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8448. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8449. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8450. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8451. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8452. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8453. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8454. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8455. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8456. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8457. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8458. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8459. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8460. };
  8461. try {
  8462. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8463. method: 'POST',
  8464. headers: { 'Content-Type': 'application/json' },
  8465. body: JSON.stringify(payload)
  8466. });
  8467. if (res.ok) {
  8468. closeOspfTemplateModal();
  8469. showToast('Saved', 'Interface template saved', 'success');
  8470. loadDynamicRouting();
  8471. } else {
  8472. const err = await res.json();
  8473. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8474. }
  8475. } catch (err) {
  8476. showToast('Error', err.message, 'error');
  8477. }
  8478. }
  8479. function applyOspfTemplateForm() {
  8480. submitOspfTemplate(null);
  8481. }
  8482. function copyOspfTemplate() {
  8483. document.getElementById('modal-ospf-tmpl-id').value = '';
  8484. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8485. showToast('Copied', 'Duplicated as new template', 'info');
  8486. }
  8487. async function deleteCurrentOspfTemplate() {
  8488. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8489. if (!id) return;
  8490. if (!confirm('Delete this interface template?')) return;
  8491. try {
  8492. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8493. closeOspfTemplateModal();
  8494. showToast('Removed', 'Interface template deleted', 'success');
  8495. loadDynamicRouting();
  8496. } catch (err) {
  8497. showToast('Error', err.message, 'error');
  8498. }
  8499. }
  8500. async function enableSelectedOspfTemplate() {
  8501. const id = state.selectedOspfRow?.templates;
  8502. if (!id) return;
  8503. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8504. method: 'POST',
  8505. headers: { 'Content-Type': 'application/json' },
  8506. body: JSON.stringify({ disabled: false })
  8507. });
  8508. loadDynamicRouting();
  8509. }
  8510. async function disableSelectedOspfTemplate() {
  8511. const id = state.selectedOspfRow?.templates;
  8512. if (!id) return;
  8513. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8514. method: 'POST',
  8515. headers: { 'Content-Type': 'application/json' },
  8516. body: JSON.stringify({ disabled: true })
  8517. });
  8518. loadDynamicRouting();
  8519. }
  8520. async function removeSelectedOspfTemplate() {
  8521. const id = state.selectedOspfRow?.templates;
  8522. if (!id) return;
  8523. if (!confirm('Delete selected interface template?')) return;
  8524. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8525. loadDynamicRouting();
  8526. }
  8527. async function promptCommentOspfTemplate() {
  8528. const id = state.selectedOspfRow?.templates;
  8529. if (!id) return;
  8530. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8531. if (!tmpl) return;
  8532. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8533. if (comment === null) return;
  8534. tmpl.comment = comment;
  8535. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8536. method: 'POST',
  8537. headers: { 'Content-Type': 'application/json' },
  8538. body: JSON.stringify(tmpl)
  8539. });
  8540. loadDynamicRouting();
  8541. }
  8542. // --- 5. OSPF STATIC NEIGHBOR ---
  8543. function populateStaticNbrAreaDropdowns() {
  8544. const select = document.getElementById('modal-ospf-snbr-area');
  8545. if (select) {
  8546. const cur = select.value;
  8547. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8548. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8549. if (cur) select.value = cur;
  8550. }
  8551. }
  8552. function openOspfStaticNbrModal(id = null) {
  8553. const isEdit = !!id;
  8554. populateStaticNbrAreaDropdowns();
  8555. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8556. id: '',
  8557. address: '',
  8558. area: 'Default',
  8559. poll_interval: 120,
  8560. cost: 1,
  8561. disabled: false,
  8562. comment: ''
  8563. };
  8564. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8565. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8566. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8567. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8568. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8569. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8570. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8571. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8572. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8573. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8574. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8575. }
  8576. function openEditOspfStaticNbrModal(id) {
  8577. openOspfStaticNbrModal(id);
  8578. }
  8579. function closeOspfStaticNbrModal() {
  8580. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8581. }
  8582. async function submitOspfStaticNbr(e) {
  8583. if (e) e.preventDefault();
  8584. const payload = {
  8585. id: document.getElementById('modal-ospf-snbr-id').value,
  8586. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8587. area: document.getElementById('modal-ospf-snbr-area').value,
  8588. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8589. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8590. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8591. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8592. };
  8593. try {
  8594. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8595. method: 'POST',
  8596. headers: { 'Content-Type': 'application/json' },
  8597. body: JSON.stringify(payload)
  8598. });
  8599. if (res.ok) {
  8600. closeOspfStaticNbrModal();
  8601. showToast('Saved', 'Static neighbor saved', 'success');
  8602. loadDynamicRouting();
  8603. } else {
  8604. const err = await res.json();
  8605. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8606. }
  8607. } catch (err) {
  8608. showToast('Error', err.message, 'error');
  8609. }
  8610. }
  8611. function applyOspfStaticNbrForm() {
  8612. submitOspfStaticNbr(null);
  8613. }
  8614. async function deleteCurrentOspfStaticNbr() {
  8615. const id = document.getElementById('modal-ospf-snbr-id').value;
  8616. if (!id) return;
  8617. if (!confirm('Delete this static neighbor?')) return;
  8618. try {
  8619. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8620. closeOspfStaticNbrModal();
  8621. showToast('Removed', 'Static neighbor removed', 'success');
  8622. loadDynamicRouting();
  8623. } catch (err) {
  8624. showToast('Error', err.message, 'error');
  8625. }
  8626. }
  8627. async function enableSelectedOspfStaticNbr() {
  8628. const id = state.selectedOspfRow?.['static-nbrs'];
  8629. if (!id) return;
  8630. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8631. if (!n) return;
  8632. n.disabled = false;
  8633. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8634. loadDynamicRouting();
  8635. }
  8636. async function disableSelectedOspfStaticNbr() {
  8637. const id = state.selectedOspfRow?.['static-nbrs'];
  8638. if (!id) return;
  8639. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8640. if (!n) return;
  8641. n.disabled = true;
  8642. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8643. loadDynamicRouting();
  8644. }
  8645. async function removeSelectedOspfStaticNbr() {
  8646. const id = state.selectedOspfRow?.['static-nbrs'];
  8647. if (!id) return;
  8648. if (!confirm('Delete selected static neighbor?')) return;
  8649. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8650. loadDynamicRouting();
  8651. }
  8652. async function promptCommentOspfStaticNbr() {
  8653. const id = state.selectedOspfRow?.['static-nbrs'];
  8654. if (!id) return;
  8655. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8656. if (!n) return;
  8657. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8658. if (comment === null) return;
  8659. n.comment = comment;
  8660. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8661. loadDynamicRouting();
  8662. }
  8663. // Backward-compat aliases
  8664. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8665. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8666. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8667. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8668. function deleteOspfInterface(id) {
  8669. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8670. }
  8671. function toggleOspfInterfaceState(id, disabled) {
  8672. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8673. method: 'POST',
  8674. headers: { 'Content-Type': 'application/json' },
  8675. body: JSON.stringify({ disabled })
  8676. }).then(() => loadDynamicRouting());
  8677. }
  8678. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8679. function deleteOspfArea(id) {
  8680. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8681. }
  8682. // ============================================================================
  8683. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8684. // ============================================================================
  8685. function switchBridgeSubTab(tab) {
  8686. state.bridgeSubTab = tab;
  8687. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8688. tabs.forEach(t => {
  8689. const panel = document.getElementById(`bridge-subtab-${t}`);
  8690. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8691. if (panel) {
  8692. if (t === tab) panel.classList.remove('hidden');
  8693. else panel.classList.add('hidden');
  8694. }
  8695. if (btn) {
  8696. if (t === tab) {
  8697. 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';
  8698. } else {
  8699. 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';
  8700. }
  8701. }
  8702. });
  8703. const addBtn = document.getElementById('bridge-top-action-btn');
  8704. if (addBtn) {
  8705. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8706. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8707. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8708. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8709. }
  8710. if (tab === 'hosts') loadBridgeHosts();
  8711. setTimeout(initTableSorting, 50);
  8712. }
  8713. function openCurrentBridgeModal() {
  8714. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8715. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8716. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8717. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8718. }
  8719. async function loadBridge() {
  8720. try {
  8721. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8722. fetch(`${API_BASE}/bridge/bridges`),
  8723. fetch(`${API_BASE}/bridge/ports`),
  8724. fetch(`${API_BASE}/bridge/vlans`),
  8725. fetch(`${API_BASE}/bridge/summary`),
  8726. fetch(`${API_BASE}/vpn/eoip`),
  8727. fetch(`${API_BASE}/vlans`)
  8728. ]);
  8729. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8730. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8731. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8732. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8733. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8734. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8735. // Badges & Stats
  8736. const bBridges = document.getElementById('bridge-badge-bridges');
  8737. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8738. const bPorts = document.getElementById('bridge-badge-ports');
  8739. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8740. const bVlans = document.getElementById('bridge-badge-vlans');
  8741. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8742. const bHosts = document.getElementById('bridge-badge-hosts');
  8743. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8744. const sBr = document.getElementById('bridge-stat-bridges');
  8745. if (sBr) sBr.innerText = (state.bridges || []).length;
  8746. const sPorts = document.getElementById('bridge-stat-ports');
  8747. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8748. const sHosts = document.getElementById('bridge-stat-hosts');
  8749. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8750. renderBridges();
  8751. renderBridgePorts();
  8752. renderBridgeVLANs();
  8753. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8754. } catch (err) {
  8755. console.error('Failed to load bridge subsystem:', err);
  8756. }
  8757. }
  8758. // ----------------- Bridges -----------------
  8759. function renderBridges() {
  8760. const tbody = document.getElementById('bridge-table-body');
  8761. const empty = document.getElementById('bridge-empty-bridges');
  8762. const countBadge = document.getElementById('bridge-count-badge');
  8763. if (!tbody) return;
  8764. tbody.innerHTML = '';
  8765. const bridges = state.bridges || [];
  8766. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8767. if (bridges.length === 0) {
  8768. empty?.classList.remove('hidden');
  8769. return;
  8770. }
  8771. empty?.classList.add('hidden');
  8772. bridges.forEach((b, idx) => {
  8773. const tr = document.createElement('tr');
  8774. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8775. // Format IP addresses pill list
  8776. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8777. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8778. ipsHtml = b.ip_addresses.map(ip => `
  8779. <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">
  8780. <span>${ip}</span>
  8781. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8782. </span>
  8783. `).join(' ');
  8784. }
  8785. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8786. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8787. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8788. tr.innerHTML = `
  8789. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8790. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8791. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8792. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8793. </td>
  8794. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8795. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8796. <td class="py-2.5 px-3">
  8797. <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>
  8798. </td>
  8799. <td class="py-2.5 px-3 text-center">
  8800. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8801. </td>
  8802. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8803. <td class="py-2.5 px-3">
  8804. <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>
  8805. </td>
  8806. <td class="py-2.5 px-3">
  8807. <div class="flex items-center gap-1.5 flex-wrap">
  8808. ${ipsHtml}
  8809. <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>
  8810. </div>
  8811. </td>
  8812. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8813. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8814. </td>
  8815. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8816. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8817. <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>
  8818. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8819. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8820. </td>
  8821. `;
  8822. tbody.appendChild(tr);
  8823. });
  8824. }
  8825. function openAddBridgeModal() {
  8826. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8827. document.getElementById('bridge-modal-id').value = '';
  8828. document.getElementById('bridge-modal-name').value = 'bridge1';
  8829. document.getElementById('bridge-modal-name').disabled = false;
  8830. document.getElementById('bridge-modal-mtu').value = '1500';
  8831. document.getElementById('bridge-modal-mac').value = '';
  8832. document.getElementById('bridge-modal-stp').value = 'rstp';
  8833. document.getElementById('bridge-modal-priority').value = '32768';
  8834. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8835. document.getElementById('bridge-modal-pvid').value = '1';
  8836. document.getElementById('bridge-modal-fastforward').checked = true;
  8837. document.getElementById('bridge-modal-comment').value = '';
  8838. document.getElementById('bridge-modal-disabled').checked = false;
  8839. toggleBridgeModalVlanFiltering();
  8840. document.getElementById('bridge-modal').classList.remove('hidden');
  8841. }
  8842. function openEditBridgeModal(id) {
  8843. const b = (state.bridges || []).find(x => x.id === id);
  8844. if (!b) return;
  8845. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8846. document.getElementById('bridge-modal-id').value = b.id;
  8847. document.getElementById('bridge-modal-name').value = b.name;
  8848. document.getElementById('bridge-modal-name').disabled = true;
  8849. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8850. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8851. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8852. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8853. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8854. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8855. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8856. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8857. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8858. toggleBridgeModalVlanFiltering();
  8859. document.getElementById('bridge-modal').classList.remove('hidden');
  8860. }
  8861. function closeBridgeModal() {
  8862. document.getElementById('bridge-modal').classList.add('hidden');
  8863. }
  8864. function toggleBridgeModalVlanFiltering() {
  8865. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8866. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8867. if (pvidBox) {
  8868. if (chk) pvidBox.classList.remove('opacity-40');
  8869. else pvidBox.classList.add('opacity-40');
  8870. }
  8871. }
  8872. async function submitSaveBridge(e) {
  8873. e.preventDefault();
  8874. const id = document.getElementById('bridge-modal-id').value;
  8875. const name = document.getElementById('bridge-modal-name').value.trim();
  8876. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8877. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8878. const stp = document.getElementById('bridge-modal-stp').value;
  8879. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8880. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8881. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8882. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8883. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8884. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8885. try {
  8886. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8887. method: 'POST',
  8888. headers: { 'Content-Type': 'application/json' },
  8889. body: JSON.stringify({
  8890. id,
  8891. name,
  8892. mtu,
  8893. mac_address: mac,
  8894. stp,
  8895. priority,
  8896. vlan_filtering: vlanFiltering,
  8897. pvid,
  8898. fast_forward: fastForward,
  8899. comment,
  8900. disabled
  8901. })
  8902. });
  8903. if (res.ok) {
  8904. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8905. closeBridgeModal();
  8906. loadBridge();
  8907. fetchData(false);
  8908. } else {
  8909. const err = await res.json();
  8910. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8911. }
  8912. } catch (err) {
  8913. showToast('Error', err.message, 'error');
  8914. }
  8915. }
  8916. async function toggleBridgeState(id, disabled) {
  8917. try {
  8918. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8919. method: 'POST',
  8920. headers: { 'Content-Type': 'application/json' },
  8921. body: JSON.stringify({ disabled })
  8922. });
  8923. if (res.ok) {
  8924. loadBridge();
  8925. fetchData(false);
  8926. }
  8927. } catch (err) {
  8928. showToast('Error', err.message, 'error');
  8929. }
  8930. }
  8931. async function deleteBridge(id) {
  8932. const b = (state.bridges || []).find(x => x.id === id);
  8933. const name = b ? b.name : id;
  8934. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8935. try {
  8936. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8937. if (res.ok) {
  8938. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8939. loadBridge();
  8940. fetchData(false);
  8941. } else {
  8942. const err = await res.json();
  8943. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8944. }
  8945. } catch (err) {
  8946. showToast('Error', err.message, 'error');
  8947. }
  8948. }
  8949. // ----------------- Bridge IP Assignments -----------------
  8950. function openAddBridgeIPModal(id, name) {
  8951. document.getElementById('bridge-ip-modal-id').value = id;
  8952. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8953. document.getElementById('bridge-ip-modal-cidr').value = '';
  8954. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8955. }
  8956. function closeBridgeIPModal() {
  8957. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8958. }
  8959. async function submitAddBridgeIP(e) {
  8960. e.preventDefault();
  8961. const id = document.getElementById('bridge-ip-modal-id').value;
  8962. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8963. try {
  8964. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8965. method: 'POST',
  8966. headers: { 'Content-Type': 'application/json' },
  8967. body: JSON.stringify({ ip })
  8968. });
  8969. if (res.ok) {
  8970. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8971. closeBridgeIPModal();
  8972. loadBridge();
  8973. fetchData(false);
  8974. } else {
  8975. const err = await res.json();
  8976. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8977. }
  8978. } catch (err) {
  8979. showToast('Error', err.message, 'error');
  8980. }
  8981. }
  8982. async function deleteBridgeIP(id, ip) {
  8983. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8984. try {
  8985. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8986. method: 'DELETE',
  8987. headers: { 'Content-Type': 'application/json' },
  8988. body: JSON.stringify({ ip })
  8989. });
  8990. if (res.ok) {
  8991. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8992. loadBridge();
  8993. fetchData(false);
  8994. }
  8995. } catch (err) {
  8996. showToast('Error', err.message, 'error');
  8997. }
  8998. }
  8999. // ----------------- Bridge Ports -----------------
  9000. function renderBridgePorts() {
  9001. const tbody = document.getElementById('bridge-ports-table-body');
  9002. const empty = document.getElementById('bridge-empty-ports');
  9003. const countBadge = document.getElementById('bridge-ports-count-badge');
  9004. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9005. if (!tbody) return;
  9006. tbody.innerHTML = '';
  9007. // Update filter select
  9008. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9009. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9010. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9011. if (ports.length === 0) {
  9012. empty?.classList.remove('hidden');
  9013. return;
  9014. }
  9015. empty?.classList.add('hidden');
  9016. ports.forEach((p, idx) => {
  9017. const tr = document.createElement('tr');
  9018. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9019. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9020. tr.innerHTML = `
  9021. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9022. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9023. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9024. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9025. </td>
  9026. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9027. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9028. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9029. <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>
  9030. <td class="py-2.5 px-3">
  9031. ${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>'}
  9032. </td>
  9033. <td class="py-2.5 px-3">
  9034. <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>
  9035. </td>
  9036. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9037. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9038. <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>
  9039. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9040. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9041. </td>
  9042. `;
  9043. tbody.appendChild(tr);
  9044. });
  9045. }
  9046. function openAddBridgePortModal() {
  9047. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9048. document.getElementById('bridge-port-modal-id').value = '';
  9049. populateBridgeSelect('bridge-port-modal-bridge');
  9050. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9051. document.getElementById('bridge-port-modal-pvid').value = '1';
  9052. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9053. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9054. document.getElementById('bridge-port-modal-horizon').value = '0';
  9055. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9056. document.getElementById('bridge-port-modal-priority').value = '128';
  9057. document.getElementById('bridge-port-modal-learn').checked = true;
  9058. document.getElementById('bridge-port-modal-comment').value = '';
  9059. document.getElementById('bridge-port-modal-disabled').checked = false;
  9060. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9061. }
  9062. function openEditBridgePortModal(id) {
  9063. const p = (state.bridgePorts || []).find(x => x.id === id);
  9064. if (!p) return;
  9065. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9066. document.getElementById('bridge-port-modal-id').value = p.id;
  9067. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9068. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9069. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9070. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9071. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9072. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9073. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9074. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9075. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9076. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9077. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9078. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9079. }
  9080. function closeBridgePortModal() {
  9081. document.getElementById('bridge-port-modal').classList.add('hidden');
  9082. }
  9083. async function submitSaveBridgePort(e) {
  9084. e.preventDefault();
  9085. const id = document.getElementById('bridge-port-modal-id').value;
  9086. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9087. const iface = document.getElementById('bridge-port-modal-interface').value;
  9088. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9089. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9090. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9091. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9092. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9093. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9094. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9095. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9096. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9097. try {
  9098. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9099. method: 'POST',
  9100. headers: { 'Content-Type': 'application/json' },
  9101. body: JSON.stringify({
  9102. id,
  9103. bridge,
  9104. interface: iface,
  9105. pvid,
  9106. frame_types: frameTypes,
  9107. ingress_filtering: ingressFiltering,
  9108. horizon,
  9109. path_cost: pathCost,
  9110. priority,
  9111. learn,
  9112. comment,
  9113. disabled
  9114. })
  9115. });
  9116. if (res.ok) {
  9117. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9118. closeBridgePortModal();
  9119. loadBridge();
  9120. fetchData(false);
  9121. } else {
  9122. const err = await res.json();
  9123. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9124. }
  9125. } catch (err) {
  9126. showToast('Error', err.message, 'error');
  9127. }
  9128. }
  9129. async function toggleBridgePortState(id, disabled) {
  9130. try {
  9131. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9132. method: 'POST',
  9133. headers: { 'Content-Type': 'application/json' },
  9134. body: JSON.stringify({ disabled })
  9135. });
  9136. if (res.ok) {
  9137. loadBridge();
  9138. fetchData(false);
  9139. }
  9140. } catch (err) {
  9141. showToast('Error', err.message, 'error');
  9142. }
  9143. }
  9144. async function deleteBridgePort(id) {
  9145. const p = (state.bridgePorts || []).find(x => x.id === id);
  9146. const iface = p ? p.interface : id;
  9147. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9148. try {
  9149. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9150. if (res.ok) {
  9151. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9152. loadBridge();
  9153. fetchData(false);
  9154. }
  9155. } catch (err) {
  9156. showToast('Error', err.message, 'error');
  9157. }
  9158. }
  9159. // ----------------- Bridge VLANs -----------------
  9160. function renderBridgeVLANs() {
  9161. const tbody = document.getElementById('bridge-vlans-table-body');
  9162. const empty = document.getElementById('bridge-empty-vlans');
  9163. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9164. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9165. if (!tbody) return;
  9166. tbody.innerHTML = '';
  9167. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9168. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9169. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9170. if (vlans.length === 0) {
  9171. empty?.classList.remove('hidden');
  9172. return;
  9173. }
  9174. empty?.classList.add('hidden');
  9175. vlans.forEach((v, idx) => {
  9176. const tr = document.createElement('tr');
  9177. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9178. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9179. ? 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(' ')
  9180. : '<span class="text-slate-600">none</span>';
  9181. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9182. ? 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(' ')
  9183. : '<span class="text-slate-600">none</span>';
  9184. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9185. tr.innerHTML = `
  9186. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9187. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9188. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9189. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9190. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9191. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9192. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9193. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9194. <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>
  9195. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9196. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9197. </td>
  9198. `;
  9199. tbody.appendChild(tr);
  9200. });
  9201. }
  9202. function openAddBridgeVLANModal() {
  9203. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9204. document.getElementById('bridge-vlan-modal-id').value = '';
  9205. populateBridgeSelect('bridge-vlan-modal-bridge');
  9206. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9207. document.getElementById('bridge-vlan-modal-comment').value = '';
  9208. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9209. updateBridgeVlanPortCheckboxes();
  9210. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9211. }
  9212. function openEditBridgeVLANModal(id) {
  9213. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9214. if (!v) return;
  9215. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9216. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9217. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9218. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9219. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9220. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9221. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9222. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9223. }
  9224. function closeBridgeVlanModal() {
  9225. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9226. }
  9227. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9228. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9229. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9230. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9231. if (!taggedBox || !untaggedBox) return;
  9232. // Ports belonging to the selected bridge
  9233. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9234. if (memberPorts.length === 0) {
  9235. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9236. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9237. return;
  9238. }
  9239. taggedBox.innerHTML = memberPorts.map(p => `
  9240. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9241. <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">
  9242. <span>${p.interface}</span>
  9243. </label>
  9244. `).join('');
  9245. untaggedBox.innerHTML = memberPorts.map(p => `
  9246. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9247. <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">
  9248. <span>${p.interface}</span>
  9249. </label>
  9250. `).join('');
  9251. }
  9252. async function submitSaveBridgeVLAN(e) {
  9253. e.preventDefault();
  9254. const id = document.getElementById('bridge-vlan-modal-id').value;
  9255. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9256. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9257. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9258. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9259. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9260. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9261. try {
  9262. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9263. method: 'POST',
  9264. headers: { 'Content-Type': 'application/json' },
  9265. body: JSON.stringify({
  9266. id,
  9267. bridge,
  9268. vlan_ids: vlanIDs,
  9269. tagged,
  9270. untagged,
  9271. comment,
  9272. disabled
  9273. })
  9274. });
  9275. if (res.ok) {
  9276. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9277. closeBridgeVlanModal();
  9278. loadBridge();
  9279. } else {
  9280. const err = await res.json();
  9281. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9282. }
  9283. } catch (err) {
  9284. showToast('Error', err.message, 'error');
  9285. }
  9286. }
  9287. async function toggleBridgeVLANState(id, disabled) {
  9288. try {
  9289. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9290. method: 'POST',
  9291. headers: { 'Content-Type': 'application/json' },
  9292. body: JSON.stringify({ disabled })
  9293. });
  9294. if (res.ok) loadBridge();
  9295. } catch (err) {
  9296. showToast('Error', err.message, 'error');
  9297. }
  9298. }
  9299. async function deleteBridgeVLAN(id) {
  9300. if (!confirm('Delete this bridge VLAN entry?')) return;
  9301. try {
  9302. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9303. if (res.ok) {
  9304. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9305. loadBridge();
  9306. }
  9307. } catch (err) {
  9308. showToast('Error', err.message, 'error');
  9309. }
  9310. }
  9311. // ----------------- Hosts / MAC Table -----------------
  9312. async function loadBridgeHosts() {
  9313. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9314. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9315. try {
  9316. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9317. const res = await fetch(url);
  9318. if (res.ok) {
  9319. state.bridgeHosts = await res.json();
  9320. renderBridgeHosts();
  9321. }
  9322. } catch (err) {
  9323. console.error('Failed to load bridge hosts:', err);
  9324. }
  9325. }
  9326. function renderBridgeHosts() {
  9327. const tbody = document.getElementById('bridge-hosts-table-body');
  9328. const empty = document.getElementById('bridge-empty-hosts');
  9329. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9330. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9331. if (!tbody) return;
  9332. tbody.innerHTML = '';
  9333. const hosts = (state.bridgeHosts || []).filter(h => {
  9334. if (!search) return true;
  9335. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9336. });
  9337. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9338. if (hosts.length === 0) {
  9339. empty?.classList.remove('hidden');
  9340. return;
  9341. }
  9342. empty?.classList.add('hidden');
  9343. hosts.forEach(h => {
  9344. const tr = document.createElement('tr');
  9345. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9346. let flagBadges = '';
  9347. 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>';
  9348. 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>';
  9349. 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>';
  9350. tr.innerHTML = `
  9351. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9352. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9353. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9354. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9355. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9356. <td class="py-2.5 px-3">${flagBadges}</td>
  9357. `;
  9358. tbody.appendChild(tr);
  9359. });
  9360. }
  9361. async function flushBridgeHosts() {
  9362. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9363. if (!selBridge) {
  9364. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9365. return;
  9366. }
  9367. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9368. try {
  9369. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9370. method: 'POST',
  9371. headers: { 'Content-Type': 'application/json' },
  9372. body: JSON.stringify({ bridge: selBridge })
  9373. });
  9374. if (res.ok) {
  9375. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9376. loadBridgeHosts();
  9377. }
  9378. } catch (err) {
  9379. showToast('Error', err.message, 'error');
  9380. }
  9381. }
  9382. // ----------------- Helpers -----------------
  9383. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9384. const sel = document.getElementById(selectId);
  9385. if (!sel) return;
  9386. const prevVal = currentVal || sel.value;
  9387. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9388. (state.bridges || []).forEach(b => {
  9389. const opt = document.createElement('option');
  9390. opt.value = b.name;
  9391. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9392. if (b.name === prevVal) opt.selected = true;
  9393. sel.appendChild(opt);
  9394. });
  9395. }
  9396. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9397. const sel = document.getElementById(selectId);
  9398. if (!sel) return;
  9399. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9400. // 1. Physical Interfaces
  9401. const grpPhys = document.createElement('optgroup');
  9402. grpPhys.label = 'Physical Interfaces';
  9403. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9404. const opt = document.createElement('option');
  9405. opt.value = i.name;
  9406. opt.innerText = `${i.name} (${i.role || i.type})`;
  9407. if (i.name === currentVal) opt.selected = true;
  9408. grpPhys.appendChild(opt);
  9409. });
  9410. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9411. // 2. VLAN Sub-interfaces
  9412. const grpVlans = document.createElement('optgroup');
  9413. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9414. (state.vlans || []).forEach(v => {
  9415. const opt = document.createElement('option');
  9416. opt.value = v.name;
  9417. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9418. if (v.name === currentVal) opt.selected = true;
  9419. grpVlans.appendChild(opt);
  9420. });
  9421. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9422. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9423. const grpEoip = document.createElement('optgroup');
  9424. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9425. (state.eoipTunnels || []).forEach(t => {
  9426. const opt = document.createElement('option');
  9427. opt.value = t.name;
  9428. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9429. if (t.name === currentVal) opt.selected = true;
  9430. grpEoip.appendChild(opt);
  9431. });
  9432. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9433. }
  9434. // -------------------------------------------------------------
  9435. // RouterOS v7 Routing Filters Management (/routing filter)
  9436. // -------------------------------------------------------------
  9437. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9438. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9439. if (!state.rfSort) state.rfSort = {};
  9440. function switchRoutingFilterTab(tab) {
  9441. state.activeRoutingFilterTab = tab;
  9442. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9443. tabs.forEach(t => {
  9444. const btn = document.getElementById(`tab-rf-${t}`);
  9445. const content = document.getElementById(`tab-content-rf-${t}`);
  9446. if (btn) {
  9447. if (t === tab) {
  9448. 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';
  9449. } else {
  9450. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9451. }
  9452. }
  9453. if (content) {
  9454. if (t === tab) content.classList.remove('hidden');
  9455. else content.classList.add('hidden');
  9456. }
  9457. });
  9458. const chainContainer = document.getElementById('rf-chain-filter-container');
  9459. if (chainContainer) {
  9460. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9461. else chainContainer.classList.add('hidden');
  9462. }
  9463. renderRoutingFilters();
  9464. }
  9465. function selectFilterRow(tab, id) {
  9466. if (state.selectedFilterRow[tab] === id) {
  9467. delete state.selectedFilterRow[tab];
  9468. } else {
  9469. state.selectedFilterRow[tab] = id;
  9470. }
  9471. if (tab === 'rules') renderRoutingFilterRules();
  9472. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9473. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9474. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9475. }
  9476. function openRoutingFilterNewModal() {
  9477. const tab = state.activeRoutingFilterTab || 'rules';
  9478. if (tab === 'rules') openAddRoutingFilterModal();
  9479. else if (tab === 'select-rules') openAddSelectRuleModal();
  9480. else if (tab === 'community-lists') openAddCommunityListModal();
  9481. else if (tab === 'as-lists') openAddASListModal();
  9482. }
  9483. function toggleSelectedRoutingFilter(disabled) {
  9484. const tab = state.activeRoutingFilterTab || 'rules';
  9485. const id = state.selectedFilterRow[tab];
  9486. if (!id) {
  9487. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9488. return;
  9489. }
  9490. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9491. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9492. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9493. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9494. }
  9495. function removeSelectedRoutingFilter() {
  9496. const tab = state.activeRoutingFilterTab || 'rules';
  9497. const id = state.selectedFilterRow[tab];
  9498. if (!id) {
  9499. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9500. return;
  9501. }
  9502. if (tab === 'rules') deleteRoutingFilter(id);
  9503. else if (tab === 'select-rules') deleteSelectRule(id);
  9504. else if (tab === 'community-lists') deleteCommunityList(id);
  9505. else if (tab === 'as-lists') deleteASList(id);
  9506. }
  9507. function searchRoutingFilters(q) {
  9508. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9509. renderRoutingFilters();
  9510. }
  9511. function sortFilterTable(tab, col) {
  9512. if (!state.rfSort) state.rfSort = {};
  9513. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9514. if (state.rfSort[tab].col === col) {
  9515. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9516. } else {
  9517. state.rfSort[tab].col = col;
  9518. state.rfSort[tab].asc = true;
  9519. }
  9520. const asc = state.rfSort[tab].asc;
  9521. let list = [];
  9522. if (tab === 'rules') list = state.routingFilters || [];
  9523. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9524. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9525. else if (tab === 'as-lists') list = state.routingASLists || [];
  9526. list.sort((a, b) => {
  9527. let valA = a[col] ?? '';
  9528. let valB = b[col] ?? '';
  9529. if (col === 'flags') {
  9530. valA = a.disabled ? 'X' : 'A';
  9531. valB = b.disabled ? 'X' : 'A';
  9532. }
  9533. if (typeof valA === 'number' && typeof valB === 'number') {
  9534. return asc ? valA - valB : valB - valA;
  9535. }
  9536. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9537. });
  9538. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9539. allCols.forEach(c => {
  9540. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9541. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9542. });
  9543. if (tab === 'rules') renderRoutingFilterRules();
  9544. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9545. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9546. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9547. }
  9548. function renderRoutingFilters() {
  9549. const navBadge = document.getElementById('badge-filters-count');
  9550. const allRules = state.routingFilters || [];
  9551. if (navBadge) navBadge.innerText = allRules.length;
  9552. // Populate chain filter select options and datalist
  9553. const chainSelect = document.getElementById('routing-filter-chain-select');
  9554. const chainDatalist = document.getElementById('dl-routing-chains');
  9555. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9556. if (chainSelect) {
  9557. const currentVal = state.filterChainSelected || 'all';
  9558. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9559. uniqueChains.map(ch => {
  9560. const count = allRules.filter(r => r.chain === ch).length;
  9561. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9562. }).join('');
  9563. chainSelect.value = currentVal;
  9564. }
  9565. if (chainDatalist) {
  9566. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9567. }
  9568. renderRoutingFilterRules();
  9569. renderRoutingFilterSelectRules();
  9570. renderRoutingFilterCommunityLists();
  9571. renderRoutingFilterASLists();
  9572. }
  9573. function filterRoutingFiltersByChain(chain) {
  9574. state.filterChainSelected = chain;
  9575. renderRoutingFilters();
  9576. }
  9577. // -------------------------------------------------------------
  9578. // TAB 1: RULES (/routing filter rule)
  9579. // -------------------------------------------------------------
  9580. function renderRoutingFilterRules() {
  9581. const tbody = document.getElementById('routing-filter-rules-tbody');
  9582. if (!tbody) return;
  9583. const empty = document.getElementById('rf-rules-empty');
  9584. const statusCount = document.getElementById('rf-status-count');
  9585. let list = (state.routingFilters || []).slice();
  9586. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9587. list = list.filter(r => r.chain === state.filterChainSelected);
  9588. }
  9589. const q = state.rfSearchQuery;
  9590. if (q) {
  9591. list = list.filter(r =>
  9592. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9593. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9594. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9595. (r.comment && r.comment.toLowerCase().includes(q))
  9596. );
  9597. }
  9598. if (!state.rfSort?.['rules']) {
  9599. list.sort((a, b) => {
  9600. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9601. return (a.rule_order || 0) - (b.rule_order || 0);
  9602. });
  9603. }
  9604. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9605. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9606. }
  9607. if (list.length === 0) {
  9608. tbody.innerHTML = '';
  9609. if (empty) empty.classList.remove('hidden');
  9610. return;
  9611. }
  9612. if (empty) empty.classList.add('hidden');
  9613. tbody.innerHTML = list.map(r => {
  9614. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9615. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9616. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9617. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9618. let ruleDisplay = '';
  9619. if (r.rule && r.rule.trim() !== '') {
  9620. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9621. } else {
  9622. let conds = [];
  9623. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9624. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9625. let act = r.action || 'accept';
  9626. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9627. }
  9628. return `
  9629. <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'}">
  9630. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9631. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9632. <td class="py-2 px-3">
  9633. <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>
  9634. </td>
  9635. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9636. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9637. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9638. <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>
  9639. <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>
  9640. <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'}">
  9641. ${r.disabled ? 'Enable' : 'Disable'}
  9642. </button>
  9643. <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">
  9644. Edit
  9645. </button>
  9646. <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">
  9647. ✕
  9648. </button>
  9649. </td>
  9650. </tr>
  9651. `;
  9652. }).join('');
  9653. }
  9654. // -------------------------------------------------------------
  9655. // TAB 2: SELECT RULES (/routing filter select-rule)
  9656. // -------------------------------------------------------------
  9657. function renderRoutingFilterSelectRules() {
  9658. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9659. if (!tbody) return;
  9660. const empty = document.getElementById('rf-select-rules-empty');
  9661. const statusCount = document.getElementById('rf-status-count');
  9662. let list = (state.routingSelectRules || []).slice();
  9663. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9664. list = list.filter(r => r.chain === state.filterChainSelected);
  9665. }
  9666. const q = state.rfSearchQuery;
  9667. if (q) {
  9668. list = list.filter(r =>
  9669. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9670. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9671. (r.comment && r.comment.toLowerCase().includes(q))
  9672. );
  9673. }
  9674. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9675. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9676. }
  9677. if (list.length === 0) {
  9678. tbody.innerHTML = '';
  9679. if (empty) empty.classList.remove('hidden');
  9680. return;
  9681. }
  9682. if (empty) empty.classList.add('hidden');
  9683. tbody.innerHTML = list.map(r => {
  9684. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9685. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9686. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9687. return `
  9688. <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'}">
  9689. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9690. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9691. <td class="py-2 px-3">
  9692. <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>
  9693. </td>
  9694. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9695. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9696. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9697. <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'}">
  9698. ${r.disabled ? 'Enable' : 'Disable'}
  9699. </button>
  9700. <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">
  9701. Edit
  9702. </button>
  9703. <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">
  9704. ✕
  9705. </button>
  9706. </td>
  9707. </tr>
  9708. `;
  9709. }).join('');
  9710. }
  9711. // -------------------------------------------------------------
  9712. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9713. // -------------------------------------------------------------
  9714. function renderRoutingFilterCommunityLists() {
  9715. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9716. if (!tbody) return;
  9717. const empty = document.getElementById('rf-comm-lists-empty');
  9718. const statusCount = document.getElementById('rf-status-count');
  9719. let list = (state.routingCommunityLists || []).slice();
  9720. const q = state.rfSearchQuery;
  9721. if (q) {
  9722. list = list.filter(cl =>
  9723. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9724. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9725. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9726. );
  9727. }
  9728. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9729. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9730. }
  9731. if (list.length === 0) {
  9732. tbody.innerHTML = '';
  9733. if (empty) empty.classList.remove('hidden');
  9734. return;
  9735. }
  9736. if (empty) empty.classList.add('hidden');
  9737. tbody.innerHTML = list.map(cl => {
  9738. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9739. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9740. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9741. const commBadges = (cl.communities || []).map(c =>
  9742. `<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>`
  9743. ).join(' ');
  9744. return `
  9745. <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'}">
  9746. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9747. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9748. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9749. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9750. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9751. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9752. <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'}">
  9753. ${cl.disabled ? 'Enable' : 'Disable'}
  9754. </button>
  9755. <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">
  9756. Edit
  9757. </button>
  9758. <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">
  9759. ✕
  9760. </button>
  9761. </td>
  9762. </tr>
  9763. `;
  9764. }).join('');
  9765. }
  9766. // -------------------------------------------------------------
  9767. // TAB 4: AS LISTS (/routing filter num-list)
  9768. // -------------------------------------------------------------
  9769. function renderRoutingFilterASLists() {
  9770. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9771. if (!tbody) return;
  9772. const empty = document.getElementById('rf-as-lists-empty');
  9773. const statusCount = document.getElementById('rf-status-count');
  9774. let list = (state.routingASLists || []).slice();
  9775. const q = state.rfSearchQuery;
  9776. if (q) {
  9777. list = list.filter(al =>
  9778. (al.name && al.name.toLowerCase().includes(q)) ||
  9779. (al.range && al.range.toLowerCase().includes(q)) ||
  9780. (al.comment && al.comment.toLowerCase().includes(q))
  9781. );
  9782. }
  9783. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9784. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9785. }
  9786. if (list.length === 0) {
  9787. tbody.innerHTML = '';
  9788. if (empty) empty.classList.remove('hidden');
  9789. return;
  9790. }
  9791. if (empty) empty.classList.add('hidden');
  9792. tbody.innerHTML = list.map(al => {
  9793. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9794. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9795. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9796. return `
  9797. <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'}">
  9798. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9799. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9800. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9801. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9802. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9803. <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'}">
  9804. ${al.disabled ? 'Enable' : 'Disable'}
  9805. </button>
  9806. <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">
  9807. Edit
  9808. </button>
  9809. <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">
  9810. ✕
  9811. </button>
  9812. </td>
  9813. </tr>
  9814. `;
  9815. }).join('');
  9816. }
  9817. // -------------------------------------------------------------
  9818. // SNIPPETS & WIZARD HELPERS
  9819. // -------------------------------------------------------------
  9820. function insertRuleSnippet(type) {
  9821. const textarea = document.getElementById('modal-rf-rule');
  9822. if (!textarea) return;
  9823. let snippet = '';
  9824. switch (type) {
  9825. case 'accept-default':
  9826. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9827. break;
  9828. case 'drop-rfc1918':
  9829. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9830. break;
  9831. case 'len-24':
  9832. snippet = 'if (dst-len > 24) { reject; }';
  9833. break;
  9834. case 'local-pref-150':
  9835. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9836. break;
  9837. case 'as-prepend-2':
  9838. snippet = 'set bgp-path-prepend 2; accept;';
  9839. break;
  9840. case 'set-comm':
  9841. snippet = 'set bgp-communities.add 65000:100; accept;';
  9842. break;
  9843. case 'match-comm':
  9844. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9845. break;
  9846. case 'reject-all':
  9847. snippet = 'reject;';
  9848. break;
  9849. }
  9850. if (!snippet) return;
  9851. if (!textarea.value.trim()) {
  9852. textarea.value = snippet;
  9853. } else {
  9854. textarea.value = textarea.value.trim() + '\n' + snippet;
  9855. }
  9856. }
  9857. function generateScriptFromWizard() {
  9858. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9859. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9860. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9861. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9862. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9863. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9864. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9865. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9866. const conds = [];
  9867. if (pfx) {
  9868. if (pfxLen) {
  9869. if (pfxLen.includes('-')) {
  9870. const parts = pfxLen.split('-');
  9871. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9872. } else {
  9873. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9874. }
  9875. } else {
  9876. conds.push(`dst in ${pfx}`);
  9877. }
  9878. }
  9879. if (proto && proto !== 'any') {
  9880. conds.push(`protocol ${proto}`);
  9881. }
  9882. if (asp) {
  9883. conds.push(`bgp-as-path "${asp}"`);
  9884. }
  9885. if (comm) {
  9886. conds.push(`bgp-communities includes ${comm}`);
  9887. }
  9888. const actions = [];
  9889. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9890. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9891. actions.push(`${act};`);
  9892. let code = '';
  9893. if (conds.length > 0) {
  9894. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9895. } else {
  9896. code = actions.join(' ');
  9897. }
  9898. const textarea = document.getElementById('modal-rf-rule');
  9899. if (textarea) textarea.value = code;
  9900. }
  9901. // -------------------------------------------------------------
  9902. // MODAL CRUD: RULES (/routing filter rule)
  9903. // -------------------------------------------------------------
  9904. function openAddRoutingFilterModal(defaultChain = '') {
  9905. const form = document.getElementById('routing-filter-form');
  9906. if (form) form.reset();
  9907. const idEl = document.getElementById('modal-rf-id');
  9908. if (idEl) idEl.value = '';
  9909. const titleEl = document.getElementById('modal-rf-title');
  9910. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9911. const chainEl = document.getElementById('modal-rf-chain');
  9912. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9913. const orderEl = document.getElementById('modal-rf-order');
  9914. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9915. const ruleEl = document.getElementById('modal-rf-rule');
  9916. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9917. const disEl = document.getElementById('modal-rf-disabled');
  9918. if (disEl) disEl.checked = false;
  9919. const modal = document.getElementById('modal-routing-filter');
  9920. if (modal) modal.classList.remove('hidden');
  9921. }
  9922. function openEditRoutingFilterModal(id) {
  9923. const r = (state.routingFilters || []).find(item => item.id === id);
  9924. if (!r) return;
  9925. const idEl = document.getElementById('modal-rf-id');
  9926. if (idEl) idEl.value = r.id;
  9927. const titleEl = document.getElementById('modal-rf-title');
  9928. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9929. const chainEl = document.getElementById('modal-rf-chain');
  9930. if (chainEl) chainEl.value = r.chain || '';
  9931. const orderEl = document.getElementById('modal-rf-order');
  9932. if (orderEl) orderEl.value = r.rule_order || 10;
  9933. const ruleEl = document.getElementById('modal-rf-rule');
  9934. if (ruleEl) {
  9935. if (r.rule) {
  9936. ruleEl.value = r.rule;
  9937. } else {
  9938. let conds = [];
  9939. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9940. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9941. let act = r.action || 'accept';
  9942. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9943. }
  9944. }
  9945. const comEl = document.getElementById('modal-rf-comment');
  9946. if (comEl) comEl.value = r.comment || '';
  9947. const disEl = document.getElementById('modal-rf-disabled');
  9948. if (disEl) disEl.checked = !!r.disabled;
  9949. const modal = document.getElementById('modal-routing-filter');
  9950. if (modal) modal.classList.remove('hidden');
  9951. }
  9952. function closeRoutingFilterModal() {
  9953. const modal = document.getElementById('modal-routing-filter');
  9954. if (modal) modal.classList.add('hidden');
  9955. }
  9956. async function submitRoutingFilter(e) {
  9957. if (e) e.preventDefault();
  9958. const payload = {
  9959. id: document.getElementById('modal-rf-id').value,
  9960. chain: document.getElementById('modal-rf-chain').value.trim(),
  9961. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9962. rule: document.getElementById('modal-rf-rule').value.trim(),
  9963. comment: document.getElementById('modal-rf-comment').value.trim(),
  9964. disabled: document.getElementById('modal-rf-disabled').checked
  9965. };
  9966. try {
  9967. const res = await fetch(`${API_BASE}/routing/filters`, {
  9968. method: 'POST',
  9969. headers: { 'Content-Type': 'application/json' },
  9970. body: JSON.stringify(payload)
  9971. });
  9972. if (res.ok) {
  9973. closeRoutingFilterModal();
  9974. showToast('Success', 'Routing filter rule saved', 'success');
  9975. loadDynamicRouting();
  9976. } else {
  9977. const err = await res.json();
  9978. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9979. }
  9980. } catch (err) {
  9981. showToast('Error', err.message, 'error');
  9982. }
  9983. }
  9984. async function applyRoutingFilterForm() {
  9985. const payload = {
  9986. id: document.getElementById('modal-rf-id').value,
  9987. chain: document.getElementById('modal-rf-chain').value.trim(),
  9988. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9989. rule: document.getElementById('modal-rf-rule').value.trim(),
  9990. comment: document.getElementById('modal-rf-comment').value.trim(),
  9991. disabled: document.getElementById('modal-rf-disabled').checked
  9992. };
  9993. try {
  9994. const res = await fetch(`${API_BASE}/routing/filters`, {
  9995. method: 'POST',
  9996. headers: { 'Content-Type': 'application/json' },
  9997. body: JSON.stringify(payload)
  9998. });
  9999. if (res.ok) {
  10000. const data = await res.json();
  10001. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10002. showToast('Applied', 'Routing filter configuration applied', 'success');
  10003. loadDynamicRouting();
  10004. } else {
  10005. const err = await res.json();
  10006. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10007. }
  10008. } catch (err) {
  10009. showToast('Error', err.message, 'error');
  10010. }
  10011. }
  10012. async function moveRoutingFilterOrder(id, delta) {
  10013. const list = state.routingFilters || [];
  10014. const idx = list.findIndex(r => r.id === id);
  10015. if (idx < 0) return;
  10016. const targetIdx = idx + delta;
  10017. if (targetIdx < 0 || targetIdx >= list.length) return;
  10018. const currentOrder = list[idx].rule_order || 10;
  10019. const targetOrder = list[targetIdx].rule_order || 20;
  10020. list[idx].rule_order = targetOrder;
  10021. list[targetIdx].rule_order = currentOrder;
  10022. try {
  10023. await fetch(`${API_BASE}/routing/filters`, {
  10024. method: 'POST',
  10025. headers: { 'Content-Type': 'application/json' },
  10026. body: JSON.stringify(list[idx])
  10027. });
  10028. await fetch(`${API_BASE}/routing/filters`, {
  10029. method: 'POST',
  10030. headers: { 'Content-Type': 'application/json' },
  10031. body: JSON.stringify(list[targetIdx])
  10032. });
  10033. loadDynamicRouting();
  10034. } catch (e) {
  10035. console.error('Reorder error:', e);
  10036. }
  10037. }
  10038. async function deleteRoutingFilter(id) {
  10039. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10040. try {
  10041. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10042. if (res.ok) {
  10043. showToast('Deleted', 'Routing filter rule removed', 'info');
  10044. loadDynamicRouting();
  10045. } else {
  10046. const err = await res.json();
  10047. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10048. }
  10049. } catch (err) {
  10050. showToast('Error', err.message, 'error');
  10051. }
  10052. }
  10053. async function toggleRoutingFilterState(id, disabled) {
  10054. try {
  10055. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10056. method: 'POST',
  10057. headers: { 'Content-Type': 'application/json' },
  10058. body: JSON.stringify({ disabled })
  10059. });
  10060. if (res.ok) {
  10061. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10062. loadDynamicRouting();
  10063. } else {
  10064. const err = await res.json();
  10065. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10066. }
  10067. } catch (err) {
  10068. showToast('Error', err.message, 'error');
  10069. }
  10070. }
  10071. // -------------------------------------------------------------
  10072. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10073. // -------------------------------------------------------------
  10074. function openAddSelectRuleModal() {
  10075. document.getElementById('modal-rf-sr-id').value = '';
  10076. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10077. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10078. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10079. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10080. document.getElementById('modal-rf-sr-comment').value = '';
  10081. document.getElementById('modal-rf-sr-disabled').checked = false;
  10082. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10083. }
  10084. function openEditSelectRuleModal(id) {
  10085. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10086. if (!r) return;
  10087. document.getElementById('modal-rf-sr-id').value = r.id;
  10088. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10089. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10090. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10091. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10092. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10093. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10094. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10095. }
  10096. function closeSelectRuleModal() {
  10097. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10098. }
  10099. async function submitSelectRule(e) {
  10100. e.preventDefault();
  10101. const payload = {
  10102. id: document.getElementById('modal-rf-sr-id').value,
  10103. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10104. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10105. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10106. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10107. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10108. };
  10109. try {
  10110. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10111. method: 'POST',
  10112. headers: { 'Content-Type': 'application/json' },
  10113. body: JSON.stringify(payload)
  10114. });
  10115. if (res.ok) {
  10116. closeSelectRuleModal();
  10117. showToast('Success', 'Select rule saved', 'success');
  10118. loadDynamicRouting();
  10119. } else {
  10120. const err = await res.json();
  10121. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10122. }
  10123. } catch (err) {
  10124. showToast('Error', err.message, 'error');
  10125. }
  10126. }
  10127. async function deleteSelectRule(id) {
  10128. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10129. try {
  10130. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10131. if (res.ok) {
  10132. showToast('Deleted', 'Select rule removed', 'info');
  10133. loadDynamicRouting();
  10134. } else {
  10135. const err = await res.json();
  10136. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10137. }
  10138. } catch (err) {
  10139. showToast('Error', err.message, 'error');
  10140. }
  10141. }
  10142. async function toggleSelectRuleState(id, disabled) {
  10143. try {
  10144. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10145. method: 'POST',
  10146. headers: { 'Content-Type': 'application/json' },
  10147. body: JSON.stringify({ disabled })
  10148. });
  10149. if (res.ok) {
  10150. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10151. loadDynamicRouting();
  10152. } else {
  10153. const err = await res.json();
  10154. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10155. }
  10156. } catch (err) {
  10157. showToast('Error', err.message, 'error');
  10158. }
  10159. }
  10160. // -------------------------------------------------------------
  10161. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10162. // -------------------------------------------------------------
  10163. function openAddCommunityListModal() {
  10164. document.getElementById('modal-rf-cl-id').value = '';
  10165. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10166. document.getElementById('modal-rf-cl-name').value = '';
  10167. document.getElementById('modal-rf-cl-communities').value = '';
  10168. document.getElementById('modal-rf-cl-regexp').value = '';
  10169. document.getElementById('modal-rf-cl-comment').value = '';
  10170. document.getElementById('modal-rf-cl-disabled').checked = false;
  10171. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10172. }
  10173. function openEditCommunityListModal(id) {
  10174. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10175. if (!cl) return;
  10176. document.getElementById('modal-rf-cl-id').value = cl.id;
  10177. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10178. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10179. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10180. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10181. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10182. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10183. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10184. }
  10185. function closeCommunityListModal() {
  10186. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10187. }
  10188. async function submitCommunityList(e) {
  10189. e.preventDefault();
  10190. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10191. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10192. const payload = {
  10193. id: document.getElementById('modal-rf-cl-id').value,
  10194. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10195. communities: comms,
  10196. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10197. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10198. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10199. };
  10200. try {
  10201. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10202. method: 'POST',
  10203. headers: { 'Content-Type': 'application/json' },
  10204. body: JSON.stringify(payload)
  10205. });
  10206. if (res.ok) {
  10207. closeCommunityListModal();
  10208. showToast('Success', 'Community list saved', 'success');
  10209. loadDynamicRouting();
  10210. } else {
  10211. const err = await res.json();
  10212. showToast('Error', err.error || 'Failed to save community list', 'error');
  10213. }
  10214. } catch (err) {
  10215. showToast('Error', err.message, 'error');
  10216. }
  10217. }
  10218. async function deleteCommunityList(id) {
  10219. if (!confirm('Are you sure you want to delete this community list?')) return;
  10220. try {
  10221. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10222. if (res.ok) {
  10223. showToast('Deleted', 'Community list removed', 'info');
  10224. loadDynamicRouting();
  10225. } else {
  10226. const err = await res.json();
  10227. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10228. }
  10229. } catch (err) {
  10230. showToast('Error', err.message, 'error');
  10231. }
  10232. }
  10233. async function toggleCommunityListState(id, disabled) {
  10234. try {
  10235. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10236. method: 'POST',
  10237. headers: { 'Content-Type': 'application/json' },
  10238. body: JSON.stringify({ disabled })
  10239. });
  10240. if (res.ok) {
  10241. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10242. loadDynamicRouting();
  10243. } else {
  10244. const err = await res.json();
  10245. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10246. }
  10247. } catch (err) {
  10248. showToast('Error', err.message, 'error');
  10249. }
  10250. }
  10251. // -------------------------------------------------------------
  10252. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10253. // -------------------------------------------------------------
  10254. function openAddASListModal() {
  10255. document.getElementById('modal-rf-al-id').value = '';
  10256. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10257. document.getElementById('modal-rf-al-name').value = '';
  10258. document.getElementById('modal-rf-al-range').value = '';
  10259. document.getElementById('modal-rf-al-comment').value = '';
  10260. document.getElementById('modal-rf-al-disabled').checked = false;
  10261. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10262. }
  10263. function openEditASListModal(id) {
  10264. const al = (state.routingASLists || []).find(item => item.id === id);
  10265. if (!al) return;
  10266. document.getElementById('modal-rf-al-id').value = al.id;
  10267. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10268. document.getElementById('modal-rf-al-name').value = al.name || '';
  10269. document.getElementById('modal-rf-al-range').value = al.range || '';
  10270. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10271. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10272. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10273. }
  10274. function closeASListModal() {
  10275. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10276. }
  10277. async function submitASList(e) {
  10278. e.preventDefault();
  10279. const payload = {
  10280. id: document.getElementById('modal-rf-al-id').value,
  10281. name: document.getElementById('modal-rf-al-name').value.trim(),
  10282. range: document.getElementById('modal-rf-al-range').value.trim(),
  10283. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10284. disabled: document.getElementById('modal-rf-al-disabled').checked
  10285. };
  10286. try {
  10287. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10288. method: 'POST',
  10289. headers: { 'Content-Type': 'application/json' },
  10290. body: JSON.stringify(payload)
  10291. });
  10292. if (res.ok) {
  10293. closeASListModal();
  10294. showToast('Success', 'AS number list saved', 'success');
  10295. loadDynamicRouting();
  10296. } else {
  10297. const err = await res.json();
  10298. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10299. }
  10300. } catch (err) {
  10301. showToast('Error', err.message, 'error');
  10302. }
  10303. }
  10304. async function deleteASList(id) {
  10305. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10306. try {
  10307. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10308. if (res.ok) {
  10309. showToast('Deleted', 'AS list removed', 'info');
  10310. loadDynamicRouting();
  10311. } else {
  10312. const err = await res.json();
  10313. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10314. }
  10315. } catch (err) {
  10316. showToast('Error', err.message, 'error');
  10317. }
  10318. }
  10319. async function toggleASListState(id, disabled) {
  10320. try {
  10321. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10322. method: 'POST',
  10323. headers: { 'Content-Type': 'application/json' },
  10324. body: JSON.stringify({ disabled })
  10325. });
  10326. if (res.ok) {
  10327. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10328. loadDynamicRouting();
  10329. } else {
  10330. const err = await res.json();
  10331. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10332. }
  10333. } catch (err) {
  10334. showToast('Error', err.message, 'error');
  10335. }
  10336. }
  10337. // ==========================================
  10338. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10339. // ==========================================
  10340. function loadToolsView() {
  10341. populateToolsInterfaces();
  10342. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10343. }
  10344. function populateToolsInterfaces() {
  10345. const pingSel = document.getElementById('tools-ping-iface');
  10346. const traceSel = document.getElementById('tools-tr-iface');
  10347. let opts = '<option value="">Auto (Default Route)</option>';
  10348. if (Array.isArray(state.interfaces)) {
  10349. state.interfaces.forEach(iface => {
  10350. if (iface.name) {
  10351. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10352. }
  10353. });
  10354. }
  10355. if (pingSel) {
  10356. const cur = pingSel.value;
  10357. pingSel.innerHTML = opts;
  10358. if (cur) pingSel.value = cur;
  10359. }
  10360. if (traceSel) {
  10361. const cur = traceSel.value;
  10362. traceSel.innerHTML = opts;
  10363. if (cur) traceSel.value = cur;
  10364. }
  10365. }
  10366. function switchToolsSubTab(subTab) {
  10367. state.activeToolsSubTab = subTab;
  10368. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10369. tabs.forEach(t => {
  10370. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10371. const view = document.getElementById(`tools-view-${t}`);
  10372. if (btn) {
  10373. if (t === subTab) {
  10374. 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';
  10375. } else {
  10376. 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';
  10377. }
  10378. }
  10379. if (view) {
  10380. if (t === subTab) {
  10381. view.classList.remove('hidden');
  10382. } else {
  10383. view.classList.add('hidden');
  10384. }
  10385. }
  10386. });
  10387. }
  10388. function setPortPreset(port) {
  10389. const input = document.getElementById('tools-port-num');
  10390. if (input) input.value = port;
  10391. }
  10392. let pingAbortController = null;
  10393. let tracerouteAbortController = null;
  10394. function clearPingTable() {
  10395. const tbody = document.getElementById('tools-ping-tbody');
  10396. if (tbody) tbody.innerHTML = '';
  10397. const rawEl = document.getElementById('tools-ping-raw');
  10398. if (rawEl) rawEl.innerText = '';
  10399. const sentEl = document.getElementById('tools-ping-stat-sent');
  10400. if (sentEl) sentEl.innerText = '0';
  10401. const recvEl = document.getElementById('tools-ping-stat-recv');
  10402. if (recvEl) recvEl.innerText = '0';
  10403. const lossEl = document.getElementById('tools-ping-stat-loss');
  10404. if (lossEl) lossEl.innerText = '0%';
  10405. const avgEl = document.getElementById('tools-ping-stat-avg');
  10406. if (avgEl) avgEl.innerText = '0 ms';
  10407. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10408. if (minMaxEl) minMaxEl.innerText = '-';
  10409. const badge = document.getElementById('tools-ping-status-badge');
  10410. if (badge) {
  10411. badge.className = '';
  10412. badge.innerText = '';
  10413. }
  10414. }
  10415. function clearTracerouteTable() {
  10416. const tbody = document.getElementById('tools-tr-tbody');
  10417. if (tbody) tbody.innerHTML = '';
  10418. const rawEl = document.getElementById('tools-tr-raw');
  10419. if (rawEl) rawEl.innerText = '';
  10420. const statHops = document.getElementById('tools-tr-hops-count');
  10421. if (statHops) statHops.innerText = '0 Hops';
  10422. }
  10423. function resetPingButton() {
  10424. const btn = document.getElementById('tools-ping-btn');
  10425. const btnText = document.getElementById('tools-ping-btn-text');
  10426. const spinner = document.getElementById('tools-ping-spinner');
  10427. if (btn) {
  10428. btn.disabled = false;
  10429. 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';
  10430. }
  10431. if (btnText) btnText.innerText = 'Start Ping';
  10432. if (spinner) spinner.classList.add('hidden');
  10433. }
  10434. function setPingRunningButton() {
  10435. const btn = document.getElementById('tools-ping-btn');
  10436. const btnText = document.getElementById('tools-ping-btn-text');
  10437. const spinner = document.getElementById('tools-ping-spinner');
  10438. if (btn) {
  10439. btn.disabled = false;
  10440. 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';
  10441. }
  10442. if (btnText) btnText.innerText = 'Stop Ping';
  10443. if (spinner) spinner.classList.remove('hidden');
  10444. }
  10445. function resetTracerouteButton() {
  10446. const btn = document.getElementById('tools-tr-btn');
  10447. const btnText = document.getElementById('tools-tr-btn-text');
  10448. const spinner = document.getElementById('tools-tr-spinner');
  10449. if (btn) {
  10450. btn.disabled = false;
  10451. 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';
  10452. }
  10453. if (btnText) btnText.innerText = 'Start Traceroute';
  10454. if (spinner) spinner.classList.add('hidden');
  10455. }
  10456. function setTracerouteRunningButton() {
  10457. const btn = document.getElementById('tools-tr-btn');
  10458. const btnText = document.getElementById('tools-tr-btn-text');
  10459. const spinner = document.getElementById('tools-tr-spinner');
  10460. if (btn) {
  10461. btn.disabled = false;
  10462. 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';
  10463. }
  10464. if (btnText) btnText.innerText = 'Stop Traceroute';
  10465. if (spinner) spinner.classList.remove('hidden');
  10466. }
  10467. async function executePing(e) {
  10468. if (e) e.preventDefault();
  10469. // If already running, clicking the button stops the stream!
  10470. if (pingAbortController) {
  10471. pingAbortController.abort();
  10472. pingAbortController = null;
  10473. resetPingButton();
  10474. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10475. return;
  10476. }
  10477. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10478. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10479. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10480. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10481. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10482. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10483. if (!target) {
  10484. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10485. return;
  10486. }
  10487. clearPingTable();
  10488. const resCard = document.getElementById('tools-ping-results');
  10489. if (resCard) resCard.classList.remove('hidden');
  10490. pingAbortController = new AbortController();
  10491. setPingRunningButton();
  10492. try {
  10493. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10494. method: 'POST',
  10495. headers: { 'Content-Type': 'application/json' },
  10496. body: JSON.stringify({
  10497. target,
  10498. count,
  10499. size,
  10500. timeout,
  10501. interface: iface,
  10502. dont_frag: dontFrag
  10503. }),
  10504. signal: pingAbortController.signal
  10505. });
  10506. if (!res.ok) {
  10507. const errText = await res.text();
  10508. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10509. resetPingButton();
  10510. pingAbortController = null;
  10511. return;
  10512. }
  10513. const reader = res.body.getReader();
  10514. const decoder = new TextDecoder('utf-8');
  10515. let buffer = '';
  10516. while (true) {
  10517. const { done, value } = await reader.read();
  10518. if (done) break;
  10519. buffer += decoder.decode(value, { stream: true });
  10520. const blocks = buffer.split('\n\n');
  10521. buffer = blocks.pop() || '';
  10522. for (const block of blocks) {
  10523. const trimmed = block.trim();
  10524. if (!trimmed) continue;
  10525. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10526. try {
  10527. const evt = JSON.parse(line);
  10528. handleLivePingEvent(evt);
  10529. } catch (parseErr) {
  10530. console.warn('Ping SSE parse error:', parseErr, line);
  10531. }
  10532. }
  10533. }
  10534. } catch (err) {
  10535. if (err.name === 'AbortError') {
  10536. // User aborted normally
  10537. } else {
  10538. showToast('Ping Error', err.message, 'error');
  10539. }
  10540. } finally {
  10541. pingAbortController = null;
  10542. resetPingButton();
  10543. }
  10544. }
  10545. function handleLivePingEvent(evt) {
  10546. const sentEl = document.getElementById('tools-ping-stat-sent');
  10547. const recvEl = document.getElementById('tools-ping-stat-recv');
  10548. const lossEl = document.getElementById('tools-ping-stat-loss');
  10549. const avgEl = document.getElementById('tools-ping-stat-avg');
  10550. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10551. const badge = document.getElementById('tools-ping-status-badge');
  10552. const tbody = document.getElementById('tools-ping-tbody');
  10553. const rawEl = document.getElementById('tools-ping-raw');
  10554. if (evt.raw && rawEl) {
  10555. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10556. rawEl.scrollTop = rawEl.scrollHeight;
  10557. }
  10558. if (evt.type === 'reply') {
  10559. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10560. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10561. if (lossEl && evt.packet_loss_pct !== undefined) {
  10562. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10563. lossEl.className = evt.packet_loss_pct === 0
  10564. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10565. : (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');
  10566. }
  10567. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10568. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10569. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10570. }
  10571. if (badge) {
  10572. if (evt.packet_loss_pct === 0) {
  10573. 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';
  10574. badge.innerText = '100% OK';
  10575. } else {
  10576. 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';
  10577. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10578. }
  10579. }
  10580. if (tbody) {
  10581. const tr = document.createElement('tr');
  10582. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10583. tr.innerHTML = `
  10584. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10585. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10586. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10587. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10588. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10589. <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>
  10590. `;
  10591. tbody.appendChild(tr);
  10592. }
  10593. } else if (evt.type === 'timeout') {
  10594. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10595. if (lossEl && evt.packet_loss_pct !== undefined) {
  10596. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10597. 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';
  10598. }
  10599. if (badge) {
  10600. 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';
  10601. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10602. }
  10603. if (tbody) {
  10604. const tr = document.createElement('tr');
  10605. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10606. tr.innerHTML = `
  10607. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10608. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10609. <td class="py-2 px-3 text-slate-600">--</td>
  10610. <td class="py-2 px-3 text-slate-600">--</td>
  10611. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10612. <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>
  10613. `;
  10614. tbody.appendChild(tr);
  10615. }
  10616. } else if (evt.type === 'unreach') {
  10617. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10618. if (lossEl && evt.packet_loss_pct !== undefined) {
  10619. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10620. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10621. }
  10622. if (badge) {
  10623. 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';
  10624. badge.innerText = 'UNREACHABLE';
  10625. }
  10626. if (tbody) {
  10627. const tr = document.createElement('tr');
  10628. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10629. tr.innerHTML = `
  10630. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10631. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10632. <td class="py-2 px-3 text-slate-600">--</td>
  10633. <td class="py-2 px-3 text-slate-600">--</td>
  10634. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10635. <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>
  10636. `;
  10637. tbody.appendChild(tr);
  10638. }
  10639. } else if (evt.type === 'stats') {
  10640. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10641. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10642. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10643. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10644. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10645. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10646. }
  10647. } else if (evt.type === 'done') {
  10648. 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');
  10649. }
  10650. }
  10651. async function executeTraceroute(e) {
  10652. if (e) e.preventDefault();
  10653. if (tracerouteAbortController) {
  10654. tracerouteAbortController.abort();
  10655. tracerouteAbortController = null;
  10656. resetTracerouteButton();
  10657. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10658. return;
  10659. }
  10660. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10661. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10662. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10663. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10664. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10665. if (!target) {
  10666. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10667. return;
  10668. }
  10669. clearTracerouteTable();
  10670. const resCard = document.getElementById('tools-tr-results');
  10671. if (resCard) resCard.classList.remove('hidden');
  10672. tracerouteAbortController = new AbortController();
  10673. setTracerouteRunningButton();
  10674. try {
  10675. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10676. method: 'POST',
  10677. headers: { 'Content-Type': 'application/json' },
  10678. body: JSON.stringify({
  10679. target,
  10680. max_hops: maxHops,
  10681. protocol,
  10682. interface: iface,
  10683. resolve
  10684. }),
  10685. signal: tracerouteAbortController.signal
  10686. });
  10687. if (!res.ok) {
  10688. const errText = await res.text();
  10689. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10690. resetTracerouteButton();
  10691. tracerouteAbortController = null;
  10692. return;
  10693. }
  10694. const reader = res.body.getReader();
  10695. const decoder = new TextDecoder('utf-8');
  10696. let buffer = '';
  10697. while (true) {
  10698. const { done, value } = await reader.read();
  10699. if (done) break;
  10700. buffer += decoder.decode(value, { stream: true });
  10701. const blocks = buffer.split('\n\n');
  10702. buffer = blocks.pop() || '';
  10703. for (const block of blocks) {
  10704. const trimmed = block.trim();
  10705. if (!trimmed) continue;
  10706. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10707. try {
  10708. const evt = JSON.parse(line);
  10709. handleLiveTracerouteEvent(evt);
  10710. } catch (parseErr) {
  10711. console.warn('Traceroute SSE parse error:', parseErr, line);
  10712. }
  10713. }
  10714. }
  10715. } catch (err) {
  10716. if (err.name === 'AbortError') {
  10717. // User aborted normally
  10718. } else {
  10719. showToast('Traceroute Error', err.message, 'error');
  10720. }
  10721. } finally {
  10722. tracerouteAbortController = null;
  10723. resetTracerouteButton();
  10724. }
  10725. }
  10726. function handleLiveTracerouteEvent(evt) {
  10727. const statHops = document.getElementById('tools-tr-hops-count');
  10728. const tbody = document.getElementById('tools-tr-tbody');
  10729. const rawEl = document.getElementById('tools-tr-raw');
  10730. if (evt.raw && rawEl) {
  10731. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10732. rawEl.scrollTop = rawEl.scrollHeight;
  10733. }
  10734. if (evt.hops_count !== undefined && statHops) {
  10735. statHops.innerText = `${evt.hops_count} Hops`;
  10736. }
  10737. if (evt.type === 'hop' && evt.hop && tbody) {
  10738. const h = evt.hop;
  10739. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10740. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10741. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10742. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10743. const tr = document.createElement('tr');
  10744. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10745. tr.innerHTML = `
  10746. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10747. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10748. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10749. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10750. <td class="py-2.5 px-3 text-right">
  10751. ${isTimeout
  10752. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10753. : '<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>'}
  10754. </td>
  10755. `;
  10756. tbody.appendChild(tr);
  10757. } else if (evt.type === 'done') {
  10758. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10759. }
  10760. }
  10761. async function executeMTR(e) {
  10762. if (e) e.preventDefault();
  10763. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10764. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10765. if (!target) {
  10766. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10767. return;
  10768. }
  10769. const btn = document.getElementById('tools-mtr-btn');
  10770. const spinner = document.getElementById('tools-mtr-spinner');
  10771. if (btn) btn.disabled = true;
  10772. if (spinner) spinner.classList.remove('hidden');
  10773. try {
  10774. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10775. method: 'POST',
  10776. headers: { 'Content-Type': 'application/json' },
  10777. body: JSON.stringify({ target, count: cycles })
  10778. });
  10779. const data = await res.json();
  10780. if (!res.ok) {
  10781. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10782. return;
  10783. }
  10784. const resCard = document.getElementById('tools-mtr-results');
  10785. if (resCard) resCard.classList.remove('hidden');
  10786. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10787. const statHops = document.getElementById('tools-mtr-hops-count');
  10788. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10789. const tbody = document.getElementById('tools-mtr-tbody');
  10790. if (tbody) {
  10791. if (hopsCount > 0) {
  10792. tbody.innerHTML = data.hops.map(h => {
  10793. 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');
  10794. return `
  10795. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10796. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10797. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10798. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10799. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10800. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10801. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10802. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10803. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10804. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10805. </tr>
  10806. `;
  10807. }).join('');
  10808. } else {
  10809. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10810. }
  10811. }
  10812. const rawEl = document.getElementById('tools-mtr-raw');
  10813. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10814. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10815. } catch (err) {
  10816. showToast('MTR Error', err.message, 'error');
  10817. } finally {
  10818. if (btn) btn.disabled = false;
  10819. if (spinner) spinner.classList.add('hidden');
  10820. }
  10821. }
  10822. async function executeDNS(e) {
  10823. if (e) e.preventDefault();
  10824. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10825. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10826. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10827. if (!domain) {
  10828. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10829. return;
  10830. }
  10831. const btn = document.getElementById('tools-dns-btn');
  10832. const spinner = document.getElementById('tools-dns-spinner');
  10833. if (btn) btn.disabled = true;
  10834. if (spinner) spinner.classList.remove('hidden');
  10835. try {
  10836. const res = await fetch(`${API_BASE}/tools/dns`, {
  10837. method: 'POST',
  10838. headers: { 'Content-Type': 'application/json' },
  10839. body: JSON.stringify({ domain, type, server })
  10840. });
  10841. const data = await res.json();
  10842. if (!res.ok) {
  10843. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10844. return;
  10845. }
  10846. const resCard = document.getElementById('tools-dns-results');
  10847. if (resCard) resCard.classList.remove('hidden');
  10848. const metaEl = document.getElementById('tools-dns-meta');
  10849. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10850. const tbody = document.getElementById('tools-dns-tbody');
  10851. if (tbody) {
  10852. if (Array.isArray(data.records) && data.records.length > 0) {
  10853. tbody.innerHTML = data.records.map(r => `
  10854. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10855. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10856. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10857. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10858. <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>
  10859. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10860. </tr>
  10861. `).join('');
  10862. } else {
  10863. 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>`;
  10864. }
  10865. }
  10866. const rawEl = document.getElementById('tools-dns-raw');
  10867. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10868. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10869. } catch (err) {
  10870. showToast('DNS Error', err.message, 'error');
  10871. } finally {
  10872. if (btn) btn.disabled = false;
  10873. if (spinner) spinner.classList.add('hidden');
  10874. }
  10875. }
  10876. async function executePortProbe(e) {
  10877. if (e) e.preventDefault();
  10878. const target = document.getElementById('tools-port-target')?.value?.trim();
  10879. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10880. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10881. if (!target || !port) {
  10882. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10883. return;
  10884. }
  10885. const btn = document.getElementById('tools-port-btn');
  10886. const spinner = document.getElementById('tools-port-spinner');
  10887. if (btn) btn.disabled = true;
  10888. if (spinner) spinner.classList.remove('hidden');
  10889. try {
  10890. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10891. method: 'POST',
  10892. headers: { 'Content-Type': 'application/json' },
  10893. body: JSON.stringify({ target, port, timeout })
  10894. });
  10895. const data = await res.json();
  10896. if (!res.ok) {
  10897. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10898. return;
  10899. }
  10900. const resCard = document.getElementById('tools-port-results');
  10901. if (resCard) resCard.classList.remove('hidden');
  10902. const banner = document.getElementById('tools-port-banner');
  10903. const icon = document.getElementById('tools-port-icon');
  10904. const title = document.getElementById('tools-port-title');
  10905. const sub = document.getElementById('tools-port-sub');
  10906. const latency = document.getElementById('tools-port-latency');
  10907. if (data.open) {
  10908. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10909. if (icon) {
  10910. 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';
  10911. icon.innerText = '✓';
  10912. }
  10913. if (title) {
  10914. title.className = 'text-sm font-bold text-emerald-300';
  10915. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10916. }
  10917. if (sub) {
  10918. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10919. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10920. }
  10921. if (latency) {
  10922. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10923. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10924. }
  10925. } else {
  10926. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10927. if (icon) {
  10928. 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';
  10929. icon.innerText = '✕';
  10930. }
  10931. if (title) {
  10932. title.className = 'text-sm font-bold text-rose-300';
  10933. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10934. }
  10935. if (sub) {
  10936. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10937. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10938. }
  10939. if (latency) {
  10940. latency.className = 'text-base font-bold font-mono text-slate-500';
  10941. latency.innerText = '--';
  10942. }
  10943. }
  10944. const rawEl = document.getElementById('tools-port-raw');
  10945. 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'}`);
  10946. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10947. } catch (err) {
  10948. showToast('Probe Error', err.message, 'error');
  10949. } finally {
  10950. if (btn) btn.disabled = false;
  10951. if (spinner) spinner.classList.add('hidden');
  10952. }
  10953. }
  10954. // ==========================================
  10955. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10956. // ==========================================
  10957. async function loadDHCPClients(showToastMsg = false) {
  10958. try {
  10959. const [clientsRes, sumRes] = await Promise.all([
  10960. fetch(`${API_BASE}/dhcp/clients`),
  10961. fetch(`${API_BASE}/dhcp/clients/summary`)
  10962. ]);
  10963. if (clientsRes.ok) {
  10964. state.dhcpClients = await clientsRes.json();
  10965. }
  10966. if (sumRes.ok) {
  10967. state.dhcpSummary = await sumRes.json();
  10968. }
  10969. renderDHCPClients();
  10970. updateDHCPSummaryCards();
  10971. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10972. if (bDhcp && state.dhcpSummary) {
  10973. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10974. }
  10975. if (showToastMsg) {
  10976. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10977. }
  10978. } catch (err) {
  10979. console.error('Failed to load DHCP clients:', err);
  10980. if (showToastMsg) {
  10981. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10982. }
  10983. }
  10984. }
  10985. function updateDHCPSummaryCards() {
  10986. const sum = state.dhcpSummary || {
  10987. total_clients: (state.dhcpClients || []).length,
  10988. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10989. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10990. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10991. };
  10992. const totalEl = document.getElementById('dhcp-stat-total');
  10993. const boundEl = document.getElementById('dhcp-stat-bound');
  10994. const searchEl = document.getElementById('dhcp-stat-searching');
  10995. const disEl = document.getElementById('dhcp-stat-disabled');
  10996. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10997. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10998. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10999. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11000. }
  11001. function renderDHCPClients() {
  11002. const tbody = document.getElementById('dhcp-clients-tbody');
  11003. const emptyState = document.getElementById('dhcp-clients-empty');
  11004. if (!tbody) return;
  11005. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11006. if (clients.length === 0) {
  11007. tbody.innerHTML = '';
  11008. if (emptyState) emptyState.classList.remove('hidden');
  11009. return;
  11010. }
  11011. if (emptyState) emptyState.classList.add('hidden');
  11012. tbody.innerHTML = clients.map(c => {
  11013. let statusBadge = '';
  11014. if (!c.enabled) {
  11015. 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>';
  11016. } else if (c.status === 'bound') {
  11017. 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>';
  11018. } else if (c.status === 'searching') {
  11019. 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>';
  11020. } else if (c.status === 'stopped') {
  11021. 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>';
  11022. } else {
  11023. 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>`;
  11024. }
  11025. 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>';
  11026. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11027. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11028. 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>';
  11029. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11030. // Option flags
  11031. const flags = [];
  11032. 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>');
  11033. 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>');
  11034. 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>');
  11035. 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>`);
  11036. return `
  11037. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11038. <td class="py-3 px-4">
  11039. <div class="flex items-center gap-2">
  11040. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11041. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11042. </div>
  11043. </td>
  11044. <td class="py-3 px-4">${statusBadge}</td>
  11045. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11046. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11047. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11048. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11049. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11050. <td class="py-3 px-4">
  11051. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11052. </td>
  11053. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11054. ${c.enabled ? `
  11055. <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>
  11056. <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>
  11057. <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>
  11058. ` : `
  11059. <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>
  11060. `}
  11061. <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>
  11062. <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>
  11063. </td>
  11064. </tr>
  11065. `;
  11066. }).join('');
  11067. }
  11068. function openDHCPClientModal(clientId = null) {
  11069. const modal = document.getElementById('modal-dhcp-client');
  11070. if (!modal) return;
  11071. const title = document.getElementById('modal-dhcp-title');
  11072. const idInput = document.getElementById('modal-dhcp-id');
  11073. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11074. const distInput = document.getElementById('modal-dhcp-distance');
  11075. const commentInput = document.getElementById('modal-dhcp-comment');
  11076. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11077. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11078. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11079. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11080. // Populate interfaces
  11081. if (ifaceSelect) {
  11082. let opts = '<option value="">Select interface...</option>';
  11083. const allIfaces = state.interfaces || [];
  11084. const allVlans = state.vlans || [];
  11085. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11086. // Group 1: Physical & Bridge Interfaces
  11087. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11088. allIfaces.forEach(i => {
  11089. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11090. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11091. });
  11092. opts += '</optgroup>';
  11093. // Group 2: VLAN Interfaces
  11094. if (allVlans.length > 0) {
  11095. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11096. allVlans.forEach(v => {
  11097. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11098. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11099. });
  11100. opts += '</optgroup>';
  11101. }
  11102. ifaceSelect.innerHTML = opts;
  11103. }
  11104. if (clientId) {
  11105. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11106. if (client) {
  11107. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11108. if (idInput) idInput.value = client.id;
  11109. if (ifaceSelect) {
  11110. ifaceSelect.value = client.interface;
  11111. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11112. }
  11113. if (distInput) distInput.value = client.default_route_distance || 1;
  11114. if (commentInput) commentInput.value = client.comment || '';
  11115. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11116. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11117. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11118. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11119. }
  11120. } else {
  11121. if (title) title.innerText = 'Add DHCP Client';
  11122. if (idInput) idInput.value = '';
  11123. if (ifaceSelect) {
  11124. ifaceSelect.value = '';
  11125. ifaceSelect.disabled = false;
  11126. }
  11127. if (distInput) distInput.value = 1;
  11128. if (commentInput) commentInput.value = '';
  11129. if (defRouteCheck) defRouteCheck.checked = true;
  11130. if (peerDnsCheck) peerDnsCheck.checked = true;
  11131. if (peerNtpCheck) peerNtpCheck.checked = true;
  11132. if (enabledCheck) enabledCheck.checked = true;
  11133. }
  11134. modal.classList.remove('hidden');
  11135. }
  11136. function openDHCPClientModalForIface(ifaceName) {
  11137. openDHCPClientModal();
  11138. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11139. if (ifaceSelect && ifaceName) {
  11140. ifaceSelect.value = ifaceName;
  11141. }
  11142. }
  11143. function closeDHCPClientModal() {
  11144. const modal = document.getElementById('modal-dhcp-client');
  11145. if (modal) modal.classList.add('hidden');
  11146. }
  11147. async function submitSaveDHCPClient(e) {
  11148. if (e) e.preventDefault();
  11149. const id = document.getElementById('modal-dhcp-id')?.value;
  11150. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11151. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11152. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11153. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11154. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11155. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11156. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11157. if (!id && !iface) {
  11158. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11159. return;
  11160. }
  11161. try {
  11162. let res;
  11163. if (id) {
  11164. // PUT update
  11165. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11166. method: 'PUT',
  11167. headers: { 'Content-Type': 'application/json' },
  11168. body: JSON.stringify({
  11169. enabled,
  11170. add_default_route: defRoute,
  11171. default_route_distance: distance,
  11172. use_peer_dns: peerDns,
  11173. use_peer_ntp: peerNtp,
  11174. comment
  11175. })
  11176. });
  11177. } else {
  11178. // POST create
  11179. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11180. method: 'POST',
  11181. headers: { 'Content-Type': 'application/json' },
  11182. body: JSON.stringify({
  11183. interface: iface,
  11184. enabled,
  11185. add_default_route: defRoute,
  11186. default_route_distance: distance,
  11187. use_peer_dns: peerDns,
  11188. use_peer_ntp: peerNtp,
  11189. comment
  11190. })
  11191. });
  11192. }
  11193. const data = await res.json();
  11194. if (!res.ok) {
  11195. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11196. return;
  11197. }
  11198. closeDHCPClientModal();
  11199. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11200. await loadDHCPClients();
  11201. fetchData(); // refresh interfaces list with new lease/status
  11202. } catch (err) {
  11203. showToast('Error', err.message, 'error');
  11204. }
  11205. }
  11206. async function toggleDHCPClientState(id, enabled) {
  11207. try {
  11208. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11209. method: 'POST',
  11210. headers: { 'Content-Type': 'application/json' },
  11211. body: JSON.stringify({ enabled })
  11212. });
  11213. const data = await res.json();
  11214. if (!res.ok) {
  11215. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11216. return;
  11217. }
  11218. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11219. await loadDHCPClients();
  11220. fetchData();
  11221. } catch (err) {
  11222. showToast('Error', err.message, 'error');
  11223. }
  11224. }
  11225. async function renewDHCPClient(id) {
  11226. try {
  11227. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11228. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11229. method: 'POST'
  11230. });
  11231. const data = await res.json();
  11232. if (!res.ok) {
  11233. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11234. return;
  11235. }
  11236. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11237. setTimeout(() => {
  11238. loadDHCPClients();
  11239. fetchData();
  11240. }, 1500);
  11241. } catch (err) {
  11242. showToast('Error', err.message, 'error');
  11243. }
  11244. }
  11245. async function releaseDHCPClient(id) {
  11246. try {
  11247. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11248. method: 'POST'
  11249. });
  11250. const data = await res.json();
  11251. if (!res.ok) {
  11252. showToast('Error', data.error || 'Failed to release lease', 'error');
  11253. return;
  11254. }
  11255. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11256. await loadDHCPClients();
  11257. fetchData();
  11258. } catch (err) {
  11259. showToast('Error', err.message, 'error');
  11260. }
  11261. }
  11262. async function deleteDHCPClient(id, ifaceName) {
  11263. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11264. return;
  11265. }
  11266. try {
  11267. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11268. method: 'DELETE'
  11269. });
  11270. const data = await res.json();
  11271. if (!res.ok) {
  11272. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11273. return;
  11274. }
  11275. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11276. await loadDHCPClients();
  11277. fetchData();
  11278. } catch (err) {
  11279. showToast('Error', err.message, 'error');
  11280. }
  11281. }
  11282. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  11283. function initTableSorting() {
  11284. document.querySelectorAll('table').forEach(setupSortableTable);
  11285. }
  11286. function setupSortableTable(table) {
  11287. const thead = table.querySelector('thead');
  11288. const tbody = table.querySelector('tbody');
  11289. if (!thead || !tbody) return;
  11290. const headerRows = thead.querySelectorAll('tr');
  11291. if (headerRows.length === 0) return;
  11292. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  11293. ths.forEach((th, colIdx) => {
  11294. if (th._sortBound) return;
  11295. th._sortBound = true;
  11296. const rawText = th.innerText.trim().toLowerCase();
  11297. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  11298. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  11299. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  11300. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  11301. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  11302. return;
  11303. }
  11304. th.classList.add('table-sortable', 'group');
  11305. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  11306. let icon = th.querySelector('.table-sort-icon');
  11307. if (!icon) {
  11308. icon = document.createElement('span');
  11309. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  11310. icon.innerHTML = '⇅';
  11311. th.appendChild(icon);
  11312. }
  11313. th.addEventListener('click', (e) => {
  11314. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  11315. handleHeaderClick(table, th, colIdx);
  11316. });
  11317. });
  11318. if (!tbody._sortObserved) {
  11319. tbody._sortObserved = true;
  11320. let sortDebounceTimer = null;
  11321. const observer = new MutationObserver((mutations) => {
  11322. if (tbody._isSorting) return;
  11323. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  11324. if (!hasChildChanges) return;
  11325. clearTimeout(sortDebounceTimer);
  11326. sortDebounceTimer = setTimeout(() => {
  11327. if (tbody._isSorting) return;
  11328. if (table._activeSort && table._activeSort.dir !== 'none') {
  11329. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  11330. } else {
  11331. tagOriginalRowOrder(tbody);
  11332. }
  11333. }, 10);
  11334. });
  11335. observer.observe(tbody, { childList: true });
  11336. }
  11337. tagOriginalRowOrder(tbody);
  11338. }
  11339. function tagOriginalRowOrder(tbody) {
  11340. let idx = 0;
  11341. Array.from(tbody.children).forEach(tr => {
  11342. if (!tr.querySelector('td[colspan]')) {
  11343. if (!tr.hasAttribute('data-orig-idx')) {
  11344. tr.setAttribute('data-orig-idx', idx++);
  11345. }
  11346. }
  11347. });
  11348. }
  11349. function handleHeaderClick(table, th, colIdx) {
  11350. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  11351. let newDir = 'asc';
  11352. if (currentSort.colIdx === colIdx) {
  11353. if (currentSort.dir === 'asc') newDir = 'desc';
  11354. else if (currentSort.dir === 'desc') newDir = 'none';
  11355. else newDir = 'asc';
  11356. } else {
  11357. newDir = 'asc';
  11358. }
  11359. table._activeSort = { colIdx, dir: newDir };
  11360. updateHeaderIcons(table, colIdx, newDir);
  11361. applyTableSort(table, colIdx, newDir, true);
  11362. }
  11363. function updateHeaderIcons(table, activeColIdx, dir) {
  11364. const thead = table.querySelector('thead');
  11365. if (!thead) return;
  11366. const ths = thead.querySelectorAll('th');
  11367. ths.forEach((th, idx) => {
  11368. const icon = th.querySelector('.table-sort-icon');
  11369. if (!icon) return;
  11370. if (idx === activeColIdx && dir !== 'none') {
  11371. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  11372. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  11373. th.classList.add('table-sorted-active');
  11374. } else {
  11375. icon.innerHTML = '⇅';
  11376. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  11377. th.classList.remove('table-sorted-active');
  11378. }
  11379. });
  11380. }
  11381. function applyTableSort(table, colIdx, dir, userInitiated) {
  11382. const tbody = table.querySelector('tbody');
  11383. if (!tbody || tbody.children.length <= 1) return;
  11384. tbody._isSorting = true;
  11385. tagOriginalRowOrder(tbody);
  11386. // Group parent rows and any attached drawer/sub-rows
  11387. const groups = [];
  11388. let currentGroup = null;
  11389. Array.from(tbody.children).forEach(tr => {
  11390. if (tr.querySelector('td[colspan]')) {
  11391. if (currentGroup) {
  11392. currentGroup.subRows.push(tr);
  11393. } else {
  11394. groups.push({ mainRow: tr, subRows: [] });
  11395. }
  11396. } else {
  11397. currentGroup = { mainRow: tr, subRows: [] };
  11398. groups.push(currentGroup);
  11399. }
  11400. });
  11401. if (dir === 'none') {
  11402. groups.sort((a, b) => {
  11403. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11404. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11405. return idxA - idxB;
  11406. });
  11407. } else {
  11408. groups.sort((a, b) => {
  11409. const cellA = a.mainRow.children[colIdx];
  11410. const cellB = b.mainRow.children[colIdx];
  11411. const res = compareTableCells(cellA, cellB);
  11412. return dir === 'asc' ? res : -res;
  11413. });
  11414. }
  11415. // Re-append rows in sorted order
  11416. groups.forEach(g => {
  11417. tbody.appendChild(g.mainRow);
  11418. g.subRows.forEach(sub => tbody.appendChild(sub));
  11419. });
  11420. tbody._isSorting = false;
  11421. }
  11422. function getCellRawText(cell) {
  11423. if (!cell) return '';
  11424. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  11425. const input = cell.querySelector('input, select');
  11426. if (input) {
  11427. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  11428. return input.value;
  11429. }
  11430. return cell.innerText.trim();
  11431. }
  11432. function parseTrafficToNumber(str) {
  11433. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  11434. if (!m) return null;
  11435. const num = parseFloat(m[1].replace(/,/g, ''));
  11436. if (isNaN(num)) return null;
  11437. const unit = m[2].toUpperCase();
  11438. let mult = 1;
  11439. if (unit.startsWith('K')) mult = 1024;
  11440. else if (unit.startsWith('M')) mult = 1024 * 1024;
  11441. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  11442. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  11443. return num * mult;
  11444. }
  11445. function parseIpToNumber(str) {
  11446. const clean = str.replace(/^[!~]/, '').trim();
  11447. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  11448. if (!m) return null;
  11449. const o1 = parseInt(m[1], 10);
  11450. const o2 = parseInt(m[2], 10);
  11451. const o3 = parseInt(m[3], 10);
  11452. const o4 = parseInt(m[4], 10);
  11453. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  11454. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  11455. }
  11456. function parseCompoundPackets(str) {
  11457. const m = str.match(/^([\d,]+)p/);
  11458. if (!m) return null;
  11459. return parseInt(m[1].replace(/,/g, ''), 10);
  11460. }
  11461. function compareTableCells(cellA, cellB) {
  11462. const a = getCellRawText(cellA);
  11463. const b = getCellRawText(cellB);
  11464. if (a === '' && b !== '') return 1;
  11465. if (b === '' && a !== '') return -1;
  11466. if (a === b) return 0;
  11467. // 1. IP Addresses / CIDR
  11468. const ipA = parseIpToNumber(a);
  11469. const ipB = parseIpToNumber(b);
  11470. if (ipA !== null && ipB !== null) return ipA - ipB;
  11471. // 2. Packet counts (e.g. "1,250p / 45 KB")
  11472. const pktA = parseCompoundPackets(a);
  11473. const pktB = parseCompoundPackets(b);
  11474. if (pktA !== null && pktB !== null) return pktA - pktB;
  11475. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  11476. const trafA = parseTrafficToNumber(a);
  11477. const trafB = parseTrafficToNumber(b);
  11478. if (trafA !== null && trafB !== null) return trafA - trafB;
  11479. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  11480. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11481. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11482. const numA = Number(cleanNumA);
  11483. const numB = Number(cleanNumB);
  11484. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  11485. return numA - numB;
  11486. }
  11487. // 5. Natural case-insensitive string compare
  11488. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  11489. }
  11490. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  11491. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  11492. const docTableObserver = new MutationObserver((mutations) => {
  11493. let needsInit = false;
  11494. for (const m of mutations) {
  11495. for (const node of m.addedNodes) {
  11496. if (node.nodeType === 1) {
  11497. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  11498. needsInit = true;
  11499. break;
  11500. }
  11501. }
  11502. }
  11503. if (needsInit) break;
  11504. }
  11505. if (needsInit) {
  11506. initTableSorting();
  11507. }
  11508. });
  11509. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  11510. }