app.js 539 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null
  48. };
  49. const API_BASE = '/api';
  50. function escapeHtml(str) {
  51. if (str === null || str === undefined) return '';
  52. return String(str)
  53. .replace(/&/g, '&')
  54. .replace(/</g, '&lt;')
  55. .replace(/>/g, '&gt;')
  56. .replace(/"/g, '&quot;')
  57. .replace(/'/g, '&#039;');
  58. }
  59. // Initialize on page load
  60. document.addEventListener('DOMContentLoaded', () => {
  61. const hash = window.location.hash.replace('#', '') || 'dashboard';
  62. navigate(hash);
  63. initTableSorting();
  64. fetchData();
  65. // Live polling every 2.5 seconds
  66. setInterval(() => {
  67. if (state.isPolling) {
  68. fetchData(false);
  69. }
  70. }, 2500);
  71. });
  72. // Navigation Handler
  73. function navigate(tabName) {
  74. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  75. navigate('bgp');
  76. return;
  77. }
  78. if (tabName === 'vlans') {
  79. navigate('interfaces');
  80. return;
  81. }
  82. state.activeTab = tabName;
  83. window.location.hash = tabName;
  84. // Update nav links styling
  85. document.querySelectorAll('.nav-link').forEach(link => {
  86. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  87. });
  88. const activeNav = document.getElementById(`nav-${tabName}`);
  89. if (activeNav) {
  90. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  91. }
  92. // Update page headers
  93. const titles = {
  94. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  95. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  96. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  97. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  98. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  99. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  100. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  101. bgp: { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 BGP Multi-Instance peering sessions, advertised networks, and BGP routing table (RIB)' },
  102. ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'BIRD 2 OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  103. 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  104. 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'BIRD 2 dynamic routing engine' },
  105. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  106. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  107. aerotun: { title: 'AeroTUN VPN (/interface aerotun)', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  108. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  109. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  110. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  111. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  112. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  113. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  114. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  115. };
  116. const header = titles[tabName] || titles.dashboard;
  117. const pTitle = document.getElementById('page-title');
  118. if (pTitle) pTitle.innerText = header.title;
  119. const pSub = document.getElementById('page-subtitle');
  120. if (pSub) pSub.innerText = header.sub;
  121. // Toggle sections dynamically for all section elements
  122. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  123. if (el.id === `section-${tabName}`) {
  124. el.classList.remove('hidden');
  125. } else {
  126. el.classList.add('hidden');
  127. }
  128. });
  129. if (tabName === 'bridge') loadBridge();
  130. if (tabName === 'firewall') loadFirewall();
  131. if (tabName === 'routes') loadRoutes();
  132. if (tabName === 'bgp') {
  133. loadDynamicRouting();
  134. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  135. }
  136. if (tabName === 'ospf') {
  137. loadDynamicRouting();
  138. switchOspfTab(state.activeOspfTab || 'instances');
  139. }
  140. if (tabName === 'routing-filters') loadDynamicRouting();
  141. if (tabName === 'dynamic-routing') loadDynamicRouting();
  142. if (tabName === 'ppp') loadPPP();
  143. if (tabName === 'eoip') loadEoIP();
  144. if (tabName === 'aerotun') loadAeroTUN();
  145. if (tabName === 'persistence') loadDebianConfig();
  146. if (tabName === 'pppoe') loadPPPoE();
  147. if (tabName === 'wireguard') loadWireGuard();
  148. if (tabName === 'ipsec') loadIPSec();
  149. if (tabName === 'l2tp') loadL2TP();
  150. if (tabName === 'pptp') loadPPTP();
  151. if (tabName === 'tools') loadToolsView();
  152. if (tabName === 'dhcp-client') loadDHCPClients();
  153. setTimeout(initTableSorting, 50);
  154. }
  155. // Fetch all core system, network and VPN telemetry
  156. async function fetchData(isManual = false) {
  157. const spinner = document.getElementById('refresh-spinner');
  158. if (isManual && spinner) spinner.classList.add('animate-spin');
  159. try {
  160. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  161. fetch(`${API_BASE}/system/status`),
  162. fetch(`${API_BASE}/interfaces`),
  163. fetch(`${API_BASE}/vlans`),
  164. fetch(`${API_BASE}/vpn/status`),
  165. fetch(`${API_BASE}/firewall/summary`),
  166. fetch(`${API_BASE}/routing/dynamic/summary`),
  167. fetch(`${API_BASE}/bridge/summary`),
  168. fetch(`${API_BASE}/dhcp/clients/summary`),
  169. fetch(`${API_BASE}/dhcp/clients`)
  170. ]);
  171. if (dhcpSumRes && dhcpSumRes.ok) {
  172. state.dhcpSummary = await dhcpSumRes.json();
  173. const bDhcp = document.getElementById('badge-dhcp-client-count');
  174. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  175. }
  176. if (dhcpClientsRes && dhcpClientsRes.ok) {
  177. state.dhcpClients = await dhcpClientsRes.json();
  178. }
  179. if (brSummaryRes.ok) {
  180. state.bridgeSummary = await brSummaryRes.json();
  181. const bBridge = document.getElementById('badge-bridge-count');
  182. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  183. const sBr = document.getElementById('bridge-stat-bridges');
  184. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  185. const sPorts = document.getElementById('bridge-stat-ports');
  186. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  187. const sHosts = document.getElementById('bridge-stat-hosts');
  188. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  189. }
  190. if (statusRes.ok) state.systemStatus = await statusRes.json();
  191. if (ifacesRes.ok) {
  192. const ifacesData = await ifacesRes.json();
  193. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  194. state.interfaces = rawIfaces.filter(i => {
  195. if (!i.name) return false;
  196. if (i.name.startsWith('ep_')) return false;
  197. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  198. });
  199. try { populateToolsInterfaces(); } catch (e) {}
  200. }
  201. if (vlansRes.ok) {
  202. const vlansData = await vlansRes.json();
  203. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  204. }
  205. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  206. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  207. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  208. updateSystemMetrics();
  209. updateBadges();
  210. if (state.activeTab === 'dashboard') renderDashboard();
  211. if (state.activeTab === 'interfaces') renderInterfacesList();
  212. if (state.activeTab === 'vlans') renderVlansList();
  213. if (state.activeTab === 'firewall') loadFirewall(false);
  214. if (state.activeTab === 'routes') loadRoutes(false);
  215. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  216. if (state.activeTab === 'ppp') loadPPP(false);
  217. if (state.activeTab === 'eoip') loadEoIP(false);
  218. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  219. if (state.activeTab === 'pppoe') loadPPPoE(false);
  220. if (state.activeTab === 'wireguard') loadWireGuard(false);
  221. if (state.activeTab === 'ipsec') loadIPSec(false);
  222. if (state.activeTab === 'l2tp') loadL2TP(false);
  223. if (state.activeTab === 'pptp') loadPPTP(false);
  224. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  225. } catch (err) {
  226. console.error('Failed to fetch router state:', err);
  227. } finally {
  228. if (isManual && spinner) {
  229. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  230. }
  231. }
  232. }
  233. // Update Top KPI and Sidebar Telemetry
  234. function updateSystemMetrics() {
  235. const s = state.systemStatus;
  236. const v = state.vpnStatus;
  237. if (!s) return;
  238. // Sidebar Host & Uptime
  239. const sideHost = document.getElementById('side-hostname');
  240. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  241. const sideUp = document.getElementById('side-uptime');
  242. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  243. const sideGw = document.getElementById('side-gateway-ip');
  244. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  245. // Compute CPU Metrics
  246. let cpuPct = 0;
  247. if (s.cpu_pct !== undefined) {
  248. cpuPct = s.cpu_pct;
  249. } else if (s.cpu_load && s.cpu_load.length > 0) {
  250. const cores = s.cpu_cores || 1;
  251. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  252. }
  253. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  254. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  255. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  256. // Sidebar CPU
  257. const sideCpuVal = document.getElementById('side-cpu-val');
  258. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  259. const sideCpuBar = document.getElementById('side-cpu-bar');
  260. if (sideCpuBar) {
  261. sideCpuBar.style.width = cpuWidth;
  262. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  263. }
  264. // Dashboard CPU Card
  265. const dashCpuVal = document.getElementById('dash-cpu-val');
  266. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  267. const dashCpuBar = document.getElementById('dash-cpu-bar');
  268. if (dashCpuBar) {
  269. dashCpuBar.style.width = cpuWidth;
  270. if (cpuPct > 85) {
  271. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  272. } else if (cpuPct > 65) {
  273. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  274. } else {
  275. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  276. }
  277. }
  278. const dashCpuCores = document.getElementById('dash-cpu-cores');
  279. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  280. const dashCpuLoad = document.getElementById('dash-cpu-load');
  281. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  282. const dashCpuStatus = document.getElementById('dash-cpu-status');
  283. if (dashCpuStatus) {
  284. if (cpuPct > 85) {
  285. dashCpuStatus.innerText = 'High';
  286. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  287. } else if (cpuPct > 65) {
  288. dashCpuStatus.innerText = 'Heavy';
  289. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  290. } else {
  291. dashCpuStatus.innerText = 'Normal';
  292. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  293. }
  294. }
  295. // Compute RAM Metrics
  296. const memPct = Math.round(s.mem_usage_pct || 0);
  297. const memPctStr = `${memPct}%`;
  298. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  299. const usedMB = s.mem_used_mb || 0;
  300. const totalMB = s.mem_total_mb || 0;
  301. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  302. function fmtMemMB(mb) {
  303. if (mb >= 1024) {
  304. return `${(mb / 1024).toFixed(1)} GB`;
  305. }
  306. return `${mb} MB`;
  307. }
  308. // Sidebar RAM
  309. const sideRamVal = document.getElementById('side-ram-val');
  310. if (sideRamVal) sideRamVal.innerText = memPctStr;
  311. const sideRamBar = document.getElementById('side-ram-bar');
  312. if (sideRamBar) sideRamBar.style.width = memWidth;
  313. // Dashboard RAM Card
  314. const dashRamVal = document.getElementById('dash-ram-val');
  315. if (dashRamVal) dashRamVal.innerText = memPctStr;
  316. const dashRamBar = document.getElementById('dash-ram-bar');
  317. if (dashRamBar) {
  318. dashRamBar.style.width = memWidth;
  319. if (memPct > 85) {
  320. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  321. } else if (memPct > 70) {
  322. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  323. } else {
  324. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  325. }
  326. }
  327. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  328. if (dashRamUsedTotal) {
  329. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  330. }
  331. const dashRamFree = document.getElementById('dash-ram-free');
  332. if (dashRamFree) {
  333. dashRamFree.innerText = fmtMemMB(freeMB);
  334. }
  335. const dashRamStatus = document.getElementById('dash-ram-status');
  336. if (dashRamStatus) {
  337. if (memPct > 85) {
  338. dashRamStatus.innerText = 'High';
  339. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  340. } else {
  341. dashRamStatus.innerText = 'Active';
  342. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  343. }
  344. }
  345. // Legacy Dashboard Stats (Safe checks)
  346. const elIfacesUp = document.getElementById('stat-ifaces-up');
  347. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  348. const elIfacesTot = document.getElementById('stat-ifaces-total');
  349. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  350. const elIfacesDown = document.getElementById('stat-ifaces-down');
  351. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  352. const elVlans = document.getElementById('stat-vlans-count');
  353. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  354. // VPN Status Indicators
  355. if (v) {
  356. const totalActive = v.total_active_tunnels || 0;
  357. const statVpnActive = document.getElementById('stat-vpn-active');
  358. if (statVpnActive) statVpnActive.innerText = totalActive;
  359. const tunnelsDot = document.getElementById('tunnels-dot');
  360. const tunnelsLabel = document.getElementById('tunnels-label');
  361. if (tunnelsDot && tunnelsLabel) {
  362. if (totalActive > 0) {
  363. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  364. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  365. } else {
  366. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  367. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  368. }
  369. }
  370. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  371. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  372. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  373. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  374. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  375. }
  376. // Total Live Bandwidth Rate
  377. let totalRx = 0;
  378. let totalTx = 0;
  379. (state.interfaces || []).forEach(i => {
  380. if (i.rate) {
  381. totalRx += i.rate.rx_bytes_sec || 0;
  382. totalTx += i.rate.tx_bytes_sec || 0;
  383. }
  384. });
  385. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  386. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  387. }
  388. function setDotBadge(id, active) {
  389. const el = document.getElementById(id);
  390. if (!el) return;
  391. if (active) {
  392. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  393. } else {
  394. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  395. }
  396. }
  397. function updateBadges() {
  398. const bIfaces = document.getElementById('badge-ifaces-count');
  399. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  400. const bVlans = document.getElementById('badge-vlans-count');
  401. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  402. if (state.fwSummary) {
  403. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  404. const badgeFw = document.getElementById('badge-firewall-count');
  405. if (badgeFw) badgeFw.innerText = totalFwRules;
  406. }
  407. if (state.vpnStatus) {
  408. const v = state.vpnStatus;
  409. const bEoIP = document.getElementById('badge-eoip-count');
  410. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  411. const bAero = document.getElementById('badge-aerotun-count');
  412. if (bAero) bAero.innerText = v.total_aerotun || 0;
  413. const bPPPSess = document.getElementById('badge-ppp-sessions');
  414. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  415. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  416. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  417. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  418. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  419. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  420. }
  421. if (state.dynSummary) {
  422. const d = state.dynSummary;
  423. setDotBadge('badge-bgp-dot', d.bgp_running);
  424. setDotBadge('badge-ospf-dot', d.ospf_running);
  425. const bBgp = document.getElementById('badge-bgp-count');
  426. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  427. const bOspf = document.getElementById('badge-ospf-count');
  428. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  429. const bFilters = document.getElementById('badge-filters-count');
  430. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  431. }
  432. }
  433. // Render Dashboard View
  434. function renderDashboard() {
  435. const matrix = document.getElementById('port-matrix');
  436. matrix.innerHTML = '';
  437. (state.interfaces || []).forEach(iface => {
  438. const isUp = iface.state === 'UP';
  439. const isVlan = iface.is_vlan;
  440. const portCard = document.createElement('div');
  441. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  442. isUp
  443. ? (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')
  444. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  445. }`;
  446. portCard.onclick = () => openIfaceModal(iface.name);
  447. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  448. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  449. portCard.innerHTML = `
  450. <div class="flex items-center justify-between mb-2">
  451. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  452. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  453. </div>
  454. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  455. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  456. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  457. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  458. </div>
  459. `;
  460. matrix.appendChild(portCard);
  461. });
  462. const ifaceTbody = document.getElementById('quick-interfaces-table');
  463. if (ifaceTbody) {
  464. ifaceTbody.innerHTML = '';
  465. (state.interfaces || []).forEach(i => {
  466. const isUp = i.state === 'UP';
  467. const tr = document.createElement('tr');
  468. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  469. tr.onclick = () => openIfaceModal(i.name);
  470. const rxStr = i.rate?.rx_human || '0 B/s';
  471. const txStr = i.rate?.tx_human || '0 B/s';
  472. tr.innerHTML = `
  473. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  474. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  475. <span>${i.name}</span>
  476. </td>
  477. <td class="py-2.5 text-slate-300 font-sans">
  478. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  479. </td>
  480. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  481. <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>
  482. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  483. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  484. </td>
  485. <td class="py-2.5 text-right font-sans font-semibold">
  486. <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>
  487. </td>
  488. `;
  489. ifaceTbody.appendChild(tr);
  490. });
  491. }
  492. const vlanTbody = document.getElementById('quick-vlans-table');
  493. if (vlanTbody) {
  494. vlanTbody.innerHTML = '';
  495. }
  496. }
  497. // Expand / Collapse Handlers
  498. function toggleExpand(parentName) {
  499. if (state.expandedParents.has(parentName)) {
  500. state.expandedParents.delete(parentName);
  501. } else {
  502. state.expandedParents.add(parentName);
  503. }
  504. renderInterfacesList();
  505. }
  506. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  507. function supportsVLAN(iface) {
  508. if (!iface) return false;
  509. if (iface.is_vlan) return false;
  510. const name = (iface.name || '').toLowerCase();
  511. const type = (iface.type || '').toLowerCase();
  512. const role = (iface.role || '').toLowerCase();
  513. // Exclude loopback
  514. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  515. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  516. if (type === 'wireguard' || name.startsWith('wg')) return false;
  517. // Exclude PPP / PPPoE
  518. if (type === 'ppp' || name.startsWith('ppp')) return false;
  519. // Exclude other Layer 3 tunnels and dummy devices
  520. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  521. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  522. return false;
  523. }
  524. // If name already contains a dot, it's already a sub-interface
  525. if (name.includes('.')) return false;
  526. return true;
  527. }
  528. // Expand / Collapse Handlers
  529. function toggleExpand(parentName) {
  530. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  531. if (childVlans.length === 0) {
  532. // Cannot expand an interface with no VLANs
  533. state.expandedParents.delete(parentName);
  534. return;
  535. }
  536. if (state.expandedParents.has(parentName)) {
  537. state.expandedParents.delete(parentName);
  538. } else {
  539. state.expandedParents.add(parentName);
  540. }
  541. renderInterfacesList();
  542. }
  543. function expandAllIfaces(expand) {
  544. if (expand) {
  545. (state.interfaces || []).forEach(i => {
  546. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  547. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  548. });
  549. } else {
  550. state.expandedParents.clear();
  551. }
  552. renderInterfacesList();
  553. }
  554. // Filter and Render Hierarchical Interfaces List
  555. function filterIfaces(filter) {
  556. state.ifaceFilter = filter || 'all';
  557. renderInterfacesList();
  558. }
  559. function renderInterfacesList() {
  560. const tbody = document.getElementById('interfaces-tree-tbody');
  561. const emptyState = document.getElementById('interfaces-empty-state');
  562. const summary = document.getElementById('ifaces-list-summary');
  563. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  564. tbody.innerHTML = '';
  565. const allIfaces = state.interfaces || [];
  566. const allVlans = state.vlans || [];
  567. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  568. const filteredParents = parentIfaces.filter(parent => {
  569. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  570. if (query) {
  571. const matchName = parent.name.toLowerCase().includes(query);
  572. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  573. const matchRole = (parent.role || '').toLowerCase().includes(query);
  574. const matchType = (parent.type || '').toLowerCase().includes(query);
  575. const matchVlan = childVlans.some(v =>
  576. v.name.toLowerCase().includes(query) ||
  577. String(v.vlan_id).includes(query) ||
  578. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  579. (v.description || '').toLowerCase().includes(query)
  580. );
  581. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  582. }
  583. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  584. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  585. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  586. return true;
  587. });
  588. if (summary) {
  589. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  590. }
  591. if (filteredParents.length === 0) {
  592. emptyState?.classList.remove('hidden');
  593. return;
  594. }
  595. emptyState?.classList.add('hidden');
  596. filteredParents.forEach(parent => {
  597. const isUp = parent.state === 'UP';
  598. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  599. const hasVlans = childVlans.length > 0;
  600. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  601. const canHaveVlan = supportsVLAN(parent);
  602. const parentRow = document.createElement('tr');
  603. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  604. parentRow.innerHTML = `
  605. <td class="py-3 px-3 text-center">
  606. ${hasVlans ? `
  607. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  608. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  609. <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">
  610. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  611. </svg>
  612. </button>
  613. ` : `
  614. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  615. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  616. </div>
  617. `}
  618. </td>
  619. <td class="py-3 px-4">
  620. <div class="flex items-center space-x-2.5">
  621. <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">
  622. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  623. </div>
  624. <div>
  625. <div class="flex items-center gap-2">
  626. ${hasVlans ? `
  627. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  628. <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>
  629. ` : `
  630. <span class="font-bold text-white text-sm">${parent.name}</span>
  631. <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>
  632. `}
  633. </div>
  634. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  635. </div>
  636. </div>
  637. </td>
  638. <td class="py-3 px-4 font-sans">
  639. <div class="flex items-center gap-1.5">
  640. <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>
  641. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  642. </div>
  643. </td>
  644. <td class="py-3 px-4">
  645. ${parent.ipv4 && parent.ipv4.length > 0
  646. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  647. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  648. }
  649. ${(() => {
  650. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  651. if (!c) return '';
  652. 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');
  653. 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>`;
  654. })()}
  655. </td>
  656. <td class="py-3 px-4 text-slate-400 text-[11px]">
  657. <div>${parent.mac || 'N/A'}</div>
  658. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  659. </td>
  660. <td class="py-3 px-4 text-[11px]">
  661. <div class="flex items-center space-x-2">
  662. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  663. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  664. </div>
  665. </td>
  666. <td class="py-3 px-4 font-sans">
  667. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  668. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  669. 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'
  670. }" title="Click to toggle link status">
  671. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  672. <span>${parent.state}</span>
  673. </button>
  674. </td>
  675. <td class="py-3 px-4 text-right space-x-2 font-sans">
  676. ${(() => {
  677. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  678. if (c) {
  679. 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>`;
  680. }
  681. 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>`;
  682. })()}
  683. ${canHaveVlan ? `
  684. <button onclick="openVlanModal('${parent.name}')"
  685. 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">
  686. + Add VLAN
  687. </button>
  688. ` : ''}
  689. <button onclick="openIfaceModal('${parent.name}')"
  690. 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">
  691. Configure
  692. </button>
  693. </td>
  694. `;
  695. tbody.appendChild(parentRow);
  696. if (isExpanded) {
  697. const drawerRow = document.createElement('tr');
  698. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  699. const drawerCell = document.createElement('td');
  700. drawerCell.colSpan = 8;
  701. drawerCell.className = 'p-0';
  702. drawerCell.innerHTML = `
  703. <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">
  704. <div class="flex items-center justify-between mb-3">
  705. <div class="flex items-center space-x-3">
  706. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  707. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  708. </span>
  709. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  710. ${childVlans.length} Attached
  711. </span>
  712. </div>
  713. <button onclick="openVlanModal('${parent.name}')"
  714. 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">
  715. <span>+ Create VLAN on ${parent.name}</span>
  716. </button>
  717. </div>
  718. ${childVlans.length === 0 ? `
  719. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  720. <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>
  721. <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">
  722. <span>+ Create Your First VLAN on ${parent.name}</span>
  723. </button>
  724. </div>
  725. ` : `
  726. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  727. <table class="w-full text-left text-xs font-mono">
  728. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  729. <tr>
  730. <th class="py-2.5 px-4">VLAN ID</th>
  731. <th class="py-2.5 px-4">Interface Device</th>
  732. <th class="py-2.5 px-4">Subnet Gateway</th>
  733. <th class="py-2.5 px-4">Role / Alias</th>
  734. <th class="py-2.5 px-4">MTU</th>
  735. <th class="py-2.5 px-4">Throughput</th>
  736. <th class="py-2.5 px-4">Status</th>
  737. <th class="py-2.5 px-4 text-right">Actions</th>
  738. </tr>
  739. </thead>
  740. <tbody class="divide-y divide-slate-800/70">
  741. ${childVlans.map(v => {
  742. const isVlanUp = v.state === 'UP';
  743. return `
  744. <tr class="hover:bg-slate-800/40 transition">
  745. <td class="py-2.5 px-4">
  746. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  747. VLAN ${v.vlan_id}
  748. </span>
  749. </td>
  750. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  751. <span class="text-cyan-500">└─</span>
  752. <span>${v.name}</span>
  753. </td>
  754. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  755. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  756. ${(() => {
  757. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  758. if (!c) return '';
  759. 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';
  760. 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>`;
  761. })()}
  762. </td>
  763. <td class="py-2.5 px-4 font-sans text-slate-300">
  764. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  765. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  766. </td>
  767. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  768. <td class="py-2.5 px-4 text-[11px]">
  769. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  770. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  771. </td>
  772. <td class="py-2.5 px-4 font-sans">
  773. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  774. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  775. 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'
  776. }">
  777. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  778. <span>${v.state}</span>
  779. </button>
  780. </td>
  781. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  782. ${(() => {
  783. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  784. if (c) {
  785. 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>`;
  786. }
  787. 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>`;
  788. })()}
  789. <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>
  790. <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>
  791. </td>
  792. </tr>
  793. `;
  794. }).join('')}
  795. </tbody>
  796. </table>
  797. </div>
  798. `}
  799. </div>
  800. `;
  801. drawerRow.appendChild(drawerCell);
  802. tbody.appendChild(drawerRow);
  803. }
  804. });
  805. }
  806. // Render VLANs Dedicated View
  807. function renderVlansList() {
  808. const tbody = document.getElementById('vlans-table-body');
  809. if (!tbody) return;
  810. const emptyState = document.getElementById('vlans-empty-state');
  811. const countBadge = document.getElementById('vlans-table-count');
  812. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  813. tbody.innerHTML = '';
  814. const allVlans = state.vlans || [];
  815. if (countBadge) countBadge.innerText = allVlans.length;
  816. const filtered = allVlans.filter(v => {
  817. if (!query) return true;
  818. return v.name.toLowerCase().includes(query) ||
  819. String(v.vlan_id).includes(query) ||
  820. (v.description || '').toLowerCase().includes(query) ||
  821. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  822. });
  823. if (allVlans.length === 0) {
  824. emptyState.classList.remove('hidden');
  825. return;
  826. }
  827. emptyState.classList.add('hidden');
  828. filtered.forEach(v => {
  829. const isUp = v.state === 'UP';
  830. const tr = document.createElement('tr');
  831. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  832. tr.innerHTML = `
  833. <td class="py-3 px-4">
  834. <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">
  835. VLAN ${v.vlan_id}
  836. </span>
  837. </td>
  838. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  839. <td class="py-3 px-4 text-slate-300">
  840. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  841. </td>
  842. <td class="py-3 px-4 text-emerald-400 font-medium">
  843. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  844. </td>
  845. <td class="py-3 px-4 text-slate-300 font-sans">
  846. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  847. </td>
  848. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  849. <td class="py-3 px-4 font-sans">
  850. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  851. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  852. 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'
  853. }">
  854. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  855. <span>${v.state}</span>
  856. </button>
  857. </td>
  858. <td class="py-3 px-4 text-right space-x-2 font-sans">
  859. <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>
  860. <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>
  861. </td>
  862. `;
  863. tbody.appendChild(tr);
  864. });
  865. }
  866. // Toggle interface UP / DOWN
  867. async function toggleInterfaceState(name, newState) {
  868. try {
  869. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  870. method: 'POST',
  871. headers: { 'Content-Type': 'application/json' },
  872. body: JSON.stringify({ state: newState })
  873. });
  874. const data = await res.json();
  875. if (res.ok) {
  876. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  877. fetchData(false);
  878. } else {
  879. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  880. }
  881. } catch (err) {
  882. showToast('Error', err.message, 'error');
  883. }
  884. }
  885. // ---------------- MikroTik Flag & Utilities ----------------
  886. function renderMikroTikFlag(running, disabled) {
  887. if (running) {
  888. 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>`;
  889. }
  890. if (disabled) {
  891. 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>`;
  892. }
  893. 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>`;
  894. }
  895. function copyToClipboard(text, label = 'Text') {
  896. navigator.clipboard.writeText(text).then(() => {
  897. showToast('Copied', `${label} copied to clipboard`, 'success');
  898. }).catch(() => {
  899. prompt('Copy value:', text);
  900. });
  901. }
  902. // ======================== PPP Profiles Shared Helper ========================
  903. async function fetchPPPProfilesList() {
  904. try {
  905. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  906. if (res.ok) {
  907. state.pppProfiles = await res.json();
  908. }
  909. } catch (err) {
  910. console.error('Failed to load PPP profiles:', err);
  911. }
  912. }
  913. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  914. const sel = document.getElementById(selectId);
  915. if (!sel) return;
  916. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  917. { name: 'default', use_encryption: 'no' },
  918. { name: 'default-encryption', use_encryption: 'required' }
  919. ];
  920. sel.innerHTML = '';
  921. profiles.forEach(p => {
  922. const opt = document.createElement('option');
  923. opt.value = p.name;
  924. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  925. opt.innerText = `${p.name}${encBadge}`;
  926. sel.appendChild(opt);
  927. });
  928. if (selectedVal) {
  929. sel.value = selectedVal;
  930. } else {
  931. sel.value = defaultVal;
  932. }
  933. if (!sel.value && sel.options.length > 0) {
  934. sel.selectedIndex = 0;
  935. }
  936. }
  937. // ======================== PPPoE Multi-Instance ========================
  938. async function loadPPPoE(populateInputs = true) {
  939. try {
  940. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  941. await fetchPPPProfilesList();
  942. }
  943. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  944. const list = await res.json();
  945. state.pppoeList = Array.isArray(list) ? list : [];
  946. const badge = document.getElementById('pppoe-count-badge');
  947. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  948. const tbody = document.getElementById('pppoe-table-body');
  949. const empty = document.getElementById('pppoe-empty');
  950. if (!tbody) return;
  951. tbody.innerHTML = '';
  952. if (state.pppoeList.length === 0) {
  953. if (empty) empty.classList.remove('hidden');
  954. } else {
  955. if (empty) empty.classList.add('hidden');
  956. state.pppoeList.forEach(inst => {
  957. const tr = document.createElement('tr');
  958. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  959. tr.innerHTML = `
  960. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  961. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  962. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  963. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  964. <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>
  965. <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>
  966. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  967. <td class="py-2.5 px-3 text-center">
  968. <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'}">
  969. ${inst.default_route ? 'Yes' : 'No'}
  970. </span>
  971. </td>
  972. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  973. ${inst.running ? `
  974. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  975. ` : `
  976. <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>
  977. `}
  978. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  979. ${inst.disabled ? 'Enable' : 'Disable'}
  980. </button>
  981. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  982. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  983. </td>
  984. `;
  985. tbody.appendChild(tr);
  986. });
  987. }
  988. } catch (err) {
  989. console.error('Failed to load PPPoE:', err);
  990. }
  991. }
  992. function openAddPPPoEModal() {
  993. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  994. document.getElementById('pppoe-modal-edit-orig').value = '';
  995. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  996. document.getElementById('pppoe-modal-name').readOnly = false;
  997. document.getElementById('pppoe-modal-user').value = '';
  998. document.getElementById('pppoe-modal-pass').value = '';
  999. document.getElementById('pppoe-modal-service').value = '';
  1000. document.getElementById('pppoe-modal-mtu').value = '1492';
  1001. document.getElementById('pppoe-modal-defroute').checked = true;
  1002. document.getElementById('pppoe-modal-reconnect').checked = true;
  1003. document.getElementById('pppoe-modal-disabled').checked = false;
  1004. // Populate profiles
  1005. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1006. // Populate interfaces
  1007. const sel = document.getElementById('pppoe-modal-iface');
  1008. sel.innerHTML = '';
  1009. (state.interfaces || []).forEach(i => {
  1010. if (i.name === 'lo') return;
  1011. const opt = document.createElement('option');
  1012. opt.value = i.name;
  1013. opt.innerText = `${i.name} (${i.role || i.type})`;
  1014. sel.appendChild(opt);
  1015. });
  1016. document.getElementById('pppoe-modal').classList.remove('hidden');
  1017. }
  1018. function openEditPPPoEModal(name) {
  1019. const inst = (state.pppoeList || []).find(i => i.name === name);
  1020. if (!inst) return;
  1021. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1022. document.getElementById('pppoe-modal-edit-orig').value = name;
  1023. document.getElementById('pppoe-modal-name').value = inst.name;
  1024. document.getElementById('pppoe-modal-name').readOnly = true;
  1025. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1026. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1027. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1028. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1029. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1030. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1031. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1032. // Populate profiles
  1033. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1034. const sel = document.getElementById('pppoe-modal-iface');
  1035. sel.innerHTML = '';
  1036. (state.interfaces || []).forEach(i => {
  1037. if (i.name === 'lo') return;
  1038. const opt = document.createElement('option');
  1039. opt.value = i.name;
  1040. opt.innerText = `${i.name} (${i.role || i.type})`;
  1041. if (i.name === inst.interface) opt.selected = true;
  1042. sel.appendChild(opt);
  1043. });
  1044. document.getElementById('pppoe-modal').classList.remove('hidden');
  1045. }
  1046. function closePPPoEModal() {
  1047. document.getElementById('pppoe-modal').classList.add('hidden');
  1048. }
  1049. async function submitSavePPPoE(e) {
  1050. e.preventDefault();
  1051. const name = document.getElementById('pppoe-modal-name').value.trim();
  1052. const iface = document.getElementById('pppoe-modal-iface').value;
  1053. const user = document.getElementById('pppoe-modal-user').value.trim();
  1054. const pass = document.getElementById('pppoe-modal-pass').value;
  1055. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1056. const service = document.getElementById('pppoe-modal-service').value.trim();
  1057. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1058. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1059. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1060. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1061. try {
  1062. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1063. method: 'POST',
  1064. headers: { 'Content-Type': 'application/json' },
  1065. body: JSON.stringify({
  1066. name,
  1067. interface: iface,
  1068. username: user,
  1069. password: pass,
  1070. profile: profile,
  1071. service_name: service,
  1072. mtu,
  1073. default_route: defRoute,
  1074. auto_reconnect: reconnect,
  1075. disabled
  1076. })
  1077. });
  1078. if (res.ok) {
  1079. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1080. closePPPoEModal();
  1081. loadPPPoE(false);
  1082. fetchData(false);
  1083. } else {
  1084. const err = await res.json();
  1085. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1086. }
  1087. } catch (err) {
  1088. showToast('Error', err.message, 'error');
  1089. }
  1090. }
  1091. async function connectPPPoEInstance(name) {
  1092. try {
  1093. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1094. if (res.ok) {
  1095. showToast('Connecting', `Dialing ${name}...`, 'info');
  1096. setTimeout(() => loadPPPoE(false), 2000);
  1097. }
  1098. } catch (err) {
  1099. showToast('Error', err.message, 'error');
  1100. }
  1101. }
  1102. async function disconnectPPPoEInstance(name) {
  1103. try {
  1104. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1105. if (res.ok) {
  1106. showToast('Disconnected', `${name} session terminated`, 'info');
  1107. setTimeout(() => loadPPPoE(false), 1000);
  1108. }
  1109. } catch (err) {
  1110. showToast('Error', err.message, 'error');
  1111. }
  1112. }
  1113. async function togglePPPoEState(name, enable) {
  1114. try {
  1115. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1116. method: 'POST',
  1117. headers: { 'Content-Type': 'application/json' },
  1118. body: JSON.stringify({ enabled: enable })
  1119. });
  1120. if (res.ok) {
  1121. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1122. loadPPPoE(false);
  1123. }
  1124. } catch (err) {
  1125. showToast('Error', err.message, 'error');
  1126. }
  1127. }
  1128. async function deletePPPoEInstance(name) {
  1129. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1130. try {
  1131. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1132. if (res.ok) {
  1133. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1134. loadPPPoE(false);
  1135. fetchData(false);
  1136. }
  1137. } catch (err) {
  1138. showToast('Error', err.message, 'error');
  1139. }
  1140. }
  1141. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1142. state.wgSubTab = 'ifaces';
  1143. function switchWGSubTab(tab) {
  1144. state.wgSubTab = tab;
  1145. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1146. const peersPanel = document.getElementById('wg-subtab-peers');
  1147. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1148. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1149. if (tab === 'ifaces') {
  1150. ifacesPanel?.classList.remove('hidden');
  1151. peersPanel?.classList.add('hidden');
  1152. 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';
  1153. 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';
  1154. } else {
  1155. ifacesPanel?.classList.add('hidden');
  1156. peersPanel?.classList.remove('hidden');
  1157. 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';
  1158. 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';
  1159. renderWGPeers();
  1160. }
  1161. }
  1162. async function loadWireGuard(populateInputs = true) {
  1163. try {
  1164. const [ifacesRes, peersRes] = await Promise.all([
  1165. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1166. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1167. ]);
  1168. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1169. const peers = peersRes.ok ? await peersRes.json() : [];
  1170. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1171. state.wgPeers = Array.isArray(peers) ? peers : [];
  1172. // Badges
  1173. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1174. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1175. const peersCountBadge = document.getElementById('wg-peers-count');
  1176. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1177. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1178. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1179. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1180. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1181. // Render Interfaces
  1182. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1183. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1184. if (ifacesTbody) {
  1185. ifacesTbody.innerHTML = '';
  1186. if (state.wgInterfaces.length === 0) {
  1187. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1188. } else {
  1189. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1190. state.wgInterfaces.forEach(iface => {
  1191. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1192. const tr = document.createElement('tr');
  1193. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1194. tr.innerHTML = `
  1195. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1196. <td class="py-2.5 px-3">
  1197. <div class="flex items-center gap-1.5">
  1198. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1199. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1200. </div>
  1201. </td>
  1202. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1203. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1204. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1205. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1206. ${(iface.public_key || '').substring(0, 10)}... 📋
  1207. </span>
  1208. </td>
  1209. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1210. <td class="py-2.5 px-3 text-center">
  1211. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1212. </td>
  1213. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1214. ${iface.running ? `
  1215. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1216. ` : `
  1217. <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>
  1218. `}
  1219. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1220. ${iface.disabled ? 'Enable' : 'Disable'}
  1221. </button>
  1222. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1223. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1224. </td>
  1225. `;
  1226. ifacesTbody.appendChild(tr);
  1227. });
  1228. }
  1229. }
  1230. // Populate filter dropdown in peers tab
  1231. const filterSel = document.getElementById('wg-peers-filter-iface');
  1232. if (filterSel) {
  1233. const currentVal = filterSel.value;
  1234. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1235. state.wgInterfaces.forEach(i => {
  1236. const opt = document.createElement('option');
  1237. opt.value = i.name;
  1238. opt.innerText = i.name;
  1239. if (i.name === currentVal) opt.selected = true;
  1240. filterSel.appendChild(opt);
  1241. });
  1242. }
  1243. renderWGPeers();
  1244. } catch (err) {
  1245. console.error('Failed to load WireGuard:', err);
  1246. }
  1247. }
  1248. function renderWGPeers() {
  1249. const filterSel = document.getElementById('wg-peers-filter-iface');
  1250. const selectedIface = filterSel ? filterSel.value : '';
  1251. const tbody = document.getElementById('wg-peers-table-body');
  1252. const empty = document.getElementById('wg-peers-empty');
  1253. if (!tbody) return;
  1254. tbody.innerHTML = '';
  1255. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1256. if (filtered.length === 0) {
  1257. if (empty) empty.classList.remove('hidden');
  1258. } else {
  1259. if (empty) empty.classList.add('hidden');
  1260. filtered.forEach(p => {
  1261. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1262. const tr = document.createElement('tr');
  1263. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1264. tr.innerHTML = `
  1265. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1266. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1267. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1268. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1269. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1270. ${(p.public_key || '').substring(0, 10)}... 📋
  1271. </span>
  1272. </td>
  1273. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1274. <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>
  1275. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1276. <td class="py-2.5 px-3 font-mono text-[11px]">
  1277. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1278. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1279. </td>
  1280. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1281. <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">
  1282. ${p.disabled ? 'Enable' : 'Disable'}
  1283. </button>
  1284. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1285. <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>
  1286. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1287. </td>
  1288. `;
  1289. tbody.appendChild(tr);
  1290. });
  1291. }
  1292. }
  1293. function openAddWGInterfaceModal() {
  1294. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1295. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1296. const nameEl = document.getElementById('wg-iface-modal-name');
  1297. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1298. nameEl.readOnly = false;
  1299. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1300. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1301. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1302. document.getElementById('wg-iface-modal-comment').value = '';
  1303. document.getElementById('wg-iface-modal-pubkey').value = '';
  1304. document.getElementById('wg-iface-modal-privkey').value = '';
  1305. document.getElementById('wg-iface-modal-disabled').checked = false;
  1306. generateWGInterfaceKeys();
  1307. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1308. }
  1309. function openEditWGInterfaceModal(name) {
  1310. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1311. if (!iface) return;
  1312. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1313. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1314. const nameEl = document.getElementById('wg-iface-modal-name');
  1315. nameEl.value = iface.name;
  1316. nameEl.readOnly = false; // ALLOW RENAMING
  1317. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1318. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1319. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1320. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1321. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1322. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1323. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1324. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1325. }
  1326. function closeAddWGInterfaceModal() {
  1327. document.getElementById('wg-iface-modal').classList.add('hidden');
  1328. }
  1329. async function generateWGInterfaceKeys() {
  1330. try {
  1331. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1332. const keys = await res.json();
  1333. if (res.ok) {
  1334. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1335. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1336. }
  1337. } catch (err) {
  1338. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1339. }
  1340. }
  1341. async function onWGInterfacePrivKeyInput() {
  1342. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1343. if (!privKey) return;
  1344. try {
  1345. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1346. method: 'POST',
  1347. headers: { 'Content-Type': 'application/json' },
  1348. body: JSON.stringify({ private_key: privKey })
  1349. });
  1350. if (res.ok) {
  1351. const data = await res.json();
  1352. if (data.public_key) {
  1353. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1354. }
  1355. }
  1356. } catch (err) {
  1357. // Ignore while typing
  1358. }
  1359. }
  1360. function toggleWGPrivKeyVisibility() {
  1361. const el = document.getElementById('wg-iface-modal-privkey');
  1362. const btn = document.getElementById('btn-toggle-wg-privkey');
  1363. if (el.type === 'password') {
  1364. el.type = 'text';
  1365. btn.innerText = '🙈 Hide';
  1366. } else {
  1367. el.type = 'password';
  1368. btn.innerText = '👁️ Show';
  1369. }
  1370. }
  1371. function copyWGInterfacePubKey() {
  1372. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1373. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1374. }
  1375. async function submitSaveWGInterface(e) {
  1376. e.preventDefault();
  1377. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1378. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1379. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1380. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1381. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1382. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1383. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1384. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1385. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1386. try {
  1387. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1388. method: 'POST',
  1389. headers: { 'Content-Type': 'application/json' },
  1390. body: JSON.stringify({
  1391. orig_name: origName,
  1392. name,
  1393. listen_port: port,
  1394. address: addr,
  1395. mtu,
  1396. comment,
  1397. public_key: pub,
  1398. private_key: priv,
  1399. disabled
  1400. })
  1401. });
  1402. const data = await res.json();
  1403. if (res.ok) {
  1404. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1405. closeAddWGInterfaceModal();
  1406. loadWireGuard(false);
  1407. fetchData(false);
  1408. } else {
  1409. showToast('Error', data.error || 'Failed to save interface', 'error');
  1410. }
  1411. } catch (err) {
  1412. showToast('Error', err.message, 'error');
  1413. }
  1414. }
  1415. async function startWGInterface(name) {
  1416. try {
  1417. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1418. if (res.ok) {
  1419. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1420. loadWireGuard(false);
  1421. fetchData(false);
  1422. }
  1423. } catch (err) {
  1424. showToast('Error', err.message, 'error');
  1425. }
  1426. }
  1427. async function stopWGInterface(name) {
  1428. try {
  1429. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1430. if (res.ok) {
  1431. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1432. loadWireGuard(false);
  1433. fetchData(false);
  1434. }
  1435. } catch (err) {
  1436. showToast('Error', err.message, 'error');
  1437. }
  1438. }
  1439. async function toggleWGInterfaceState(name, enable) {
  1440. try {
  1441. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1442. method: 'POST',
  1443. headers: { 'Content-Type': 'application/json' },
  1444. body: JSON.stringify({ enabled: enable })
  1445. });
  1446. if (res.ok) {
  1447. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1448. loadWireGuard(false);
  1449. fetchData(false);
  1450. }
  1451. } catch (err) {
  1452. showToast('Error', err.message, 'error');
  1453. }
  1454. }
  1455. async function deleteWGInterface(name) {
  1456. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1457. try {
  1458. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1459. if (res.ok) {
  1460. showToast('Deleted', `Interface ${name} removed`, 'success');
  1461. loadWireGuard(false);
  1462. fetchData(false);
  1463. }
  1464. } catch (err) {
  1465. showToast('Error', err.message, 'error');
  1466. }
  1467. }
  1468. function populateWGPeerIfaceSelect(selectedIface = '') {
  1469. const sel = document.getElementById('wg-peer-modal-iface');
  1470. if (!sel) return;
  1471. sel.innerHTML = '';
  1472. (state.wgInterfaces || []).forEach(i => {
  1473. const opt = document.createElement('option');
  1474. opt.value = i.name;
  1475. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1476. if (i.name === selectedIface) opt.selected = true;
  1477. sel.appendChild(opt);
  1478. });
  1479. }
  1480. function openAddWGPeerModal() {
  1481. if ((state.wgInterfaces || []).length === 0) {
  1482. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1483. openAddWGInterfaceModal();
  1484. return;
  1485. }
  1486. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1487. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1488. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1489. populateWGPeerIfaceSelect();
  1490. document.getElementById('wg-peer-modal-name').value = '';
  1491. document.getElementById('wg-peer-modal-pubkey').value = '';
  1492. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1493. document.getElementById('wg-peer-modal-endpoint').value = '';
  1494. document.getElementById('wg-peer-modal-port').value = '';
  1495. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1496. document.getElementById('wg-peer-modal-preshared').value = '';
  1497. document.getElementById('wg-peer-modal-disabled').checked = false;
  1498. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1499. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1500. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1501. }
  1502. function openEditWGPeerModal(ifaceName, pubKey) {
  1503. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1504. if (!peer) {
  1505. showToast('Not Found', 'Peer not found', 'warning');
  1506. return;
  1507. }
  1508. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1509. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1510. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1511. populateWGPeerIfaceSelect(peer.interface);
  1512. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1513. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1514. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1515. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1516. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1517. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1518. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1519. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1520. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1521. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1522. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1523. }
  1524. function closeAddWGPeerModal() {
  1525. document.getElementById('wg-peer-modal').classList.add('hidden');
  1526. }
  1527. async function generatePeerKeypairHelper() {
  1528. try {
  1529. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1530. const keys = await res.json();
  1531. if (res.ok) {
  1532. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1533. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1534. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1535. checkWGPeerKeyValidity();
  1536. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1537. }
  1538. } catch (err) {
  1539. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1540. }
  1541. }
  1542. function copyGeneratedPeerPrivKey() {
  1543. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1544. if (priv) copyToClipboard(priv, 'Client Private Key');
  1545. }
  1546. async function generatePeerPSK() {
  1547. try {
  1548. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1549. const keys = await res.json();
  1550. if (res.ok && keys.private_key) {
  1551. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1552. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1553. }
  1554. } catch (err) {
  1555. showToast('Error', err.message, 'error');
  1556. }
  1557. }
  1558. function checkWGPeerKeyValidity() {
  1559. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1560. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1561. const warningEl = document.getElementById('wg-peer-key-warning');
  1562. if (!warningEl) return;
  1563. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1564. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1565. warningEl.classList.remove('hidden');
  1566. } else {
  1567. warningEl.classList.add('hidden');
  1568. }
  1569. }
  1570. async function submitSaveWGPeer(e) {
  1571. e.preventDefault();
  1572. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1573. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1574. const iface = document.getElementById('wg-peer-modal-iface').value;
  1575. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1576. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1577. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1578. .split(',')
  1579. .map(s => s.trim())
  1580. .filter(s => s.length > 0);
  1581. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1582. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1583. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1584. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1585. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1586. // Validation
  1587. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1588. if (targetIface && targetIface.public_key === pub) {
  1589. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1590. return;
  1591. }
  1592. try {
  1593. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1594. method: 'POST',
  1595. headers: { 'Content-Type': 'application/json' },
  1596. body: JSON.stringify({
  1597. orig_interface: origIface,
  1598. orig_public_key: origPubKey,
  1599. interface: iface,
  1600. name,
  1601. public_key: pub,
  1602. allowed_ips: allowed,
  1603. endpoint_address: epHost,
  1604. endpoint_port: epPort,
  1605. persistent_keepalive: keepalive,
  1606. preshared_key: psk,
  1607. disabled
  1608. })
  1609. });
  1610. const data = await res.json();
  1611. if (res.ok) {
  1612. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1613. closeAddWGPeerModal();
  1614. loadWireGuard(false);
  1615. } else {
  1616. showToast('Error', data.error || 'Failed to save peer', 'error');
  1617. }
  1618. } catch (err) {
  1619. showToast('Error', err.message, 'error');
  1620. }
  1621. }
  1622. async function toggleWGPeerState(iface, pubkey, enable) {
  1623. try {
  1624. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1625. method: 'POST',
  1626. headers: { 'Content-Type': 'application/json' },
  1627. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1628. });
  1629. const data = await res.json();
  1630. if (res.ok) {
  1631. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1632. loadWireGuard(false);
  1633. } else {
  1634. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1635. }
  1636. } catch (err) {
  1637. showToast('Error', err.message, 'error');
  1638. }
  1639. }
  1640. async function deleteWGPeer(iface, pubkey) {
  1641. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1642. try {
  1643. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1644. method: 'POST',
  1645. headers: { 'Content-Type': 'application/json' },
  1646. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1647. });
  1648. const data = await res.json();
  1649. if (res.ok) {
  1650. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1651. loadWireGuard(false);
  1652. } else {
  1653. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1654. }
  1655. } catch (err) {
  1656. showToast('Error', err.message, 'error');
  1657. }
  1658. }
  1659. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1660. function switchIpsecModalTab(tab) {
  1661. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1662. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1663. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1664. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1665. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1666. if (tab === 'p1') {
  1667. if (p1Tab) {
  1668. 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';
  1669. }
  1670. if (p2Tab) {
  1671. 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';
  1672. }
  1673. if (p1Content) p1Content.classList.remove('hidden');
  1674. if (p2Content) p2Content.classList.add('hidden');
  1675. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1676. } else {
  1677. if (p1Tab) {
  1678. 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';
  1679. }
  1680. if (p2Tab) {
  1681. 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';
  1682. }
  1683. if (p1Content) p1Content.classList.add('hidden');
  1684. if (p2Content) p2Content.classList.remove('hidden');
  1685. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1686. }
  1687. }
  1688. function toggleIpsecPhaseStep() {
  1689. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1690. if (p1Content && !p1Content.classList.contains('hidden')) {
  1691. switchIpsecModalTab('p2');
  1692. } else {
  1693. switchIpsecModalTab('p1');
  1694. }
  1695. }
  1696. function toggleIpsecPskVisibility() {
  1697. const pskInput = document.getElementById('ipsec-modal-psk');
  1698. if (!pskInput) return;
  1699. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1700. }
  1701. function addIpsecLocalSubnet(val = '') {
  1702. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1703. if (!container) return;
  1704. const row = document.createElement('div');
  1705. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1706. row.innerHTML = `
  1707. <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">
  1708. <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>
  1709. `;
  1710. container.appendChild(row);
  1711. }
  1712. function addIpsecRemoteSubnet(val = '') {
  1713. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1714. if (!container) return;
  1715. const row = document.createElement('div');
  1716. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1717. row.innerHTML = `
  1718. <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">
  1719. <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>
  1720. `;
  1721. container.appendChild(row);
  1722. }
  1723. function updateIpsecEspProposalFromPFS(val) {
  1724. const prop = document.getElementById('ipsec-modal-espprop');
  1725. if (!prop) return;
  1726. if (val === 'none') {
  1727. prop.value = 'aes256-sha256,aes128-sha256,default';
  1728. } else {
  1729. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1730. }
  1731. }
  1732. function updateIpsecIkeProposalFromDH(dh) {
  1733. const el = document.getElementById('ipsec-modal-ikeprop');
  1734. if (el) {
  1735. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1736. }
  1737. }
  1738. function safeSetVal(id, val) {
  1739. const el = document.getElementById(id);
  1740. if (el) el.value = val;
  1741. }
  1742. function safeSetChecked(id, val) {
  1743. const el = document.getElementById(id);
  1744. if (el) el.checked = !!val;
  1745. }
  1746. function safeGetVal(id, def = '') {
  1747. const el = document.getElementById(id);
  1748. return el ? el.value : def;
  1749. }
  1750. async function loadIPSec(populateInputs = true) {
  1751. try {
  1752. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1753. const list = await res.json();
  1754. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1755. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1756. const badge = document.getElementById('ipsec-sas-badge');
  1757. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1758. const tbody = document.getElementById('ipsec-table-body');
  1759. const empty = document.getElementById('ipsec-empty');
  1760. if (!tbody) return;
  1761. tbody.innerHTML = '';
  1762. if (state.ipsecTunnels.length === 0) {
  1763. if (empty) empty.classList.remove('hidden');
  1764. } else {
  1765. if (empty) empty.classList.add('hidden');
  1766. state.ipsecTunnels.forEach(c => {
  1767. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1768. const tr = document.createElement('tr');
  1769. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1770. // Local subnets tags
  1771. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1772. 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('');
  1773. // Remote subnets tags
  1774. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1775. 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('');
  1776. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1777. const p2Name = c.phase2_name || `${c.name}_p2`;
  1778. tr.innerHTML = `
  1779. <td class="py-2.5 px-3 text-center">
  1780. ${isEstablished ? `
  1781. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1782. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1783. <span>UP</span>
  1784. </span>
  1785. ` : (c.disabled ? `
  1786. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1787. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1788. <span>DOWN</span>
  1789. </span>
  1790. ` : `
  1791. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1792. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1793. <span>IDLE</span>
  1794. </span>
  1795. `)}
  1796. </td>
  1797. <td class="py-2.5 px-4 font-bold text-white">
  1798. <div class="flex items-center gap-2">
  1799. <span class="text-amber-400">🛡</span>
  1800. <div>
  1801. <div>${escapeHtml(c.name)}</div>
  1802. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1803. </div>
  1804. </div>
  1805. </td>
  1806. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1807. <td class="py-2.5 px-4 font-sans">
  1808. <div class="flex items-center gap-1.5">
  1809. <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>
  1810. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1811. </div>
  1812. </td>
  1813. <td class="py-2.5 px-4">
  1814. <div class="space-y-1">
  1815. <div class="flex items-center flex-wrap gap-1">
  1816. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1817. ${localBadges}
  1818. </div>
  1819. <div class="flex items-center flex-wrap gap-1">
  1820. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1821. ${remoteBadges}
  1822. </div>
  1823. </div>
  1824. </td>
  1825. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1826. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1827. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1828. </div>
  1829. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1830. </td>
  1831. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1832. ${isEstablished ? `
  1833. <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>
  1834. ` : `
  1835. <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>
  1836. `}
  1837. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1838. ${c.disabled ? 'Enable' : 'Disable'}
  1839. </button>
  1840. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1841. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1842. </td>
  1843. `;
  1844. tbody.appendChild(tr);
  1845. });
  1846. }
  1847. } catch (err) {
  1848. console.error('Failed to load IPSec:', err);
  1849. }
  1850. }
  1851. function openAddIPSecModal() {
  1852. const modal = document.getElementById('ipsec-modal');
  1853. if (!modal) return;
  1854. const title = document.getElementById('ipsec-modal-title');
  1855. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1856. // Phase 1 Fields
  1857. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1858. const nameEl = document.getElementById('ipsec-modal-name');
  1859. if (nameEl) nameEl.readOnly = false;
  1860. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1861. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1862. safeSetVal('ipsec-modal-remotegw', '');
  1863. safeSetVal('ipsec-modal-localaddrs', '');
  1864. safeSetVal('ipsec-modal-comments', '');
  1865. safeSetVal('ipsec-modal-psk', '');
  1866. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1867. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1868. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1869. safeSetVal('ipsec-modal-localid', '');
  1870. safeSetVal('ipsec-modal-remoteid', '');
  1871. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1872. // Phase 2 Fields
  1873. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1874. safeSetVal('ipsec-modal-espkeylife', '28800');
  1875. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1876. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1877. safeSetChecked('ipsec-modal-autostart', true);
  1878. safeSetChecked('ipsec-modal-disabled', false);
  1879. // Clear & Populate default dynamic subnets
  1880. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1881. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1882. if (localContainer) {
  1883. localContainer.innerHTML = '';
  1884. addIpsecLocalSubnet('192.168.10.0/24');
  1885. }
  1886. if (remoteContainer) {
  1887. remoteContainer.innerHTML = '';
  1888. addIpsecRemoteSubnet('192.168.20.0/24');
  1889. }
  1890. switchIpsecModalTab('p1');
  1891. modal.classList.remove('hidden');
  1892. }
  1893. function openEditIPSecModal(name) {
  1894. const modal = document.getElementById('ipsec-modal');
  1895. if (!modal) return;
  1896. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1897. if (!conn) return;
  1898. const title = document.getElementById('ipsec-modal-title');
  1899. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1900. // Phase 1 Fields
  1901. safeSetVal('ipsec-modal-name', conn.name);
  1902. const nameEl = document.getElementById('ipsec-modal-name');
  1903. if (nameEl) nameEl.readOnly = true;
  1904. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1905. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1906. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1907. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1908. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1909. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1910. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1911. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1912. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1913. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1914. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1915. // Phase 2 Fields
  1916. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1917. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1918. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1919. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1920. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1921. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1922. // Populate dynamic subnets
  1923. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1924. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1925. if (localContainer) {
  1926. localContainer.innerHTML = '';
  1927. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1928. locals.forEach(s => addIpsecLocalSubnet(s));
  1929. }
  1930. if (remoteContainer) {
  1931. remoteContainer.innerHTML = '';
  1932. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1933. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1934. }
  1935. switchIpsecModalTab('p1');
  1936. modal.classList.remove('hidden');
  1937. }
  1938. function closeAddIPSecModal() {
  1939. const modal = document.getElementById('ipsec-modal');
  1940. if (modal) modal.classList.add('hidden');
  1941. }
  1942. async function submitSaveIPSec(e) {
  1943. if (e) e.preventDefault();
  1944. const name = safeGetVal('ipsec-modal-name').trim();
  1945. if (!name) {
  1946. showToast('Error', 'Tunnel name is required', 'error');
  1947. return;
  1948. }
  1949. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1950. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1951. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1952. const comments = safeGetVal('ipsec-modal-comments').trim();
  1953. const psk = safeGetVal('ipsec-modal-psk');
  1954. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1955. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1956. const localId = safeGetVal('ipsec-modal-localid').trim();
  1957. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1958. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1959. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1960. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1961. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1962. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1963. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1964. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1965. // Scrape dynamic local and remote subnets
  1966. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1967. const localSubnets = [];
  1968. localInputs.forEach(inp => {
  1969. const v = inp.value.trim();
  1970. if (v) localSubnets.push(v);
  1971. });
  1972. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1973. const remoteSubnets = [];
  1974. remoteInputs.forEach(inp => {
  1975. const v = inp.value.trim();
  1976. if (v) remoteSubnets.push(v);
  1977. });
  1978. try {
  1979. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  1980. method: 'POST',
  1981. headers: { 'Content-Type': 'application/json' },
  1982. body: JSON.stringify({
  1983. name,
  1984. comment: comments,
  1985. ike_version: ikeVersion,
  1986. local_addrs: localAddrs,
  1987. remote_addrs: remotegw,
  1988. preshared_key: psk,
  1989. ike_proposals: ikeProposals,
  1990. ike_keylife: ikeKeylife,
  1991. local_id: localId,
  1992. remote_id: remoteId,
  1993. dpd: dpd,
  1994. phase2_name: phase2Name,
  1995. esp_proposals: espProposals,
  1996. esp_keylife: espKeylife,
  1997. pfs_group: pfsGroup,
  1998. pfs: pfsGroup !== 'none',
  1999. local_subnets: localSubnets,
  2000. remote_subnets: remoteSubnets,
  2001. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2002. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2003. auto_start: autostart,
  2004. disabled
  2005. })
  2006. });
  2007. if (res.ok) {
  2008. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2009. closeAddIPSecModal();
  2010. loadIPSec(false);
  2011. } else {
  2012. const err = await res.json();
  2013. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2014. }
  2015. } catch (err) {
  2016. showToast('Error', err.message, 'error');
  2017. }
  2018. }
  2019. async function startIPSecTunnel(name) {
  2020. try {
  2021. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2022. if (res.ok) {
  2023. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2024. setTimeout(() => loadIPSec(false), 2000);
  2025. }
  2026. } catch (err) {
  2027. showToast('Error', err.message, 'error');
  2028. }
  2029. }
  2030. async function stopIPSecTunnel(name) {
  2031. try {
  2032. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2033. if (res.ok) {
  2034. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2035. loadIPSec(false);
  2036. }
  2037. } catch (err) {
  2038. showToast('Error', err.message, 'error');
  2039. }
  2040. }
  2041. async function toggleIPSecState(name, enable) {
  2042. try {
  2043. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2044. method: 'POST',
  2045. headers: { 'Content-Type': 'application/json' },
  2046. body: JSON.stringify({ enabled: enable })
  2047. });
  2048. if (res.ok) {
  2049. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2050. loadIPSec(false);
  2051. }
  2052. } catch (err) {
  2053. showToast('Error', err.message, 'error');
  2054. }
  2055. }
  2056. async function deleteIPSecConn(name) {
  2057. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2058. try {
  2059. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2060. if (res.ok) {
  2061. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2062. loadIPSec(false);
  2063. fetchData(false);
  2064. }
  2065. } catch (err) {
  2066. showToast('Error', err.message, 'error');
  2067. }
  2068. }
  2069. // ======================== L2TP Multi-Instance ========================
  2070. async function loadL2TP(populateInputs = true) {
  2071. try {
  2072. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2073. await fetchPPPProfilesList();
  2074. }
  2075. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2076. const list = await res.json();
  2077. state.l2tpList = Array.isArray(list) ? list : [];
  2078. const badge = document.getElementById('l2tp-count-badge');
  2079. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2080. const tbody = document.getElementById('l2tp-table-body');
  2081. const empty = document.getElementById('l2tp-empty');
  2082. if (!tbody) return;
  2083. tbody.innerHTML = '';
  2084. if (state.l2tpList.length === 0) {
  2085. if (empty) empty.classList.remove('hidden');
  2086. } else {
  2087. if (empty) empty.classList.add('hidden');
  2088. state.l2tpList.forEach(inst => {
  2089. const tr = document.createElement('tr');
  2090. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2091. tr.innerHTML = `
  2092. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2093. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2094. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2095. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2096. <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>
  2097. <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>
  2098. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2099. <td class="py-2.5 px-3 text-center">
  2100. <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'}">
  2101. ${inst.default_route ? 'Yes' : 'No'}
  2102. </span>
  2103. </td>
  2104. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2105. ${inst.running ? `
  2106. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2107. ` : `
  2108. <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>
  2109. `}
  2110. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2111. ${inst.disabled ? 'Enable' : 'Disable'}
  2112. </button>
  2113. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2114. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2115. </td>
  2116. `;
  2117. tbody.appendChild(tr);
  2118. });
  2119. }
  2120. } catch (err) {
  2121. console.error('Failed to load L2TP:', err);
  2122. }
  2123. }
  2124. async function openAddL2TPModal() {
  2125. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2126. await fetchPPPProfilesList();
  2127. }
  2128. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2129. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2130. document.getElementById('l2tp-modal-name').readOnly = false;
  2131. document.getElementById('l2tp-modal-server').value = '';
  2132. document.getElementById('l2tp-modal-user').value = '';
  2133. document.getElementById('l2tp-modal-pass').value = '';
  2134. document.getElementById('l2tp-modal-ipsec').value = '';
  2135. document.getElementById('l2tp-modal-defroute').checked = true;
  2136. document.getElementById('l2tp-modal-disabled').checked = false;
  2137. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2138. document.getElementById('l2tp-modal').classList.remove('hidden');
  2139. }
  2140. async function openEditL2TPModal(name) {
  2141. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2142. await fetchPPPProfilesList();
  2143. }
  2144. const inst = (state.l2tpList || []).find(i => i.name === name);
  2145. if (!inst) return;
  2146. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2147. document.getElementById('l2tp-modal-name').value = inst.name;
  2148. document.getElementById('l2tp-modal-name').readOnly = true;
  2149. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2150. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2151. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2152. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2153. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2154. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2155. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2156. document.getElementById('l2tp-modal').classList.remove('hidden');
  2157. }
  2158. function closeL2TPModal() {
  2159. document.getElementById('l2tp-modal').classList.add('hidden');
  2160. }
  2161. async function submitSaveL2TP(e) {
  2162. e.preventDefault();
  2163. const name = document.getElementById('l2tp-modal-name').value.trim();
  2164. const server = document.getElementById('l2tp-modal-server').value.trim();
  2165. const user = document.getElementById('l2tp-modal-user').value.trim();
  2166. const pass = document.getElementById('l2tp-modal-pass').value;
  2167. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2168. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2169. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2170. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2171. try {
  2172. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2173. method: 'POST',
  2174. headers: { 'Content-Type': 'application/json' },
  2175. body: JSON.stringify({
  2176. name,
  2177. connect_to: server,
  2178. username: user,
  2179. password: pass,
  2180. profile: profile,
  2181. ipsec_secret: ipsec,
  2182. default_route: defRoute,
  2183. disabled
  2184. })
  2185. });
  2186. if (res.ok) {
  2187. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2188. closeL2TPModal();
  2189. loadL2TP(false);
  2190. fetchData(false);
  2191. }
  2192. } catch (err) {
  2193. showToast('Error', err.message, 'error');
  2194. }
  2195. }
  2196. async function connectL2TPInstance(name) {
  2197. try {
  2198. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2199. if (res.ok) {
  2200. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2201. setTimeout(() => loadL2TP(false), 2000);
  2202. }
  2203. } catch (err) {
  2204. showToast('Error', err.message, 'error');
  2205. }
  2206. }
  2207. async function disconnectL2TPInstance(name) {
  2208. try {
  2209. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2210. if (res.ok) {
  2211. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2212. loadL2TP(false);
  2213. }
  2214. } catch (err) {
  2215. showToast('Error', err.message, 'error');
  2216. }
  2217. }
  2218. async function toggleL2TPState(name, enable) {
  2219. try {
  2220. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2221. method: 'POST',
  2222. headers: { 'Content-Type': 'application/json' },
  2223. body: JSON.stringify({ enabled: enable })
  2224. });
  2225. if (res.ok) {
  2226. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2227. loadL2TP(false);
  2228. }
  2229. } catch (err) {
  2230. showToast('Error', err.message, 'error');
  2231. }
  2232. }
  2233. async function deleteL2TPInstance(name) {
  2234. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2235. try {
  2236. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2237. if (res.ok) {
  2238. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2239. loadL2TP(false);
  2240. fetchData(false);
  2241. }
  2242. } catch (err) {
  2243. showToast('Error', err.message, 'error');
  2244. }
  2245. }
  2246. // ======================== PPTP Multi-Instance ========================
  2247. async function loadPPTP(populateInputs = true) {
  2248. try {
  2249. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2250. await fetchPPPProfilesList();
  2251. }
  2252. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2253. const list = await res.json();
  2254. state.pptpList = Array.isArray(list) ? list : [];
  2255. const badge = document.getElementById('pptp-count-badge');
  2256. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2257. const tbody = document.getElementById('pptp-table-body');
  2258. const empty = document.getElementById('pptp-empty');
  2259. if (!tbody) return;
  2260. tbody.innerHTML = '';
  2261. if (state.pptpList.length === 0) {
  2262. if (empty) empty.classList.remove('hidden');
  2263. } else {
  2264. if (empty) empty.classList.add('hidden');
  2265. state.pptpList.forEach(inst => {
  2266. const tr = document.createElement('tr');
  2267. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2268. tr.innerHTML = `
  2269. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2270. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2271. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2272. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2273. <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>
  2274. <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>
  2275. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2276. <td class="py-2.5 px-3 text-center">
  2277. <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'}">
  2278. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2279. </span>
  2280. </td>
  2281. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2282. ${inst.running ? `
  2283. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2284. ` : `
  2285. <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>
  2286. `}
  2287. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2288. ${inst.disabled ? 'Enable' : 'Disable'}
  2289. </button>
  2290. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2291. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2292. </td>
  2293. `;
  2294. tbody.appendChild(tr);
  2295. });
  2296. }
  2297. } catch (err) {
  2298. console.error('Failed to load PPTP:', err);
  2299. }
  2300. }
  2301. async function openAddPPTPModal() {
  2302. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2303. await fetchPPPProfilesList();
  2304. }
  2305. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2306. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2307. document.getElementById('pptp-modal-name').readOnly = false;
  2308. document.getElementById('pptp-modal-server').value = '';
  2309. document.getElementById('pptp-modal-user').value = '';
  2310. document.getElementById('pptp-modal-pass').value = '';
  2311. document.getElementById('pptp-modal-mppe').checked = true;
  2312. document.getElementById('pptp-modal-defroute').checked = true;
  2313. document.getElementById('pptp-modal-disabled').checked = false;
  2314. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2315. document.getElementById('pptp-modal').classList.remove('hidden');
  2316. }
  2317. async function openEditPPTPModal(name) {
  2318. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2319. await fetchPPPProfilesList();
  2320. }
  2321. const inst = (state.pptpList || []).find(i => i.name === name);
  2322. if (!inst) return;
  2323. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2324. document.getElementById('pptp-modal-name').value = inst.name;
  2325. document.getElementById('pptp-modal-name').readOnly = true;
  2326. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2327. document.getElementById('pptp-modal-user').value = inst.username || '';
  2328. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2329. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2330. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2331. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2332. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2333. document.getElementById('pptp-modal').classList.remove('hidden');
  2334. }
  2335. function closePPTPModal() {
  2336. document.getElementById('pptp-modal').classList.add('hidden');
  2337. }
  2338. async function submitSavePPTP(e) {
  2339. e.preventDefault();
  2340. const name = document.getElementById('pptp-modal-name').value.trim();
  2341. const server = document.getElementById('pptp-modal-server').value.trim();
  2342. const user = document.getElementById('pptp-modal-user').value.trim();
  2343. const pass = document.getElementById('pptp-modal-pass').value;
  2344. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2345. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2346. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2347. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2348. try {
  2349. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2350. method: 'POST',
  2351. headers: { 'Content-Type': 'application/json' },
  2352. body: JSON.stringify({
  2353. name,
  2354. connect_to: server,
  2355. username: user,
  2356. password: pass,
  2357. profile: profile,
  2358. require_mppe: mppe,
  2359. default_route: defRoute,
  2360. auto_reconnect: true,
  2361. disabled
  2362. })
  2363. });
  2364. if (res.ok) {
  2365. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2366. closePPTPModal();
  2367. loadPPTP(false);
  2368. fetchData(false);
  2369. }
  2370. } catch (err) {
  2371. showToast('Error', err.message, 'error');
  2372. }
  2373. }
  2374. async function connectPPTPInstance(name) {
  2375. try {
  2376. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2377. if (res.ok) {
  2378. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2379. setTimeout(() => loadPPTP(false), 2000);
  2380. }
  2381. } catch (err) {
  2382. showToast('Error', err.message, 'error');
  2383. }
  2384. }
  2385. async function disconnectPPTPInstance(name) {
  2386. try {
  2387. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2388. if (res.ok) {
  2389. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2390. loadPPTP(false);
  2391. }
  2392. } catch (err) {
  2393. showToast('Error', err.message, 'error');
  2394. }
  2395. }
  2396. async function togglePPTPState(name, enable) {
  2397. try {
  2398. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2399. method: 'POST',
  2400. headers: { 'Content-Type': 'application/json' },
  2401. body: JSON.stringify({ enabled: enable })
  2402. });
  2403. if (res.ok) {
  2404. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2405. loadPPTP(false);
  2406. }
  2407. } catch (err) {
  2408. showToast('Error', err.message, 'error');
  2409. }
  2410. }
  2411. async function deletePPTPInstance(name) {
  2412. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2413. try {
  2414. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2415. if (res.ok) {
  2416. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2417. loadPPTP(false);
  2418. fetchData(false);
  2419. }
  2420. } catch (err) {
  2421. showToast('Error', err.message, 'error');
  2422. }
  2423. }
  2424. // ---------------- Modal & Helper Functions ----------------
  2425. function openVlanModal(defaultParent = '') {
  2426. const select = document.getElementById('vlan-parent');
  2427. select.innerHTML = '';
  2428. const allIfaces = state.interfaces || [];
  2429. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2430. if (eligible.length === 0) {
  2431. const opt = document.createElement('option');
  2432. opt.value = '';
  2433. opt.innerText = 'No VLAN-capable interfaces available';
  2434. select.appendChild(opt);
  2435. } else {
  2436. eligible.forEach(i => {
  2437. const opt = document.createElement('option');
  2438. opt.value = i.name;
  2439. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2440. if (i.name === defaultParent) opt.selected = true;
  2441. select.appendChild(opt);
  2442. });
  2443. }
  2444. document.getElementById('vlan-id').value = '';
  2445. document.getElementById('vlan-name').value = '';
  2446. document.getElementById('vlan-ip').value = '';
  2447. document.getElementById('vlan-desc').value = '';
  2448. autoSuggestVlanName();
  2449. document.getElementById('vlan-modal').classList.remove('hidden');
  2450. }
  2451. function closeVlanModal() {
  2452. document.getElementById('vlan-modal').classList.add('hidden');
  2453. }
  2454. function autoSuggestVlanName() {
  2455. const parent = document.getElementById('vlan-parent').value;
  2456. if (!parent) return;
  2457. const id = document.getElementById('vlan-id').value;
  2458. const nameInput = document.getElementById('vlan-name');
  2459. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2460. }
  2461. function setSubnetPreset(cidr) {
  2462. const ipInput = document.getElementById('vlan-ip');
  2463. const id = document.getElementById('vlan-id').value || '10';
  2464. ipInput.value = `192.168.${id}.1${cidr}`;
  2465. }
  2466. async function submitCreateVlan(e) {
  2467. e.preventDefault();
  2468. const btn = document.getElementById('vlan-submit-btn');
  2469. btn.disabled = true;
  2470. btn.innerText = 'Creating...';
  2471. const parent = document.getElementById('vlan-parent').value;
  2472. if (!parent) {
  2473. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2474. btn.disabled = false;
  2475. btn.innerText = 'Create VLAN';
  2476. return;
  2477. }
  2478. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2479. const name = document.getElementById('vlan-name').value.trim();
  2480. const ip = document.getElementById('vlan-ip').value.trim();
  2481. const role = document.getElementById('vlan-role').value;
  2482. const desc = document.getElementById('vlan-desc').value.trim();
  2483. try {
  2484. const res = await fetch(`${API_BASE}/vlans`, {
  2485. method: 'POST',
  2486. headers: { 'Content-Type': 'application/json' },
  2487. body: JSON.stringify({
  2488. parent_name: parent,
  2489. vlan_id: id,
  2490. name: name,
  2491. ip_address: ip,
  2492. role: role,
  2493. description: desc,
  2494. mtu: 1500,
  2495. auto_up: true
  2496. })
  2497. });
  2498. const data = await res.json();
  2499. if (res.ok) {
  2500. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2501. state.expandedParents.add(parent);
  2502. closeVlanModal();
  2503. await fetchData(true);
  2504. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2505. } else {
  2506. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2507. }
  2508. } catch (err) {
  2509. showToast('Error', err.message, 'error');
  2510. } finally {
  2511. btn.disabled = false;
  2512. btn.innerText = 'Create VLAN';
  2513. }
  2514. }
  2515. async function confirmDeleteVlan(name) {
  2516. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2517. try {
  2518. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2519. if (res.ok) {
  2520. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2521. closeIfaceModal();
  2522. fetchData(true);
  2523. }
  2524. } catch (err) {
  2525. showToast('Error', err.message, 'error');
  2526. }
  2527. }
  2528. function openIfaceModal(name) {
  2529. const iface = (state.interfaces || []).find(i => i.name === name);
  2530. if (!iface) return;
  2531. state.currentModalIface = iface.name;
  2532. document.getElementById('modal-iface-name').innerText = iface.name;
  2533. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2534. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2535. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2536. document.getElementById('modal-iface-desc').value = iface.description || '';
  2537. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2538. if (iface.is_vlan) {
  2539. delBtn.classList.remove('hidden');
  2540. } else {
  2541. delBtn.classList.add('hidden');
  2542. }
  2543. renderModalIPs(iface);
  2544. document.getElementById('iface-modal').classList.remove('hidden');
  2545. }
  2546. function renderModalIPs(iface) {
  2547. const container = document.getElementById('modal-ip-list');
  2548. container.innerHTML = '';
  2549. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2550. if (addrs.length === 0) {
  2551. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2552. return;
  2553. }
  2554. addrs.forEach(addr => {
  2555. const row = document.createElement('div');
  2556. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2557. row.innerHTML = `
  2558. <span class="text-white">${addr}</span>
  2559. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2560. `;
  2561. container.appendChild(row);
  2562. });
  2563. }
  2564. function closeIfaceModal() {
  2565. document.getElementById('iface-modal').classList.add('hidden');
  2566. state.currentModalIface = null;
  2567. }
  2568. async function setIfaceState(name, newState) {
  2569. await toggleInterfaceState(name, newState);
  2570. const updated = (state.interfaces || []).find(i => i.name === name);
  2571. if (updated) openIfaceModal(name);
  2572. }
  2573. async function applyMTU() {
  2574. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2575. try {
  2576. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2577. method: 'POST',
  2578. headers: { 'Content-Type': 'application/json' },
  2579. body: JSON.stringify({ mtu })
  2580. });
  2581. if (res.ok) {
  2582. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2583. fetchData(false);
  2584. }
  2585. } catch (err) {
  2586. showToast('Error', err.message, 'error');
  2587. }
  2588. }
  2589. async function addInterfaceIP() {
  2590. const ip = document.getElementById('modal-new-ip').value.trim();
  2591. if (!ip) return;
  2592. try {
  2593. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2594. method: 'POST',
  2595. headers: { 'Content-Type': 'application/json' },
  2596. body: JSON.stringify({ ip })
  2597. });
  2598. if (res.ok) {
  2599. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2600. document.getElementById('modal-new-ip').value = '';
  2601. await fetchData(false);
  2602. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2603. if (iface) renderModalIPs(iface);
  2604. } else {
  2605. const err = await res.json();
  2606. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2607. }
  2608. } catch (err) {
  2609. showToast('Error', err.message, 'error');
  2610. }
  2611. }
  2612. async function removeInterfaceIP(ip) {
  2613. if (!confirm(`Remove IP ${ip}?`)) return;
  2614. try {
  2615. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2616. method: 'DELETE',
  2617. headers: { 'Content-Type': 'application/json' },
  2618. body: JSON.stringify({ ip })
  2619. });
  2620. if (res.ok) {
  2621. showToast('IP Removed', `Removed ${ip}`, 'success');
  2622. await fetchData(false);
  2623. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2624. if (iface) renderModalIPs(iface);
  2625. }
  2626. } catch (err) {
  2627. showToast('Error', err.message, 'error');
  2628. }
  2629. }
  2630. async function saveInterfaceMetadata() {
  2631. const role = document.getElementById('modal-iface-role').value;
  2632. const desc = document.getElementById('modal-iface-desc').value.trim();
  2633. try {
  2634. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2635. method: 'POST',
  2636. headers: { 'Content-Type': 'application/json' },
  2637. body: JSON.stringify({ role, description: desc })
  2638. });
  2639. if (res.ok) {
  2640. showToast('Saved', 'Metadata updated', 'success');
  2641. closeIfaceModal();
  2642. fetchData(false);
  2643. }
  2644. } catch (err) {
  2645. showToast('Error', err.message, 'error');
  2646. }
  2647. }
  2648. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2649. state.fwSubTab = 'filter';
  2650. state.routesSubTab = 'routes';
  2651. function renderRuleFlag(disabled, hasComment) {
  2652. let flags = '';
  2653. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2654. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2655. return flags || '<span class="text-slate-600">-</span>';
  2656. }
  2657. function renderActionBadge(action) {
  2658. const act = (action || '').toLowerCase();
  2659. let color = 'bg-slate-800 text-slate-300';
  2660. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2661. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2662. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2663. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2664. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2665. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2666. }
  2667. function switchFWSubTab(tab) {
  2668. state.fwSubTab = tab;
  2669. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2670. tabs.forEach(t => {
  2671. const panel = document.getElementById(`fw-subtab-${t}`);
  2672. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2673. if (panel) {
  2674. if (t === tab) panel.classList.remove('hidden');
  2675. else panel.classList.add('hidden');
  2676. }
  2677. if (btn) {
  2678. if (t === tab) {
  2679. 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';
  2680. } else {
  2681. 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';
  2682. }
  2683. }
  2684. });
  2685. const addBtn = document.getElementById('fw-primary-add-btn');
  2686. if (addBtn) {
  2687. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2688. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2689. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2690. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2691. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2692. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2693. }
  2694. if (tab === 'geo') loadGeoIP();
  2695. if (tab === 'connections') loadConnections();
  2696. setTimeout(initTableSorting, 50);
  2697. }
  2698. function openCurrentFWModal() {
  2699. if (state.fwSubTab === 'filter') openAddFilterModal();
  2700. else if (state.fwSubTab === 'nat') openAddNATModal();
  2701. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2702. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2703. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2704. else if (state.fwSubTab === 'connections') loadConnections();
  2705. }
  2706. async function loadFirewall(populateDropdowns = true) {
  2707. try {
  2708. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2709. fetch(`${API_BASE}/firewall/summary`),
  2710. fetch(`${API_BASE}/firewall/filter`),
  2711. fetch(`${API_BASE}/firewall/nat`),
  2712. fetch(`${API_BASE}/firewall/mangle`),
  2713. fetch(`${API_BASE}/firewall/address-lists`),
  2714. fetch(`${API_BASE}/firewall/geoip/status`),
  2715. fetch(`${API_BASE}/firewall/geoip/countries`)
  2716. ]);
  2717. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2718. if (filterRes.ok) state.filterRules = await filterRes.json();
  2719. if (natRes.ok) state.natRules = await natRes.json();
  2720. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2721. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2722. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2723. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2724. // Badges
  2725. const bFilter = document.getElementById('fw-badge-filter');
  2726. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2727. const bNat = document.getElementById('fw-badge-nat');
  2728. if (bNat) bNat.innerText = (state.natRules || []).length;
  2729. const bMangle = document.getElementById('fw-badge-mangle');
  2730. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2731. const bAddr = document.getElementById('fw-badge-addrlist');
  2732. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2733. const bGeo = document.getElementById('fw-badge-geo');
  2734. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2735. renderFilterRules();
  2736. renderNATRules();
  2737. renderMangleRules();
  2738. renderAddressLists();
  2739. renderGeoCountries();
  2740. if (state.fwSubTab === 'connections') {
  2741. loadConnections();
  2742. }
  2743. } catch (err) {
  2744. console.error('Failed to load firewall:', err);
  2745. }
  2746. }
  2747. // ----------------- Filter Rules -----------------
  2748. function renderFilterRules() {
  2749. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2750. const tbody = document.getElementById('filter-table-body');
  2751. const empty = document.getElementById('filter-empty');
  2752. if (!tbody) return;
  2753. tbody.innerHTML = '';
  2754. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2755. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2756. if (rules.length === 0) {
  2757. empty?.classList.remove('hidden');
  2758. return;
  2759. }
  2760. empty?.classList.add('hidden');
  2761. rules.forEach((r, idx) => {
  2762. const tr = document.createElement('tr');
  2763. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2764. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2765. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2766. let actionExtra = '';
  2767. if (r.action === 'reject') {
  2768. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2769. } else if (r.action === 'jump') {
  2770. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2771. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2772. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2773. } else if (r.action === 'log' && r.log_prefix) {
  2774. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2775. }
  2776. tr.innerHTML = `
  2777. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2778. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2779. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2780. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2781. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2782. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2783. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2784. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2785. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2786. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2787. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2788. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2789. </td>
  2790. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2791. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2792. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2793. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2794. <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>
  2795. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2796. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2797. </td>
  2798. `;
  2799. tbody.appendChild(tr);
  2800. });
  2801. }
  2802. function formatTarget(addr, list, geo) {
  2803. const parts = [];
  2804. if (addr) parts.push(`<span>${addr}</span>`);
  2805. if (list) {
  2806. const inv = list.startsWith('!') ? '!' : '';
  2807. const clean = list.replace(/^!/, '');
  2808. 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>`);
  2809. }
  2810. if (geo) {
  2811. const inv = geo.startsWith('!') ? '!' : '';
  2812. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2813. 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>`);
  2814. }
  2815. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2816. return parts.join(' ');
  2817. }
  2818. function populateInterfaceSelect(selectId, currentVal = '') {
  2819. const sel = document.getElementById(selectId);
  2820. if (!sel) return;
  2821. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2822. (state.interfaces || []).forEach(i => {
  2823. const opt = document.createElement('option');
  2824. opt.value = i.name;
  2825. opt.innerText = `${i.name} (${i.role || i.type})`;
  2826. if (i.name === currentVal) opt.selected = true;
  2827. sel.appendChild(opt);
  2828. });
  2829. }
  2830. function populateAddressListSelect(selectId, currentVal = '') {
  2831. const sel = document.getElementById(selectId);
  2832. if (!sel) return;
  2833. sel.innerHTML = '<option value="">(None)</option>';
  2834. const cleanVal = (currentVal || '').replace(/^!/, '');
  2835. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2836. customNames.forEach(name => {
  2837. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2838. const opt = document.createElement('option');
  2839. opt.value = name;
  2840. opt.innerText = `${name} (${count} entries)`;
  2841. if (name === cleanVal) opt.selected = true;
  2842. sel.appendChild(opt);
  2843. });
  2844. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2845. const opt = document.createElement('option');
  2846. opt.value = cleanVal;
  2847. opt.innerText = cleanVal;
  2848. opt.selected = true;
  2849. sel.appendChild(opt);
  2850. }
  2851. populateCommonAddrListDatalist();
  2852. }
  2853. function populateCommonAddrListDatalist() {
  2854. const dl = document.getElementById('fw-addrlist-datalist');
  2855. if (!dl) return;
  2856. dl.innerHTML = '';
  2857. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2858. names.forEach(name => {
  2859. const opt = document.createElement('option');
  2860. opt.value = name;
  2861. dl.appendChild(opt);
  2862. });
  2863. }
  2864. function populateGeoIPSelect(selectId, currentVal = '') {
  2865. const sel = document.getElementById(selectId);
  2866. if (!sel) return;
  2867. sel.innerHTML = '<option value="">(None)</option>';
  2868. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2869. // Presets optgroup
  2870. const grpPresets = document.createElement('optgroup');
  2871. grpPresets.label = '⚡ Regional Presets';
  2872. const presets = [
  2873. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2874. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2875. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2876. ];
  2877. presets.forEach(p => {
  2878. const opt = document.createElement('option');
  2879. opt.value = p.code;
  2880. opt.innerText = p.label;
  2881. if (p.code === cleanVal) opt.selected = true;
  2882. grpPresets.appendChild(opt);
  2883. });
  2884. sel.appendChild(grpPresets);
  2885. // All Countries optgroup
  2886. const grpCountries = document.createElement('optgroup');
  2887. grpCountries.label = '🌍 All Countries';
  2888. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2889. countries.forEach(c => {
  2890. const opt = document.createElement('option');
  2891. opt.value = c.code;
  2892. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2893. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2894. if (c.code === cleanVal) opt.selected = true;
  2895. grpCountries.appendChild(opt);
  2896. });
  2897. sel.appendChild(grpCountries);
  2898. }
  2899. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2900. function switchFwRuleTab(tab) {
  2901. state.activeFwRuleTab = tab;
  2902. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2903. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2904. btn.classList.add('text-slate-400', 'border-transparent');
  2905. });
  2906. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2907. if (activeBtn) {
  2908. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2909. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2910. }
  2911. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2912. const activePane = document.getElementById(`fw-pane-${tab}`);
  2913. if (activePane) activePane.classList.remove('hidden');
  2914. if (tab === 'statistics') {
  2915. startFwStatPolling();
  2916. } else {
  2917. stopFwStatPolling();
  2918. }
  2919. }
  2920. function toggleFwField(fieldKey, expand) {
  2921. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2922. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2923. if (!plusBtn || !fieldBox) return;
  2924. if (expand) {
  2925. plusBtn.classList.add('hidden');
  2926. fieldBox.classList.remove('hidden');
  2927. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2928. if (valInput) valInput.focus();
  2929. } else {
  2930. fieldBox.classList.add('hidden');
  2931. plusBtn.classList.remove('hidden');
  2932. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2933. if (valInput) {
  2934. if (valInput.tagName === 'SELECT') {
  2935. valInput.selectedIndex = 0;
  2936. } else {
  2937. valInput.value = '';
  2938. }
  2939. }
  2940. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2941. if (invInput) invInput.checked = false;
  2942. if (fieldKey === 'cs') {
  2943. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2944. const el = document.getElementById(id);
  2945. if (el) el.checked = false;
  2946. });
  2947. }
  2948. if (fieldKey === 'natstate') {
  2949. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2950. const el = document.getElementById(id);
  2951. if (el) el.checked = false;
  2952. });
  2953. }
  2954. if (fieldKey === 'days') {
  2955. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2956. const el = document.getElementById(`fw-day-${d}`);
  2957. if (el) el.checked = true;
  2958. });
  2959. }
  2960. }
  2961. }
  2962. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2963. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2964. toggleFwField(fieldKey, true);
  2965. let strVal = String(value);
  2966. if (hasInvert) {
  2967. const inv = strVal.startsWith('!');
  2968. if (inv) strVal = strVal.slice(1);
  2969. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2970. if (invEl) invEl.checked = inv;
  2971. }
  2972. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2973. if (valEl) valEl.value = strVal;
  2974. } else {
  2975. toggleFwField(fieldKey, false);
  2976. }
  2977. }
  2978. function getFwFieldVal(fieldKey, hasInvert = false) {
  2979. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2980. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  2981. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2982. let v = valEl ? valEl.value.trim() : '';
  2983. if (!v) return '';
  2984. if (hasInvert) {
  2985. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2986. if (invEl && invEl.checked) {
  2987. v = '!' + v.replace(/^!/, '');
  2988. }
  2989. }
  2990. return v;
  2991. }
  2992. function toggleMaximizeFilterModal() {
  2993. const win = document.getElementById('filter-modal-window');
  2994. if (!win) return;
  2995. if (win.classList.contains('max-w-[720px]')) {
  2996. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  2997. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  2998. } else {
  2999. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3000. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3001. }
  3002. }
  3003. function openAddFilterModal() {
  3004. switchFwRuleTab('general');
  3005. const badge = document.getElementById('fw-modal-badge');
  3006. if (badge) badge.innerText = 'New...';
  3007. document.getElementById('filter-modal-id').value = '';
  3008. document.getElementById('filter-modal-enabled').checked = true;
  3009. document.getElementById('filter-modal-comment').value = '';
  3010. document.getElementById('filter-modal-chain').value = 'forward';
  3011. document.getElementById('filter-modal-action').value = 'accept';
  3012. document.getElementById('filter-modal-log').checked = false;
  3013. populateInterfaceSelect('fw-val-iniface');
  3014. populateInterfaceSelect('fw-val-outiface');
  3015. populateAddressListSelect('fw-val-srclist');
  3016. populateAddressListSelect('fw-val-dstlist');
  3017. populateGeoIPSelect('fw-val-srcgeo');
  3018. populateGeoIPSelect('fw-val-dstgeo');
  3019. const allFieldKeys = [
  3020. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3021. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3022. 'routingmark', 'conntype', 'cs', 'natstate',
  3023. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3024. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3025. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3026. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3027. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3028. ];
  3029. allFieldKeys.forEach(k => toggleFwField(k, false));
  3030. resetCurrentRuleCounters();
  3031. toggleFilterActionFields();
  3032. document.getElementById('filter-modal').classList.remove('hidden');
  3033. }
  3034. function openEditFilterModal(id) {
  3035. const r = (state.filterRules || []).find(rule => rule.id === id);
  3036. if (!r) return;
  3037. switchFwRuleTab('general');
  3038. const badge = document.getElementById('fw-modal-badge');
  3039. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3040. document.getElementById('filter-modal-id').value = r.id;
  3041. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3042. document.getElementById('filter-modal-comment').value = r.comment || '';
  3043. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3044. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3045. document.getElementById('filter-modal-log').checked = !!r.log;
  3046. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3047. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3048. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3049. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3050. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3051. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3052. setFwFieldVal('src', r.src_address, true);
  3053. setFwFieldVal('dst', r.dst_address, true);
  3054. setFwFieldVal('srclist', r.src_address_list, true);
  3055. setFwFieldVal('dstlist', r.dst_address_list, true);
  3056. setFwFieldVal('srcgeo', r.src_geoip, true);
  3057. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3058. if (r.protocol && r.protocol !== 'all') {
  3059. setFwFieldVal('proto', r.protocol, true);
  3060. } else {
  3061. toggleFwField('proto', false);
  3062. }
  3063. setFwFieldVal('sport', r.src_port, true);
  3064. setFwFieldVal('dport', r.dst_port, true);
  3065. setFwFieldVal('anyport', r.any_port, true);
  3066. setFwFieldVal('iniface', r.in_interface, true);
  3067. setFwFieldVal('outiface', r.out_interface, true);
  3068. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3069. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3070. setFwFieldVal('pktmark', r.packet_mark, true);
  3071. setFwFieldVal('connmark', r.connection_mark, true);
  3072. setFwFieldVal('routingmark', r.routing_mark, true);
  3073. setFwFieldVal('conntype', r.connection_type, false);
  3074. const states = r.connection_state || [];
  3075. if (states.length > 0) {
  3076. toggleFwField('cs', true);
  3077. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3078. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3079. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3080. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3081. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3082. } else {
  3083. toggleFwField('cs', false);
  3084. }
  3085. const natStates = r.connection_nat_state || [];
  3086. if (natStates.length > 0) {
  3087. toggleFwField('natstate', true);
  3088. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3089. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3090. } else {
  3091. toggleFwField('natstate', false);
  3092. }
  3093. // Advanced tab fields
  3094. setFwFieldVal('layer7', r.layer7_protocol, false);
  3095. setFwFieldVal('content', r.content, false);
  3096. setFwFieldVal('connbytes', r.connection_bytes, false);
  3097. setFwFieldVal('connrate', r.connection_rate, false);
  3098. setFwFieldVal('pcc', r.pcc, false);
  3099. setFwFieldVal('srcmac', r.src_mac_address, true);
  3100. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3101. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3102. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3103. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3104. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3105. setFwFieldVal('tlshost', r.tls_host, false);
  3106. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3107. setFwFieldVal('priority', r.priority, false);
  3108. setFwFieldVal('dscp', r.dscp, false);
  3109. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3110. if (r.tos) {
  3111. const tosEl = document.getElementById('fw-val-tos');
  3112. if (tosEl) tosEl.value = r.tos;
  3113. }
  3114. setFwFieldVal('pktsize', r.packet_size, false);
  3115. setFwFieldVal('random', r.random, false);
  3116. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3117. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3118. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3119. setFwFieldVal('ttl', r.ttl, false);
  3120. // Extra tab fields
  3121. setFwFieldVal('time', r.time, false);
  3122. if (r.days) {
  3123. toggleFwField('days', true);
  3124. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3125. const chk = document.getElementById(`fw-day-${d}`);
  3126. if (chk) chk.checked = r.days.includes(d);
  3127. });
  3128. } else {
  3129. toggleFwField('days', false);
  3130. }
  3131. setFwFieldVal('limit', r.limit, false);
  3132. setFwFieldVal('dstlimit', r.dst_limit, false);
  3133. setFwFieldVal('psd', r.psd, false);
  3134. // Action fields
  3135. if (r.reject_with) {
  3136. const rwEl = document.getElementById('filter-modal-rejectwith');
  3137. if (rwEl) rwEl.value = r.reject_with;
  3138. }
  3139. if (r.jump_target) {
  3140. const jtEl = document.getElementById('filter-modal-jumptarget');
  3141. if (jtEl) jtEl.value = r.jump_target;
  3142. }
  3143. if (r.address_list) {
  3144. const alEl = document.getElementById('filter-modal-action-addrlist');
  3145. if (alEl) alEl.value = r.address_list;
  3146. }
  3147. if (r.address_list_timeout) {
  3148. const toEl = document.getElementById('filter-modal-action-timeout');
  3149. if (toEl) toEl.value = r.address_list_timeout;
  3150. }
  3151. setFwFieldVal('logprefix', r.log_prefix, false);
  3152. // Statistics
  3153. const bEl = document.getElementById('fw-stat-bytes');
  3154. const pEl = document.getElementById('fw-stat-packets');
  3155. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3156. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3157. state.fwLastBytes = r.bytes || 0;
  3158. state.fwLastPackets = r.packets || 0;
  3159. state.fwLastTimestamp = Date.now();
  3160. state.fwStatRateHistory = new Array(30).fill(0);
  3161. state.fwStatPktHistory = new Array(30).fill(0);
  3162. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3163. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3164. toggleFilterActionFields();
  3165. document.getElementById('filter-modal').classList.remove('hidden');
  3166. }
  3167. function closeFilterModal() {
  3168. stopFwStatPolling();
  3169. document.getElementById('filter-modal').classList.add('hidden');
  3170. }
  3171. function toggleFilterActionFields() {
  3172. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3173. const rejectBox = document.getElementById('filter-action-reject-box');
  3174. const jumpBox = document.getElementById('filter-action-jump-box');
  3175. const addrBox = document.getElementById('filter-action-addrlist-box');
  3176. if (rejectBox) {
  3177. if (act === 'reject') rejectBox.classList.remove('hidden');
  3178. else rejectBox.classList.add('hidden');
  3179. }
  3180. if (jumpBox) {
  3181. if (act === 'jump') jumpBox.classList.remove('hidden');
  3182. else jumpBox.classList.add('hidden');
  3183. }
  3184. if (addrBox) {
  3185. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3186. addrBox.classList.remove('hidden');
  3187. } else {
  3188. addrBox.classList.add('hidden');
  3189. }
  3190. }
  3191. if (act === 'log') {
  3192. const logEl = document.getElementById('filter-modal-log');
  3193. if (logEl) logEl.checked = true;
  3194. toggleFwField('logprefix', true);
  3195. }
  3196. }
  3197. function toggleFwLogPrefix() {
  3198. const isLog = document.getElementById('filter-modal-log')?.checked;
  3199. toggleFwField('logprefix', !!isLog);
  3200. }
  3201. function copyFilterRule() {
  3202. document.getElementById('filter-modal-id').value = '';
  3203. const badge = document.getElementById('fw-modal-badge');
  3204. if (badge) badge.innerText = 'New...';
  3205. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3206. }
  3207. function resetCurrentRuleCounters() {
  3208. state.fwStatRateHistory = new Array(30).fill(0);
  3209. state.fwStatPktHistory = new Array(30).fill(0);
  3210. state.fwLastBytes = 0;
  3211. state.fwLastPackets = 0;
  3212. state.fwLastTimestamp = Date.now();
  3213. const bEl = document.getElementById('fw-stat-bytes');
  3214. const pEl = document.getElementById('fw-stat-packets');
  3215. const rEl = document.getElementById('fw-stat-rate');
  3216. const prEl = document.getElementById('fw-stat-pktrate');
  3217. if (bEl) bEl.value = '0 B';
  3218. if (pEl) pEl.value = '0';
  3219. if (rEl) rEl.value = '0 bps';
  3220. if (prEl) prEl.value = '0 p/s';
  3221. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3222. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3223. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3224. }
  3225. async function resetAllFwCounters() {
  3226. try {
  3227. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3228. if (res.ok) {
  3229. resetCurrentRuleCounters();
  3230. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3231. loadFirewall(false);
  3232. }
  3233. } catch (err) {
  3234. showToast('Error', err.message, 'error');
  3235. }
  3236. }
  3237. async function applyFilterRule(closeAfter = false) {
  3238. const id = document.getElementById('filter-modal-id').value;
  3239. const chain = document.getElementById('filter-modal-chain').value;
  3240. const action = document.getElementById('filter-modal-action').value;
  3241. const comment = document.getElementById('filter-modal-comment').value.trim();
  3242. const enabled = document.getElementById('filter-modal-enabled').checked;
  3243. const src = getFwFieldVal('src', true);
  3244. const dst = getFwFieldVal('dst', true);
  3245. const srclist = getFwFieldVal('srclist', true);
  3246. const dstlist = getFwFieldVal('dstlist', true);
  3247. const srcgeo = getFwFieldVal('srcgeo', true);
  3248. const dstgeo = getFwFieldVal('dstgeo', true);
  3249. const proto = getFwFieldVal('proto', true);
  3250. const sport = getFwFieldVal('sport', true);
  3251. const dport = getFwFieldVal('dport', true);
  3252. const anyport = getFwFieldVal('anyport', true);
  3253. const iniface = getFwFieldVal('iniface', true);
  3254. const outiface = getFwFieldVal('outiface', true);
  3255. const inifacelist = getFwFieldVal('inifacelist', true);
  3256. const outifacelist = getFwFieldVal('outifacelist', true);
  3257. const pktmark = getFwFieldVal('pktmark', true);
  3258. const connmark = getFwFieldVal('connmark', true);
  3259. const routingmark = getFwFieldVal('routingmark', true);
  3260. const conntype = getFwFieldVal('conntype', false);
  3261. const states = [];
  3262. const csBox = document.getElementById('fw-field-cs');
  3263. if (csBox && !csBox.classList.contains('hidden')) {
  3264. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3265. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3266. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3267. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3268. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3269. }
  3270. const natStates = [];
  3271. const natBox = document.getElementById('fw-field-natstate');
  3272. if (natBox && !natBox.classList.contains('hidden')) {
  3273. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3274. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3275. }
  3276. const payload = {
  3277. id,
  3278. chain,
  3279. action,
  3280. protocol: proto || 'all',
  3281. src_address: src,
  3282. dst_address: dst,
  3283. src_port: sport,
  3284. dst_port: dport,
  3285. any_port: anyport,
  3286. in_interface: iniface,
  3287. out_interface: outiface,
  3288. in_interface_list: inifacelist,
  3289. out_interface_list: outifacelist,
  3290. packet_mark: pktmark,
  3291. connection_mark: connmark,
  3292. routing_mark: routingmark,
  3293. connection_type: conntype,
  3294. connection_state: states,
  3295. connection_nat_state: natStates,
  3296. src_address_list: srclist,
  3297. dst_address_list: dstlist,
  3298. src_geoip: srcgeo,
  3299. dst_geoip: dstgeo,
  3300. comment,
  3301. disabled: !enabled,
  3302. // Advanced tab
  3303. layer7_protocol: getFwFieldVal('layer7', false),
  3304. content: getFwFieldVal('content', false),
  3305. connection_bytes: getFwFieldVal('connbytes', false),
  3306. connection_rate: getFwFieldVal('connrate', false),
  3307. pcc: getFwFieldVal('pcc', false),
  3308. src_mac_address: getFwFieldVal('srcmac', true),
  3309. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3310. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3311. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3312. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3313. ipsec_policy: getFwFieldVal('ipsec', false),
  3314. tls_host: getFwFieldVal('tlshost', false),
  3315. ingress_priority: getFwFieldVal('ingresspriority', false),
  3316. priority: getFwFieldVal('priority', false),
  3317. dscp: getFwFieldVal('dscp', false),
  3318. tcp_mss: getFwFieldVal('tcpmss', false),
  3319. tos: document.getElementById('fw-val-tos')?.value || '',
  3320. packet_size: getFwFieldVal('pktsize', false),
  3321. random: getFwFieldVal('random', false),
  3322. tcp_flags: getFwFieldVal('tcpflags', false),
  3323. icmp_options: getFwFieldVal('icmpoptions', false),
  3324. ipv4_options: getFwFieldVal('ipv4options', false),
  3325. ttl: getFwFieldVal('ttl', false),
  3326. // Extra tab
  3327. time: getFwFieldVal('time', false),
  3328. limit: getFwFieldVal('limit', false),
  3329. dst_limit: getFwFieldVal('dstlimit', false),
  3330. psd: getFwFieldVal('psd', false),
  3331. // Action tab
  3332. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3333. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3334. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3335. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3336. log: document.getElementById('filter-modal-log')?.checked || false,
  3337. log_prefix: getFwFieldVal('logprefix', false)
  3338. };
  3339. try {
  3340. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3341. method: 'POST',
  3342. headers: { 'Content-Type': 'application/json' },
  3343. body: JSON.stringify(payload)
  3344. });
  3345. if (res.ok) {
  3346. const data = await res.json();
  3347. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3348. loadFirewall(false);
  3349. if (closeAfter) {
  3350. closeFilterModal();
  3351. } else {
  3352. if (data.id) {
  3353. document.getElementById('filter-modal-id').value = data.id;
  3354. const badge = document.getElementById('fw-modal-badge');
  3355. if (badge) badge.innerText = `#${data.id}`;
  3356. }
  3357. }
  3358. } else {
  3359. const err = await res.json();
  3360. showToast('Error', err.message || 'Failed to save rule', 'error');
  3361. }
  3362. } catch (err) {
  3363. showToast('Error', err.message, 'error');
  3364. }
  3365. }
  3366. function submitSaveFilterRule(e) {
  3367. if (e && e.preventDefault) e.preventDefault();
  3368. return applyFilterRule(true);
  3369. }
  3370. function startFwStatPolling() {
  3371. stopFwStatPolling();
  3372. pollRuleStats();
  3373. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3374. }
  3375. function stopFwStatPolling() {
  3376. if (state.fwStatInterval) {
  3377. clearInterval(state.fwStatInterval);
  3378. state.fwStatInterval = null;
  3379. }
  3380. }
  3381. async function pollRuleStats() {
  3382. const id = document.getElementById('filter-modal-id')?.value;
  3383. if (!id) {
  3384. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3385. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3386. return;
  3387. }
  3388. try {
  3389. const res = await fetch(`${API_BASE}/firewall/filter`);
  3390. if (!res.ok) return;
  3391. const rules = await res.json();
  3392. const r = rules.find(x => x.id === id);
  3393. if (!r) return;
  3394. const now = Date.now();
  3395. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3396. state.fwLastTimestamp = now;
  3397. const curBytes = r.bytes || 0;
  3398. const curPackets = r.packets || 0;
  3399. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3400. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3401. state.fwLastBytes = curBytes;
  3402. state.fwLastPackets = curPackets;
  3403. const rateBps = Math.round((deltaBytes * 8) / dt);
  3404. const ratePkt = Math.round(deltaPkts / dt);
  3405. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3406. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3407. state.fwStatRateHistory.push(rateBps);
  3408. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3409. state.fwStatPktHistory.push(ratePkt);
  3410. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3411. const bEl = document.getElementById('fw-stat-bytes');
  3412. const pEl = document.getElementById('fw-stat-packets');
  3413. const rEl = document.getElementById('fw-stat-rate');
  3414. const prEl = document.getElementById('fw-stat-pktrate');
  3415. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3416. if (pEl) pEl.value = curPackets.toLocaleString();
  3417. if (rEl) rEl.value = formatBps(rateBps);
  3418. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3419. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3420. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3421. } catch (e) {
  3422. console.error('Error polling rule stats', e);
  3423. }
  3424. }
  3425. function formatBps(bps) {
  3426. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3427. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3428. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3429. return bps + ' bps';
  3430. }
  3431. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3432. const svg = document.getElementById(svgId);
  3433. if (!svg) return;
  3434. const w = 500;
  3435. const h = 100;
  3436. const paddingRight = 45;
  3437. const graphWidth = w - paddingRight;
  3438. const maxVal = Math.max(5, ...dataArray);
  3439. const currentVal = dataArray[dataArray.length - 1] || 0;
  3440. const leg = document.getElementById(legendId);
  3441. if (leg) {
  3442. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3443. }
  3444. let gridLines = '';
  3445. for (let i = 0; i <= 5; i++) {
  3446. const y = 8 + (i * (h - 18) / 5);
  3447. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3448. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3449. gridLines += `
  3450. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3451. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3452. `;
  3453. }
  3454. const step = graphWidth / (dataArray.length - 1);
  3455. const points = dataArray.map((val, idx) => {
  3456. const x = idx * step;
  3457. const y = (h - 10) - (val / maxVal) * (h - 20);
  3458. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3459. });
  3460. const polylineStr = points.join(' ');
  3461. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3462. svg.innerHTML = `
  3463. ${gridLines}
  3464. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3465. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3466. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3467. `;
  3468. }
  3469. async function moveFilterRule(id, dir) {
  3470. try {
  3471. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3472. method: 'POST',
  3473. headers: { 'Content-Type': 'application/json' },
  3474. body: JSON.stringify({ direction: dir })
  3475. });
  3476. if (res.ok) loadFirewall(false);
  3477. } catch (err) {
  3478. showToast('Error', err.message, 'error');
  3479. }
  3480. }
  3481. async function toggleFilterRuleState(id, disabled) {
  3482. try {
  3483. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3484. method: 'POST',
  3485. headers: { 'Content-Type': 'application/json' },
  3486. body: JSON.stringify({ disabled })
  3487. });
  3488. if (res.ok) loadFirewall(false);
  3489. } catch (err) {
  3490. showToast('Error', err.message, 'error');
  3491. }
  3492. }
  3493. async function deleteFilterRule(id) {
  3494. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3495. try {
  3496. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3497. if (res.ok) {
  3498. showToast('Deleted', 'Filter rule removed', 'success');
  3499. loadFirewall(false);
  3500. }
  3501. } catch (err) {
  3502. showToast('Error', err.message, 'error');
  3503. }
  3504. }
  3505. // ----------------- NAT Rules -----------------
  3506. function renderNATRules() {
  3507. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3508. const tbody = document.getElementById('nat-table-body');
  3509. const empty = document.getElementById('nat-empty');
  3510. if (!tbody) return;
  3511. tbody.innerHTML = '';
  3512. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3513. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3514. if (rules.length === 0) {
  3515. empty?.classList.remove('hidden');
  3516. return;
  3517. }
  3518. empty?.classList.add('hidden');
  3519. rules.forEach((r, idx) => {
  3520. const tr = document.createElement('tr');
  3521. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3522. let toTarget = '-';
  3523. if (r.action === 'jump') {
  3524. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3525. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3526. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3527. } else if (r.action === 'redirect') {
  3528. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3529. } else if (r.action === 'masquerade') {
  3530. 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>`;
  3531. } else if (r.action === 'log') {
  3532. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3533. } else {
  3534. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3535. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3536. }
  3537. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3538. tr.innerHTML = `
  3539. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3540. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3541. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3542. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3543. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3544. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3545. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3546. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3547. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3548. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3549. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3550. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3551. </td>
  3552. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3553. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3554. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3555. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3556. <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>
  3557. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3558. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3559. </td>
  3560. `;
  3561. tbody.appendChild(tr);
  3562. });
  3563. }
  3564. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3565. function switchNATRuleTab(tab) {
  3566. state.activeNATRuleTab = tab;
  3567. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3568. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3569. btn.classList.add('text-slate-400', 'border-transparent');
  3570. });
  3571. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3572. if (activeBtn) {
  3573. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3574. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3575. }
  3576. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3577. const activePane = document.getElementById(`nat-pane-${tab}`);
  3578. if (activePane) activePane.classList.remove('hidden');
  3579. if (tab === 'statistics') {
  3580. startNATStatPolling();
  3581. } else {
  3582. stopNATStatPolling();
  3583. }
  3584. }
  3585. function toggleNATField(fieldKey, expand) {
  3586. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3587. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3588. if (!plusBtn || !fieldBox) return;
  3589. if (expand) {
  3590. plusBtn.classList.add('hidden');
  3591. fieldBox.classList.remove('hidden');
  3592. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3593. if (valInput) valInput.focus();
  3594. } else {
  3595. fieldBox.classList.add('hidden');
  3596. plusBtn.classList.remove('hidden');
  3597. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3598. if (valInput) {
  3599. if (valInput.tagName === 'SELECT') {
  3600. valInput.selectedIndex = 0;
  3601. } else {
  3602. valInput.value = '';
  3603. }
  3604. }
  3605. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3606. if (invInput) invInput.checked = false;
  3607. if (fieldKey === 'days') {
  3608. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3609. const el = document.getElementById(`nat-day-${d}`);
  3610. if (el) el.checked = true;
  3611. });
  3612. }
  3613. }
  3614. }
  3615. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3616. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3617. toggleNATField(fieldKey, true);
  3618. let strVal = String(value);
  3619. if (hasInvert) {
  3620. const inv = strVal.startsWith('!');
  3621. if (inv) strVal = strVal.slice(1);
  3622. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3623. if (invEl) invEl.checked = inv;
  3624. }
  3625. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3626. if (valEl) valEl.value = strVal;
  3627. } else {
  3628. toggleNATField(fieldKey, false);
  3629. }
  3630. }
  3631. function getNATFieldVal(fieldKey, hasInvert = false) {
  3632. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3633. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3634. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3635. let v = valEl ? valEl.value.trim() : '';
  3636. if (!v) return '';
  3637. if (hasInvert) {
  3638. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3639. if (invEl && invEl.checked) {
  3640. v = '!' + v.replace(/^!/, '');
  3641. }
  3642. }
  3643. return v;
  3644. }
  3645. function toggleMaximizeNATModal() {
  3646. const win = document.getElementById('nat-modal-window');
  3647. if (!win) return;
  3648. if (win.classList.contains('max-w-[720px]')) {
  3649. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3650. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3651. } else {
  3652. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3653. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3654. }
  3655. }
  3656. function handleNATChainChange() {
  3657. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3658. const actSel = document.getElementById('nat-modal-action');
  3659. if (actSel) {
  3660. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3661. actSel.value = 'masquerade';
  3662. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3663. actSel.value = 'dst-nat';
  3664. }
  3665. }
  3666. toggleNATActionFields();
  3667. }
  3668. function toggleNATActionFields() {
  3669. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3670. const rowAddr = document.getElementById('nat-row-toaddr');
  3671. const rowPort = document.getElementById('nat-row-toport');
  3672. const jumpBox = document.getElementById('nat-action-jump-box');
  3673. const addrBox = document.getElementById('nat-action-addrlist-box');
  3674. // Hide all dynamic rows first
  3675. if (rowAddr) rowAddr.classList.add('hidden');
  3676. if (rowPort) rowPort.classList.add('hidden');
  3677. if (jumpBox) jumpBox.classList.add('hidden');
  3678. if (addrBox) addrBox.classList.add('hidden');
  3679. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3680. if (rowAddr) rowAddr.classList.remove('hidden');
  3681. if (rowPort) rowPort.classList.remove('hidden');
  3682. } else if (act === 'redirect' || act === 'masquerade') {
  3683. if (rowPort) rowPort.classList.remove('hidden');
  3684. } else if (act === 'jump') {
  3685. if (jumpBox) jumpBox.classList.remove('hidden');
  3686. } else if (act.includes('address-list') || act.includes('address list')) {
  3687. if (addrBox) addrBox.classList.remove('hidden');
  3688. }
  3689. if (act === 'log') {
  3690. const logEl = document.getElementById('nat-modal-log');
  3691. if (logEl) logEl.checked = true;
  3692. toggleNATField('logprefix', true);
  3693. }
  3694. }
  3695. function toggleNATLogPrefix() {
  3696. const isLog = document.getElementById('nat-modal-log')?.checked;
  3697. toggleNATField('logprefix', !!isLog);
  3698. }
  3699. function openAddNATModal() {
  3700. switchNATRuleTab('general');
  3701. const badge = document.getElementById('nat-modal-badge');
  3702. if (badge) badge.innerText = 'New...';
  3703. document.getElementById('nat-modal-id').value = '';
  3704. document.getElementById('nat-modal-enabled').checked = true;
  3705. document.getElementById('nat-modal-comment').value = '';
  3706. document.getElementById('nat-modal-chain').value = 'srcnat';
  3707. document.getElementById('nat-modal-action').value = 'masquerade';
  3708. document.getElementById('nat-modal-toaddr').value = '';
  3709. document.getElementById('nat-modal-toport').value = '';
  3710. document.getElementById('nat-modal-log').checked = false;
  3711. populateInterfaceSelect('nat-val-iniface');
  3712. populateInterfaceSelect('nat-val-outiface');
  3713. populateAddressListSelect('nat-val-srclist');
  3714. populateAddressListSelect('nat-val-dstlist');
  3715. populateGeoIPSelect('nat-val-srcgeo');
  3716. populateGeoIPSelect('nat-val-dstgeo');
  3717. const allFieldKeys = [
  3718. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3719. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3720. 'routingmark', 'conntype',
  3721. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3722. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3723. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3724. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3725. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3726. ];
  3727. allFieldKeys.forEach(k => toggleNATField(k, false));
  3728. resetCurrentNATRuleCounters();
  3729. toggleNATActionFields();
  3730. document.getElementById('nat-modal').classList.remove('hidden');
  3731. }
  3732. function openEditNATModal(id) {
  3733. const r = (state.natRules || []).find(rule => rule.id === id);
  3734. if (!r) return;
  3735. switchNATRuleTab('general');
  3736. const badge = document.getElementById('nat-modal-badge');
  3737. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3738. document.getElementById('nat-modal-id').value = r.id;
  3739. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3740. document.getElementById('nat-modal-comment').value = r.comment || '';
  3741. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3742. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3743. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3744. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3745. document.getElementById('nat-modal-log').checked = !!r.log;
  3746. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3747. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3748. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3749. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3750. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3751. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3752. setNATFieldVal('src', r.src_address, true);
  3753. setNATFieldVal('dst', r.dst_address, true);
  3754. setNATFieldVal('srclist', r.src_address_list, true);
  3755. setNATFieldVal('dstlist', r.dst_address_list, true);
  3756. setNATFieldVal('srcgeo', r.src_geoip, true);
  3757. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3758. if (r.protocol && r.protocol !== 'all') {
  3759. setNATFieldVal('proto', r.protocol, true);
  3760. } else {
  3761. toggleNATField('proto', false);
  3762. }
  3763. setNATFieldVal('sport', r.src_port, true);
  3764. setNATFieldVal('dport', r.dst_port, true);
  3765. setNATFieldVal('anyport', r.any_port, true);
  3766. setNATFieldVal('iniface', r.in_interface, true);
  3767. setNATFieldVal('outiface', r.out_interface, true);
  3768. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3769. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3770. setNATFieldVal('pktmark', r.packet_mark, true);
  3771. setNATFieldVal('connmark', r.connection_mark, true);
  3772. setNATFieldVal('routingmark', r.routing_mark, true);
  3773. setNATFieldVal('conntype', r.connection_type, false);
  3774. // Advanced tab fields
  3775. setNATFieldVal('layer7', r.layer7_protocol, false);
  3776. setNATFieldVal('content', r.content, false);
  3777. setNATFieldVal('connbytes', r.connection_bytes, false);
  3778. setNATFieldVal('connrate', r.connection_rate, false);
  3779. setNATFieldVal('pcc', r.pcc, false);
  3780. setNATFieldVal('srcmac', r.src_mac_address, true);
  3781. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3782. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3783. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3784. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3785. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3786. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3787. setNATFieldVal('priority', r.priority, false);
  3788. setNATFieldVal('dscp', r.dscp, false);
  3789. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3790. if (r.tos) {
  3791. const tosEl = document.getElementById('nat-val-tos');
  3792. if (tosEl) tosEl.value = r.tos;
  3793. }
  3794. setNATFieldVal('pktsize', r.packet_size, false);
  3795. setNATFieldVal('random', r.random, false);
  3796. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3797. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3798. setNATFieldVal('ttl', r.ttl, false);
  3799. // Extra tab fields
  3800. setNATFieldVal('time', r.time, false);
  3801. if (r.days) {
  3802. toggleNATField('days', true);
  3803. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3804. const chk = document.getElementById(`nat-day-${d}`);
  3805. if (chk) chk.checked = r.days.includes(d);
  3806. });
  3807. } else {
  3808. toggleNATField('days', false);
  3809. }
  3810. setNATFieldVal('limit', r.limit, false);
  3811. setNATFieldVal('dstlimit', r.dst_limit, false);
  3812. setNATFieldVal('psd', r.psd, false);
  3813. // Action fields
  3814. if (r.jump_target) {
  3815. const jtEl = document.getElementById('nat-modal-jumptarget');
  3816. if (jtEl) jtEl.value = r.jump_target;
  3817. }
  3818. if (r.address_list) {
  3819. const alEl = document.getElementById('nat-modal-action-addrlist');
  3820. if (alEl) alEl.value = r.address_list;
  3821. }
  3822. if (r.address_list_timeout) {
  3823. const toEl = document.getElementById('nat-modal-action-timeout');
  3824. if (toEl) toEl.value = r.address_list_timeout;
  3825. }
  3826. setNATFieldVal('logprefix', r.log_prefix, false);
  3827. // Statistics
  3828. const bEl = document.getElementById('nat-stat-bytes');
  3829. const pEl = document.getElementById('nat-stat-packets');
  3830. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3831. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3832. state.natLastBytes = r.bytes || 0;
  3833. state.natLastPackets = r.packets || 0;
  3834. state.natLastTimestamp = Date.now();
  3835. state.natStatRateHistory = new Array(30).fill(0);
  3836. state.natStatPktHistory = new Array(30).fill(0);
  3837. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3838. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3839. toggleNATActionFields();
  3840. document.getElementById('nat-modal').classList.remove('hidden');
  3841. }
  3842. function closeNATModal() {
  3843. stopNATStatPolling();
  3844. document.getElementById('nat-modal').classList.add('hidden');
  3845. }
  3846. function copyNATRule() {
  3847. document.getElementById('nat-modal-id').value = '';
  3848. const badge = document.getElementById('nat-modal-badge');
  3849. if (badge) badge.innerText = 'New...';
  3850. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3851. }
  3852. function resetCurrentNATRuleCounters() {
  3853. state.natStatRateHistory = new Array(30).fill(0);
  3854. state.natStatPktHistory = new Array(30).fill(0);
  3855. state.natLastBytes = 0;
  3856. state.natLastPackets = 0;
  3857. state.natLastTimestamp = Date.now();
  3858. const bEl = document.getElementById('nat-stat-bytes');
  3859. const pEl = document.getElementById('nat-stat-packets');
  3860. const rEl = document.getElementById('nat-stat-rate');
  3861. const prEl = document.getElementById('nat-stat-pktrate');
  3862. if (bEl) bEl.value = '0 B';
  3863. if (pEl) pEl.value = '0';
  3864. if (rEl) rEl.value = '0 bps';
  3865. if (prEl) prEl.value = '0 p/s';
  3866. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3867. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3868. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3869. }
  3870. async function applyNATRule(closeAfter = false) {
  3871. const id = document.getElementById('nat-modal-id').value;
  3872. const chain = document.getElementById('nat-modal-chain').value;
  3873. const action = document.getElementById('nat-modal-action').value;
  3874. const comment = document.getElementById('nat-modal-comment').value.trim();
  3875. const enabled = document.getElementById('nat-modal-enabled').checked;
  3876. const src = getNATFieldVal('src', true);
  3877. const dst = getNATFieldVal('dst', true);
  3878. const srclist = getNATFieldVal('srclist', true);
  3879. const dstlist = getNATFieldVal('dstlist', true);
  3880. const srcgeo = getNATFieldVal('srcgeo', true);
  3881. const dstgeo = getNATFieldVal('dstgeo', true);
  3882. const proto = getNATFieldVal('proto', true);
  3883. const sport = getNATFieldVal('sport', true);
  3884. const dport = getNATFieldVal('dport', true);
  3885. const anyport = getNATFieldVal('anyport', true);
  3886. const iniface = getNATFieldVal('iniface', true);
  3887. const outiface = getNATFieldVal('outiface', true);
  3888. const inifacelist = getNATFieldVal('inifacelist', true);
  3889. const outifacelist = getNATFieldVal('outifacelist', true);
  3890. const pktmark = getNATFieldVal('pktmark', true);
  3891. const connmark = getNATFieldVal('connmark', true);
  3892. const routingmark = getNATFieldVal('routingmark', true);
  3893. const conntype = getNATFieldVal('conntype', false);
  3894. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3895. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3896. const payload = {
  3897. id,
  3898. chain,
  3899. action,
  3900. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3901. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3902. protocol: proto || 'all',
  3903. src_address: src,
  3904. dst_address: dst,
  3905. src_port: sport,
  3906. dst_port: dport,
  3907. any_port: anyport,
  3908. in_interface: iniface,
  3909. out_interface: outiface,
  3910. in_interface_list: inifacelist,
  3911. out_interface_list: outifacelist,
  3912. packet_mark: pktmark,
  3913. connection_mark: connmark,
  3914. routing_mark: routingmark,
  3915. connection_type: conntype,
  3916. src_address_list: srclist,
  3917. dst_address_list: dstlist,
  3918. src_geoip: srcgeo,
  3919. dst_geoip: dstgeo,
  3920. comment,
  3921. disabled: !enabled,
  3922. // Advanced tab
  3923. layer7_protocol: getNATFieldVal('layer7', false),
  3924. content: getNATFieldVal('content', false),
  3925. connection_bytes: getNATFieldVal('connbytes', false),
  3926. connection_rate: getNATFieldVal('connrate', false),
  3927. pcc: getNATFieldVal('pcc', false),
  3928. src_mac_address: getNATFieldVal('srcmac', true),
  3929. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3930. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3931. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3932. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3933. ipsec_policy: getNATFieldVal('ipsec', false),
  3934. ingress_priority: getNATFieldVal('ingresspriority', false),
  3935. priority: getNATFieldVal('priority', false),
  3936. dscp: getNATFieldVal('dscp', false),
  3937. tcp_mss: getNATFieldVal('tcpmss', false),
  3938. tos: document.getElementById('nat-val-tos')?.value || '',
  3939. packet_size: getNATFieldVal('pktsize', false),
  3940. random: getNATFieldVal('random', false),
  3941. icmp_options: getNATFieldVal('icmpoptions', false),
  3942. ipv4_options: getNATFieldVal('ipv4options', false),
  3943. ttl: getNATFieldVal('ttl', false),
  3944. // Extra tab
  3945. time: getNATFieldVal('time', false),
  3946. limit: getNATFieldVal('limit', false),
  3947. dst_limit: getNATFieldVal('dstlimit', false),
  3948. psd: getNATFieldVal('psd', false),
  3949. // Action tab
  3950. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3951. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3952. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3953. log: document.getElementById('nat-modal-log')?.checked || false,
  3954. log_prefix: getNATFieldVal('logprefix', false)
  3955. };
  3956. try {
  3957. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3958. method: 'POST',
  3959. headers: { 'Content-Type': 'application/json' },
  3960. body: JSON.stringify(payload)
  3961. });
  3962. if (res.ok) {
  3963. const data = await res.json();
  3964. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3965. loadFirewall(false);
  3966. if (closeAfter) {
  3967. closeNATModal();
  3968. } else {
  3969. if (data.id) {
  3970. document.getElementById('nat-modal-id').value = data.id;
  3971. const badge = document.getElementById('nat-modal-badge');
  3972. if (badge) badge.innerText = `#${data.id}`;
  3973. }
  3974. }
  3975. } else {
  3976. const err = await res.json();
  3977. showToast('Error', err.message || 'Failed to save rule', 'error');
  3978. }
  3979. } catch (err) {
  3980. showToast('Error', err.message, 'error');
  3981. }
  3982. }
  3983. function submitSaveNATRule(e) {
  3984. if (e && e.preventDefault) e.preventDefault();
  3985. return applyNATRule(true);
  3986. }
  3987. function startNATStatPolling() {
  3988. stopNATStatPolling();
  3989. pollNATRuleStats();
  3990. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  3991. }
  3992. function stopNATStatPolling() {
  3993. if (state.natStatInterval) {
  3994. clearInterval(state.natStatInterval);
  3995. state.natStatInterval = null;
  3996. }
  3997. }
  3998. async function pollNATRuleStats() {
  3999. const id = document.getElementById('nat-modal-id')?.value;
  4000. if (!id) {
  4001. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4002. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4003. return;
  4004. }
  4005. try {
  4006. const res = await fetch(`${API_BASE}/firewall/nat`);
  4007. if (!res.ok) return;
  4008. const rules = await res.json();
  4009. const r = rules.find(x => x.id === id);
  4010. if (!r) return;
  4011. const now = Date.now();
  4012. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4013. state.natLastTimestamp = now;
  4014. const curBytes = r.bytes || 0;
  4015. const curPackets = r.packets || 0;
  4016. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4017. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4018. state.natLastBytes = curBytes;
  4019. state.natLastPackets = curPackets;
  4020. const rateBps = Math.round((deltaBytes * 8) / dt);
  4021. const ratePkt = Math.round(deltaPkts / dt);
  4022. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4023. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4024. state.natStatRateHistory.push(rateBps);
  4025. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4026. state.natStatPktHistory.push(ratePkt);
  4027. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4028. const bEl = document.getElementById('nat-stat-bytes');
  4029. const pEl = document.getElementById('nat-stat-packets');
  4030. const rEl = document.getElementById('nat-stat-rate');
  4031. const prEl = document.getElementById('nat-stat-pktrate');
  4032. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4033. if (pEl) pEl.value = curPackets.toLocaleString();
  4034. if (rEl) rEl.value = formatBps(rateBps);
  4035. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4036. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4037. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4038. } catch (e) {
  4039. console.error('Error polling NAT rule stats', e);
  4040. }
  4041. }
  4042. async function moveNATRule(id, dir) {
  4043. try {
  4044. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4045. method: 'POST',
  4046. headers: { 'Content-Type': 'application/json' },
  4047. body: JSON.stringify({ direction: dir })
  4048. });
  4049. if (res.ok) loadFirewall(false);
  4050. } catch (err) {
  4051. showToast('Error', err.message, 'error');
  4052. }
  4053. }
  4054. async function toggleNATRuleState(id, disabled) {
  4055. try {
  4056. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4057. method: 'POST',
  4058. headers: { 'Content-Type': 'application/json' },
  4059. body: JSON.stringify({ disabled })
  4060. });
  4061. if (res.ok) loadFirewall(false);
  4062. } catch (err) {
  4063. showToast('Error', err.message, 'error');
  4064. }
  4065. }
  4066. async function deleteNATRule(id) {
  4067. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4068. try {
  4069. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4070. if (res.ok) {
  4071. showToast('Deleted', 'NAT rule removed', 'success');
  4072. loadFirewall(false);
  4073. }
  4074. } catch (err) {
  4075. showToast('Error', err.message, 'error');
  4076. }
  4077. }
  4078. // ----------------- Mangle Rules -----------------
  4079. function renderMangleRules() {
  4080. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4081. const tbody = document.getElementById('mangle-table-body');
  4082. const empty = document.getElementById('mangle-empty');
  4083. if (!tbody) return;
  4084. tbody.innerHTML = '';
  4085. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4086. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4087. if (rules.length === 0) {
  4088. empty?.classList.remove('hidden');
  4089. return;
  4090. }
  4091. empty?.classList.add('hidden');
  4092. rules.forEach((r, idx) => {
  4093. const tr = document.createElement('tr');
  4094. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4095. let markVal = '<span class="text-slate-500">-</span>';
  4096. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4097. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4098. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4099. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4100. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4101. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4102. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4103. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4104. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4105. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4106. 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>`;
  4107. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4108. tr.innerHTML = `
  4109. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4110. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4111. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4112. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4113. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4114. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4115. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4116. <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>
  4117. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4118. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4119. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4120. </td>
  4121. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4122. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4123. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4124. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4125. <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>
  4126. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4127. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4128. </td>
  4129. `;
  4130. tbody.appendChild(tr);
  4131. });
  4132. }
  4133. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4134. function switchMangleRuleTab(tab) {
  4135. state.activeMangleRuleTab = tab;
  4136. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4137. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4138. btn.classList.add('text-slate-400', 'border-transparent');
  4139. });
  4140. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4141. if (activeBtn) {
  4142. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4143. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4144. }
  4145. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4146. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4147. if (activePane) activePane.classList.remove('hidden');
  4148. if (tab === 'statistics') {
  4149. startMangleStatPolling();
  4150. } else {
  4151. stopMangleStatPolling();
  4152. }
  4153. }
  4154. function toggleMangleField(fieldKey, expand) {
  4155. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4156. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4157. if (!plusBtn || !fieldBox) return;
  4158. if (expand) {
  4159. plusBtn.classList.add('hidden');
  4160. fieldBox.classList.remove('hidden');
  4161. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4162. if (valInput) valInput.focus();
  4163. } else {
  4164. fieldBox.classList.add('hidden');
  4165. plusBtn.classList.remove('hidden');
  4166. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4167. if (valInput) {
  4168. if (valInput.tagName === 'SELECT') {
  4169. valInput.selectedIndex = 0;
  4170. } else {
  4171. valInput.value = '';
  4172. }
  4173. }
  4174. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4175. if (invInput) invInput.checked = false;
  4176. if (fieldKey === 'cs') {
  4177. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4178. const el = document.getElementById(id);
  4179. if (el) el.checked = false;
  4180. });
  4181. }
  4182. if (fieldKey === 'natstate') {
  4183. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4184. const el = document.getElementById(id);
  4185. if (el) el.checked = false;
  4186. });
  4187. }
  4188. }
  4189. }
  4190. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4191. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4192. toggleMangleField(fieldKey, true);
  4193. let strVal = String(value);
  4194. if (hasInvert) {
  4195. const inv = strVal.startsWith('!');
  4196. if (inv) strVal = strVal.slice(1);
  4197. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4198. if (invEl) invEl.checked = inv;
  4199. }
  4200. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4201. if (valEl) valEl.value = strVal;
  4202. } else {
  4203. toggleMangleField(fieldKey, false);
  4204. }
  4205. }
  4206. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4207. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4208. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4209. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4210. let v = valEl ? valEl.value.trim() : '';
  4211. if (!v) return '';
  4212. if (hasInvert) {
  4213. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4214. if (invEl && invEl.checked) {
  4215. v = '!' + v.replace(/^!/, '');
  4216. }
  4217. }
  4218. return v;
  4219. }
  4220. function toggleMaximizeMangleModal() {
  4221. const win = document.getElementById('mangle-modal-window');
  4222. if (!win) return;
  4223. if (win.classList.contains('max-w-[720px]')) {
  4224. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4225. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4226. } else {
  4227. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4228. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4229. }
  4230. }
  4231. function toggleMangleActionFields() {
  4232. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4233. // Hide all dynamic rows first
  4234. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4235. const el = document.getElementById(`mangle-row-${id}`);
  4236. if (el) el.classList.add('hidden');
  4237. });
  4238. const jumpBox = document.getElementById('mangle-action-jump-box');
  4239. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4240. if (jumpBox) jumpBox.classList.add('hidden');
  4241. if (addrBox) addrBox.classList.add('hidden');
  4242. // Activate matching rows
  4243. if (act === 'mark-connection') {
  4244. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4245. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4246. } else if (act === 'mark-routing') {
  4247. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4248. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4249. } else if (act === 'mark-packet') {
  4250. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4251. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4252. } else if (act === 'change-mss') {
  4253. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4254. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4255. } else if (act === 'change-dscp') {
  4256. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4257. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4258. } else if (act === 'change-ttl') {
  4259. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4260. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4261. } else if (act === 'set-priority') {
  4262. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4263. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4264. } else if (act === 'route') {
  4265. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4266. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4267. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4268. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4269. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4270. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4271. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4272. } else if (act === 'jump') {
  4273. if (jumpBox) jumpBox.classList.remove('hidden');
  4274. } else if (act.includes('address-list') || act.includes('address list')) {
  4275. if (addrBox) addrBox.classList.remove('hidden');
  4276. }
  4277. if (act === 'log') {
  4278. const logEl = document.getElementById('mangle-modal-log');
  4279. if (logEl) logEl.checked = true;
  4280. toggleMangleField('logprefix', true);
  4281. }
  4282. }
  4283. function toggleMangleLogPrefix() {
  4284. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4285. toggleMangleField('logprefix', !!isLog);
  4286. }
  4287. const allMangleFieldKeys = [
  4288. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4289. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4290. 'routingmark', 'conntype', 'cs', 'natstate',
  4291. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4292. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4293. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4294. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4295. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4296. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4297. ];
  4298. function openAddMangleModal() {
  4299. switchMangleRuleTab('general');
  4300. const badge = document.getElementById('mangle-modal-badge');
  4301. if (badge) badge.innerText = 'New...';
  4302. document.getElementById('mangle-modal-id').value = '';
  4303. document.getElementById('mangle-modal-enabled').checked = true;
  4304. document.getElementById('mangle-modal-comment').value = '';
  4305. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4306. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4307. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4308. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4309. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4310. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4311. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4312. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4313. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4314. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4315. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4316. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4317. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4318. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4319. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4320. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4321. populateInterfaceSelect('mangle-val-iniface');
  4322. populateInterfaceSelect('mangle-val-outiface');
  4323. populateAddressListSelect('mangle-val-srclist');
  4324. populateAddressListSelect('mangle-val-dstlist');
  4325. populateGeoIPSelect('mangle-val-srcgeo');
  4326. populateGeoIPSelect('mangle-val-dstgeo');
  4327. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4328. resetCurrentMangleRuleCounters();
  4329. toggleMangleActionFields();
  4330. document.getElementById('mangle-modal').classList.remove('hidden');
  4331. }
  4332. function openEditMangleModal(id) {
  4333. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4334. if (!r) return;
  4335. switchMangleRuleTab('general');
  4336. const badge = document.getElementById('mangle-modal-badge');
  4337. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4338. document.getElementById('mangle-modal-id').value = r.id;
  4339. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4340. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4341. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4342. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4343. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4344. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4345. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4346. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4347. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4348. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4349. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4350. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4351. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4352. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4353. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4354. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4355. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4356. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4357. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4358. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4359. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4360. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4361. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4362. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4363. setMangleFieldVal('src', r.src_address, true);
  4364. setMangleFieldVal('dst', r.dst_address, true);
  4365. setMangleFieldVal('srclist', r.src_address_list, true);
  4366. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4367. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4368. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4369. if (r.protocol && r.protocol !== 'all') {
  4370. setMangleFieldVal('proto', r.protocol, true);
  4371. } else {
  4372. toggleMangleField('proto', false);
  4373. }
  4374. setMangleFieldVal('sport', r.src_port, true);
  4375. setMangleFieldVal('dport', r.dst_port, true);
  4376. setMangleFieldVal('anyport', r.any_port, true);
  4377. setMangleFieldVal('iniface', r.in_interface, true);
  4378. setMangleFieldVal('outiface', r.out_interface, true);
  4379. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4380. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4381. setMangleFieldVal('pktmark', r.packet_mark, true);
  4382. setMangleFieldVal('connmark', r.connection_mark, true);
  4383. setMangleFieldVal('routingmark', r.routing_mark, true);
  4384. setMangleFieldVal('conntype', r.connection_type, false);
  4385. // Connection State
  4386. const states = r.connection_state || [];
  4387. if (states.length > 0) {
  4388. toggleMangleField('cs', true);
  4389. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4390. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4391. if (el) el.checked = states.includes(s);
  4392. });
  4393. } else {
  4394. toggleMangleField('cs', false);
  4395. }
  4396. // Connection NAT State
  4397. const natStates = r.connection_nat_state || [];
  4398. if (natStates.length > 0) {
  4399. toggleMangleField('natstate', true);
  4400. ['srcnat', 'dstnat'].forEach(s => {
  4401. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4402. if (el) el.checked = natStates.includes(s);
  4403. });
  4404. } else {
  4405. toggleMangleField('natstate', false);
  4406. }
  4407. // Advanced tab fields
  4408. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4409. setMangleFieldVal('content', r.content, false);
  4410. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4411. setMangleFieldVal('connrate', r.connection_rate, false);
  4412. setMangleFieldVal('pcc', r.pcc, false);
  4413. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4414. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4415. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4416. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4417. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4418. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4419. setMangleFieldVal('tlshost', r.tls_host, false);
  4420. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4421. setMangleFieldVal('priority', r.priority, false);
  4422. setMangleFieldVal('dscp', r.dscp, false);
  4423. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4424. if (r.tos) {
  4425. const tosEl = document.getElementById('mangle-val-tos');
  4426. if (tosEl) tosEl.value = r.tos;
  4427. }
  4428. setMangleFieldVal('pktsize', r.packet_size, false);
  4429. setMangleFieldVal('random', r.random, false);
  4430. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4431. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4432. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4433. setMangleFieldVal('ttl', r.ttl, false);
  4434. // Extra tab fields
  4435. setMangleFieldVal('nth', r.nth, false);
  4436. setMangleFieldVal('connlimit', r.connection_limit, false);
  4437. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4438. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4439. setMangleFieldVal('hotspot', r.hotspot, false);
  4440. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4441. setMangleFieldVal('limit', r.limit, false);
  4442. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4443. setMangleFieldVal('time', r.time, false);
  4444. setMangleFieldVal('psd', r.psd, false);
  4445. // Action fields
  4446. if (r.jump_target) {
  4447. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4448. if (jtEl) jtEl.value = r.jump_target;
  4449. }
  4450. if (r.address_list) {
  4451. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4452. if (alEl) alEl.value = r.address_list;
  4453. }
  4454. if (r.address_list_timeout) {
  4455. const toEl = document.getElementById('mangle-modal-action-timeout');
  4456. if (toEl) toEl.value = r.address_list_timeout;
  4457. }
  4458. setMangleFieldVal('logprefix', r.log_prefix, false);
  4459. // Statistics
  4460. const bEl = document.getElementById('mangle-stat-bytes');
  4461. const pEl = document.getElementById('mangle-stat-packets');
  4462. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4463. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4464. state.mangleLastBytes = r.bytes || 0;
  4465. state.mangleLastPackets = r.packets || 0;
  4466. state.mangleLastTimestamp = Date.now();
  4467. state.mangleStatRateHistory = new Array(30).fill(0);
  4468. state.mangleStatPktHistory = new Array(30).fill(0);
  4469. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4470. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4471. toggleMangleActionFields();
  4472. document.getElementById('mangle-modal').classList.remove('hidden');
  4473. }
  4474. function closeMangleModal() {
  4475. stopMangleStatPolling();
  4476. document.getElementById('mangle-modal').classList.add('hidden');
  4477. }
  4478. function copyMangleRule() {
  4479. document.getElementById('mangle-modal-id').value = '';
  4480. const badge = document.getElementById('mangle-modal-badge');
  4481. if (badge) badge.innerText = 'New...';
  4482. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4483. }
  4484. function resetCurrentMangleRuleCounters() {
  4485. state.mangleStatRateHistory = new Array(30).fill(0);
  4486. state.mangleStatPktHistory = new Array(30).fill(0);
  4487. state.mangleLastBytes = 0;
  4488. state.mangleLastPackets = 0;
  4489. state.mangleLastTimestamp = Date.now();
  4490. const bEl = document.getElementById('mangle-stat-bytes');
  4491. const pEl = document.getElementById('mangle-stat-packets');
  4492. const rEl = document.getElementById('mangle-stat-rate');
  4493. const prEl = document.getElementById('mangle-stat-pktrate');
  4494. if (bEl) bEl.value = '0 B';
  4495. if (pEl) pEl.value = '0';
  4496. if (rEl) rEl.value = '0 bps';
  4497. if (prEl) prEl.value = '0 p/s';
  4498. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4499. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4500. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4501. }
  4502. async function applyMangleRule(closeAfter = false) {
  4503. const id = document.getElementById('mangle-modal-id').value;
  4504. const chain = document.getElementById('mangle-modal-chain').value;
  4505. const action = document.getElementById('mangle-modal-action').value;
  4506. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4507. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4508. const src = getMangleFieldVal('src', true);
  4509. const dst = getMangleFieldVal('dst', true);
  4510. const srclist = getMangleFieldVal('srclist', true);
  4511. const dstlist = getMangleFieldVal('dstlist', true);
  4512. const srcgeo = getMangleFieldVal('srcgeo', true);
  4513. const dstgeo = getMangleFieldVal('dstgeo', true);
  4514. const proto = getMangleFieldVal('proto', true);
  4515. const sport = getMangleFieldVal('sport', true);
  4516. const dport = getMangleFieldVal('dport', true);
  4517. const anyport = getMangleFieldVal('anyport', true);
  4518. const iniface = getMangleFieldVal('iniface', true);
  4519. const outiface = getMangleFieldVal('outiface', true);
  4520. const inifacelist = getMangleFieldVal('inifacelist', true);
  4521. const outifacelist = getMangleFieldVal('outifacelist', true);
  4522. const pktmark = getMangleFieldVal('pktmark', true);
  4523. const connmark = getMangleFieldVal('connmark', true);
  4524. const routingmark = getMangleFieldVal('routingmark', true);
  4525. const conntype = getMangleFieldVal('conntype', false);
  4526. const states = [];
  4527. const csBox = document.getElementById('mangle-field-cs');
  4528. if (csBox && !csBox.classList.contains('hidden')) {
  4529. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4530. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4531. });
  4532. }
  4533. const natStates = [];
  4534. const natBox = document.getElementById('mangle-field-natstate');
  4535. if (natBox && !natBox.classList.contains('hidden')) {
  4536. ['srcnat', 'dstnat'].forEach(s => {
  4537. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4538. });
  4539. }
  4540. const payload = {
  4541. id,
  4542. chain,
  4543. action,
  4544. protocol: proto || 'all',
  4545. src_address: src,
  4546. dst_address: dst,
  4547. src_port: sport,
  4548. dst_port: dport,
  4549. any_port: anyport,
  4550. in_interface: iniface,
  4551. out_interface: outiface,
  4552. in_interface_list: inifacelist,
  4553. out_interface_list: outifacelist,
  4554. packet_mark: pktmark,
  4555. connection_mark: connmark,
  4556. routing_mark: routingmark,
  4557. connection_type: conntype,
  4558. connection_state: states,
  4559. connection_nat_state: natStates,
  4560. src_address_list: srclist,
  4561. dst_address_list: dstlist,
  4562. src_geoip: srcgeo,
  4563. dst_geoip: dstgeo,
  4564. comment,
  4565. disabled: !enabled,
  4566. // Advanced tab
  4567. layer7_protocol: getMangleFieldVal('layer7', false),
  4568. content: getMangleFieldVal('content', false),
  4569. connection_bytes: getMangleFieldVal('connbytes', false),
  4570. connection_rate: getMangleFieldVal('connrate', false),
  4571. pcc: getMangleFieldVal('pcc', false),
  4572. src_mac_address: getMangleFieldVal('srcmac', true),
  4573. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4574. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4575. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4576. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4577. ipsec_policy: getMangleFieldVal('ipsec', false),
  4578. tls_host: getMangleFieldVal('tlshost', false),
  4579. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4580. priority: getMangleFieldVal('priority', false),
  4581. dscp: getMangleFieldVal('dscp', false),
  4582. tcp_mss: getMangleFieldVal('tcpmss', false),
  4583. tos: document.getElementById('mangle-val-tos')?.value || '',
  4584. packet_size: getMangleFieldVal('pktsize', false),
  4585. random: getMangleFieldVal('random', false),
  4586. tcp_flags: getMangleFieldVal('tcpflags', false),
  4587. icmp_options: getMangleFieldVal('icmpoptions', false),
  4588. ipv4_options: getMangleFieldVal('ipv4options', false),
  4589. ttl: getMangleFieldVal('ttl', false),
  4590. // Extra tab
  4591. nth: getMangleFieldVal('nth', false),
  4592. connection_limit: getMangleFieldVal('connlimit', false),
  4593. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4594. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4595. hotspot: getMangleFieldVal('hotspot', false),
  4596. ip_fragment: getMangleFieldVal('ipfragment', false),
  4597. limit: getMangleFieldVal('limit', false),
  4598. dst_limit: getMangleFieldVal('dstlimit', false),
  4599. time: getMangleFieldVal('time', false),
  4600. psd: getMangleFieldVal('psd', false),
  4601. // Action tab
  4602. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4603. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4604. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4605. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4606. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4607. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4608. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4609. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4610. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4611. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4612. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4613. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4614. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4615. log: document.getElementById('mangle-modal-log')?.checked || false,
  4616. log_prefix: getMangleFieldVal('logprefix', false)
  4617. };
  4618. try {
  4619. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4620. method: 'POST',
  4621. headers: { 'Content-Type': 'application/json' },
  4622. body: JSON.stringify(payload)
  4623. });
  4624. if (res.ok) {
  4625. const data = await res.json();
  4626. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4627. loadFirewall(false);
  4628. if (closeAfter) {
  4629. closeMangleModal();
  4630. } else {
  4631. if (data.id) {
  4632. document.getElementById('mangle-modal-id').value = data.id;
  4633. const badge = document.getElementById('mangle-modal-badge');
  4634. if (badge) badge.innerText = `#${data.id}`;
  4635. }
  4636. }
  4637. } else {
  4638. const err = await res.json();
  4639. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4640. }
  4641. } catch (err) {
  4642. showToast('Error', err.message, 'error');
  4643. }
  4644. }
  4645. function submitSaveMangleRule(e) {
  4646. if (e && e.preventDefault) e.preventDefault();
  4647. return applyMangleRule(true);
  4648. }
  4649. function startMangleStatPolling() {
  4650. stopMangleStatPolling();
  4651. pollMangleRuleStats();
  4652. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4653. }
  4654. function stopMangleStatPolling() {
  4655. if (state.mangleStatInterval) {
  4656. clearInterval(state.mangleStatInterval);
  4657. state.mangleStatInterval = null;
  4658. }
  4659. }
  4660. async function pollMangleRuleStats() {
  4661. const id = document.getElementById('mangle-modal-id')?.value;
  4662. if (!id) {
  4663. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4664. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4665. return;
  4666. }
  4667. try {
  4668. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4669. if (!res.ok) return;
  4670. const rules = await res.json();
  4671. const r = rules.find(x => x.id === id);
  4672. if (!r) return;
  4673. const now = Date.now();
  4674. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4675. state.mangleLastTimestamp = now;
  4676. const curBytes = r.bytes || 0;
  4677. const curPackets = r.packets || 0;
  4678. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4679. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4680. state.mangleLastBytes = curBytes;
  4681. state.mangleLastPackets = curPackets;
  4682. const rateBps = Math.round((deltaBytes * 8) / dt);
  4683. const ratePkt = Math.round(deltaPkts / dt);
  4684. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4685. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4686. state.mangleStatRateHistory.push(rateBps);
  4687. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4688. state.mangleStatPktHistory.push(ratePkt);
  4689. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4690. const bEl = document.getElementById('mangle-stat-bytes');
  4691. const pEl = document.getElementById('mangle-stat-packets');
  4692. const rEl = document.getElementById('mangle-stat-rate');
  4693. const prEl = document.getElementById('mangle-stat-pktrate');
  4694. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4695. if (pEl) pEl.value = curPackets.toLocaleString();
  4696. if (rEl) rEl.value = formatBps(rateBps);
  4697. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4698. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4699. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4700. } catch (e) {
  4701. console.error('Error polling Mangle rule stats', e);
  4702. }
  4703. }
  4704. async function moveMangleRule(id, dir) {
  4705. try {
  4706. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4707. method: 'POST',
  4708. headers: { 'Content-Type': 'application/json' },
  4709. body: JSON.stringify({ direction: dir })
  4710. });
  4711. if (res.ok) loadFirewall(false);
  4712. } catch (err) {
  4713. showToast('Error', err.message, 'error');
  4714. }
  4715. }
  4716. async function toggleMangleRuleState(id, disabled) {
  4717. try {
  4718. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4719. method: 'POST',
  4720. headers: { 'Content-Type': 'application/json' },
  4721. body: JSON.stringify({ disabled })
  4722. });
  4723. if (res.ok) loadFirewall(false);
  4724. } catch (err) {
  4725. showToast('Error', err.message, 'error');
  4726. }
  4727. }
  4728. async function deleteMangleRule(id) {
  4729. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4730. try {
  4731. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4732. if (res.ok) {
  4733. showToast('Deleted', 'Mangle rule removed', 'success');
  4734. loadFirewall(false);
  4735. }
  4736. } catch (err) {
  4737. showToast('Error', err.message, 'error');
  4738. }
  4739. }
  4740. // ----------------- Address Lists -----------------
  4741. function renderAddressLists() {
  4742. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4743. const tbody = document.getElementById('addrlist-table-body');
  4744. const empty = document.getElementById('addrlist-empty');
  4745. if (!tbody) return;
  4746. tbody.innerHTML = '';
  4747. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4748. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4749. // Update filter select
  4750. const sel = document.getElementById('addrlist-filter-name');
  4751. if (sel) {
  4752. const cur = sel.value;
  4753. sel.innerHTML = '<option value="">All Lists</option>';
  4754. const set = new Set((state.addressLists || []).map(a => a.name));
  4755. set.forEach(n => {
  4756. const opt = document.createElement('option');
  4757. opt.value = n;
  4758. opt.innerText = n;
  4759. if (n === cur) opt.selected = true;
  4760. sel.appendChild(opt);
  4761. });
  4762. }
  4763. if (entries.length === 0) {
  4764. empty?.classList.remove('hidden');
  4765. return;
  4766. }
  4767. empty?.classList.add('hidden');
  4768. entries.forEach((e, idx) => {
  4769. const tr = document.createElement('tr');
  4770. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4771. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4772. tr.innerHTML = `
  4773. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4774. <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>
  4775. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4776. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4777. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4778. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4779. <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>
  4780. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4781. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4782. </td>
  4783. `;
  4784. tbody.appendChild(tr);
  4785. });
  4786. populateCommonAddrListDatalist();
  4787. }
  4788. function openAddAddrListModal() {
  4789. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4790. document.getElementById('addrlist-modal-id').value = '';
  4791. document.getElementById('addrlist-modal-name').value = '';
  4792. document.getElementById('addrlist-modal-addr').value = '';
  4793. document.getElementById('addrlist-modal-comment').value = '';
  4794. document.getElementById('addrlist-modal-disabled').checked = false;
  4795. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4796. if (submitBtn) submitBtn.innerText = 'Add to List';
  4797. document.getElementById('addrlist-modal').classList.remove('hidden');
  4798. }
  4799. function openEditAddrListModal(id) {
  4800. const e = (state.addressLists || []).find(item => item.id === id);
  4801. if (!e) return;
  4802. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4803. document.getElementById('addrlist-modal-id').value = e.id;
  4804. document.getElementById('addrlist-modal-name').value = e.name;
  4805. document.getElementById('addrlist-modal-addr').value = e.address;
  4806. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4807. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4808. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4809. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4810. document.getElementById('addrlist-modal').classList.remove('hidden');
  4811. }
  4812. function closeAddrListModal() {
  4813. document.getElementById('addrlist-modal').classList.add('hidden');
  4814. }
  4815. async function submitSaveAddrList(e) {
  4816. e.preventDefault();
  4817. const id = document.getElementById('addrlist-modal-id').value;
  4818. const name = document.getElementById('addrlist-modal-name').value.trim();
  4819. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4820. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4821. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4822. try {
  4823. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4824. method: 'POST',
  4825. headers: { 'Content-Type': 'application/json' },
  4826. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4827. });
  4828. if (res.ok) {
  4829. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4830. closeAddrListModal();
  4831. loadFirewall(false);
  4832. } else {
  4833. const err = await res.json();
  4834. showToast('Error', err.message || 'Failed to save address list', 'error');
  4835. }
  4836. } catch (err) {
  4837. showToast('Error', err.message, 'error');
  4838. }
  4839. }
  4840. async function toggleAddrListState(id, disabled) {
  4841. try {
  4842. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4843. method: 'POST',
  4844. headers: { 'Content-Type': 'application/json' },
  4845. body: JSON.stringify({ disabled })
  4846. });
  4847. if (res.ok) {
  4848. loadFirewall(false);
  4849. }
  4850. } catch (err) {
  4851. showToast('Error', err.message, 'error');
  4852. }
  4853. }
  4854. async function deleteAddrList(id) {
  4855. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4856. try {
  4857. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4858. if (res.ok) {
  4859. showToast('Deleted', 'Address list item removed', 'info');
  4860. loadFirewall(false);
  4861. }
  4862. } catch (err) {
  4863. showToast('Error', err.message, 'error');
  4864. }
  4865. }
  4866. // ----------------- Geo-Location IP Management -----------------
  4867. async function loadGeoIP() {
  4868. try {
  4869. const [statusRes, countriesRes] = await Promise.all([
  4870. fetch(`${API_BASE}/firewall/geoip/status`),
  4871. fetch(`${API_BASE}/firewall/geoip/countries`)
  4872. ]);
  4873. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4874. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4875. updateGeoHeader();
  4876. renderGeoCountries();
  4877. } catch (err) {
  4878. console.error('Failed to load GeoIP:', err);
  4879. }
  4880. }
  4881. function getGeoUsageMap() {
  4882. const usage = {};
  4883. const checkRule = (r, type) => {
  4884. ['src_geoip', 'dst_geoip'].forEach(field => {
  4885. let val = (r && r[field]) || '';
  4886. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4887. if (code) {
  4888. if (!usage[code]) usage[code] = [];
  4889. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4890. if (!usage[code].includes(label)) usage[code].push(label);
  4891. }
  4892. });
  4893. };
  4894. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4895. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4896. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4897. return usage;
  4898. }
  4899. function updateGeoHeader() {
  4900. const s = state.geoStatus || {};
  4901. const statusBadge = document.getElementById('geo-status-badge');
  4902. if (statusBadge) {
  4903. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4904. statusBadge.className = s.auto_update
  4905. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4906. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4907. }
  4908. const intervalLabel = document.getElementById('geo-interval-label');
  4909. if (intervalLabel) {
  4910. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4911. }
  4912. const usageMap = getGeoUsageMap();
  4913. const inUseCount = Object.keys(usageMap).length;
  4914. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4915. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4916. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4917. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4918. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4919. if (lastSyncEl) {
  4920. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4921. const d = new Date(s.last_updated);
  4922. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4923. } else {
  4924. lastSyncEl.innerText = 'Never (Sync Pending)';
  4925. }
  4926. }
  4927. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4928. if (nextSyncEl) {
  4929. if (s.next_update && !s.next_update.startsWith('0001')) {
  4930. const d = new Date(s.next_update);
  4931. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4932. } else {
  4933. nextSyncEl.innerText = '-';
  4934. }
  4935. }
  4936. const badge = document.getElementById('fw-badge-geo');
  4937. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4938. }
  4939. function renderGeoCountries() {
  4940. const tbody = document.getElementById('geo-table-body');
  4941. const empty = document.getElementById('geo-empty');
  4942. if (!tbody) return;
  4943. tbody.innerHTML = '';
  4944. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4945. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4946. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4947. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4948. const usageMap = getGeoUsageMap();
  4949. const countries = (state.geoCountries || []).filter(c => {
  4950. const isUsed = !!usageMap[c.code];
  4951. if (inUseOnly && !isUsed) return false;
  4952. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4953. if (continent && c.continent !== continent) return false;
  4954. if (q) {
  4955. const matchCode = c.code.toLowerCase().includes(q);
  4956. const matchName = c.name.toLowerCase().includes(q);
  4957. if (!matchCode && !matchName) return false;
  4958. }
  4959. return true;
  4960. });
  4961. if (countries.length === 0) {
  4962. empty?.classList.remove('hidden');
  4963. return;
  4964. }
  4965. empty?.classList.add('hidden');
  4966. countries.forEach(c => {
  4967. const tr = document.createElement('tr');
  4968. const isUsed = !!usageMap[c.code];
  4969. const rulesUsing = usageMap[c.code] || [];
  4970. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4971. let statusHtml = '';
  4972. if (isUsed) {
  4973. 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>`;
  4974. } else if (c.subnet_count > 0) {
  4975. 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>';
  4976. } else {
  4977. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4978. }
  4979. tr.innerHTML = `
  4980. <td class="py-2.5 px-3 text-center">
  4981. <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'}">
  4982. ${c.code}
  4983. </span>
  4984. </td>
  4985. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  4986. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  4987. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  4988. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  4989. </td>
  4990. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  4991. <td class="py-2.5 px-3">
  4992. ${statusHtml}
  4993. </td>
  4994. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4995. <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>
  4996. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  4997. </td>
  4998. `;
  4999. tbody.appendChild(tr);
  5000. });
  5001. }
  5002. function quickFilterGeo(preset) {
  5003. const searchInput = document.getElementById('geo-search-input');
  5004. const continentSel = document.getElementById('geo-continent-filter');
  5005. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5006. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5007. if (searchInput) searchInput.value = '';
  5008. if (continentSel) continentSel.value = '';
  5009. if (inUseCheck) inUseCheck.checked = false;
  5010. if (cachedCheck) cachedCheck.checked = false;
  5011. if (preset === 'GR') {
  5012. if (searchInput) searchInput.value = 'Greece';
  5013. } else if (preset === 'Europe') {
  5014. if (continentSel) continentSel.value = 'Europe';
  5015. } else if (preset === 'HIGHRISK') {
  5016. if (searchInput) searchInput.value = 'China';
  5017. }
  5018. renderGeoCountries();
  5019. }
  5020. async function toggleGeoCountry(code, enabled) {
  5021. try {
  5022. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5023. method: 'POST',
  5024. headers: { 'Content-Type': 'application/json' },
  5025. body: JSON.stringify({ enabled })
  5026. });
  5027. if (res.ok) {
  5028. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5029. loadGeoIP();
  5030. } else {
  5031. const err = await res.json();
  5032. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5033. }
  5034. } catch (err) {
  5035. showToast('Error', err.message, 'error');
  5036. }
  5037. }
  5038. async function updateGeoCountry(code) {
  5039. try {
  5040. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5041. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5042. if (res.ok) {
  5043. const data = await res.json();
  5044. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5045. loadGeoIP();
  5046. } else {
  5047. const err = await res.json();
  5048. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5049. }
  5050. } catch (err) {
  5051. showToast('Error', err.message, 'error');
  5052. }
  5053. }
  5054. async function triggerGeoUpdateNow() {
  5055. const spinner = document.getElementById('geo-update-spinner');
  5056. if (spinner) spinner.classList.remove('hidden');
  5057. try {
  5058. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5059. if (res.ok) {
  5060. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5061. setTimeout(() => {
  5062. loadGeoIP();
  5063. if (spinner) spinner.classList.add('hidden');
  5064. }, 2500);
  5065. } else {
  5066. const err = await res.json();
  5067. showToast('Notice', err.message || 'Update in progress', 'info');
  5068. if (spinner) spinner.classList.add('hidden');
  5069. }
  5070. } catch (err) {
  5071. showToast('Error', err.message, 'error');
  5072. if (spinner) spinner.classList.add('hidden');
  5073. }
  5074. }
  5075. async function applyGeoPreset(preset) {
  5076. try {
  5077. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5078. method: 'POST',
  5079. headers: { 'Content-Type': 'application/json' },
  5080. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5081. });
  5082. if (res.ok) {
  5083. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5084. loadGeoIP();
  5085. }
  5086. } catch (err) {
  5087. showToast('Error', err.message, 'error');
  5088. }
  5089. }
  5090. function openGeoIntervalModal() {
  5091. const s = state.geoStatus || {};
  5092. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5093. const sel = document.getElementById('geo-cfg-interval');
  5094. const customBox = document.getElementById('geo-cfg-custom-box');
  5095. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5096. const curHours = s.interval_hours || 24;
  5097. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5098. if (matchOption) {
  5099. sel.value = String(curHours);
  5100. customBox.classList.add('hidden');
  5101. } else {
  5102. sel.value = 'custom';
  5103. customHoursInput.value = curHours;
  5104. customBox.classList.remove('hidden');
  5105. }
  5106. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5107. }
  5108. function closeGeoIntervalModal() {
  5109. document.getElementById('geo-interval-modal').classList.add('hidden');
  5110. }
  5111. function toggleCustomGeoInterval() {
  5112. const val = document.getElementById('geo-cfg-interval').value;
  5113. const customBox = document.getElementById('geo-cfg-custom-box');
  5114. if (val === 'custom') {
  5115. customBox.classList.remove('hidden');
  5116. } else {
  5117. customBox.classList.add('hidden');
  5118. }
  5119. }
  5120. async function submitGeoIntervalSettings(e) {
  5121. e.preventDefault();
  5122. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5123. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5124. let hours = 24;
  5125. if (intervalVal === 'custom') {
  5126. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5127. } else {
  5128. hours = parseInt(intervalVal, 10) || 24;
  5129. }
  5130. try {
  5131. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5132. method: 'POST',
  5133. headers: { 'Content-Type': 'application/json' },
  5134. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5135. });
  5136. if (res.ok) {
  5137. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5138. closeGeoIntervalModal();
  5139. loadGeoIP();
  5140. } else {
  5141. const err = await res.json();
  5142. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5143. }
  5144. } catch (err) {
  5145. showToast('Error', err.message, 'error');
  5146. }
  5147. }
  5148. async function viewGeoSubnets(code, name) {
  5149. if (!name) {
  5150. const found = (state.geoCountries || []).find(x => x.code === code);
  5151. name = found ? found.name : code;
  5152. }
  5153. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5154. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5155. const listEl = document.getElementById('geo-subnets-list');
  5156. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5157. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5158. try {
  5159. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5160. if (res.ok) {
  5161. const data = await res.json();
  5162. const subnets = data.subnets || [];
  5163. if (subnets.length === 0) {
  5164. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5165. } else {
  5166. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5167. }
  5168. } else {
  5169. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5170. }
  5171. } catch (err) {
  5172. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5173. }
  5174. }
  5175. function closeGeoSubnetsModal() {
  5176. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5177. }
  5178. // ----------------- Active Connections Tracking -----------------
  5179. async function loadConnections() {
  5180. try {
  5181. const res = await fetch(`${API_BASE}/firewall/connections`);
  5182. const data = await res.json();
  5183. state.connections = Array.isArray(data) ? data : [];
  5184. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5185. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5186. renderConnections();
  5187. } catch (err) {
  5188. console.error('Failed to load connections:', err);
  5189. }
  5190. }
  5191. function renderConnections() {
  5192. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5193. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5194. const tbody = document.getElementById('conns-table-body');
  5195. const empty = document.getElementById('conns-empty');
  5196. if (!tbody) return;
  5197. tbody.innerHTML = '';
  5198. const conns = (state.connections || []).filter(c => {
  5199. if (protoFilter && c.protocol !== protoFilter) return false;
  5200. if (search) {
  5201. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5202. if (!line.includes(search)) return false;
  5203. }
  5204. return true;
  5205. });
  5206. if (conns.length === 0) {
  5207. empty?.classList.remove('hidden');
  5208. return;
  5209. }
  5210. empty?.classList.add('hidden');
  5211. conns.slice(0, 150).forEach(c => {
  5212. const tr = document.createElement('tr');
  5213. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5214. let stateColor = 'text-slate-400';
  5215. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5216. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5217. tr.innerHTML = `
  5218. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5219. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5220. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5221. <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>
  5222. <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>
  5223. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5224. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5225. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5226. <td class="py-2.5 px-3 text-right font-sans">
  5227. <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>
  5228. </td>
  5229. `;
  5230. tbody.appendChild(tr);
  5231. });
  5232. }
  5233. async function killConnection(protocol, src, sport, dst, dport) {
  5234. try {
  5235. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5236. method: 'POST',
  5237. headers: { 'Content-Type': 'application/json' },
  5238. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5239. });
  5240. if (res.ok) {
  5241. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5242. loadConnections();
  5243. }
  5244. } catch (err) {
  5245. showToast('Error', err.message, 'error');
  5246. }
  5247. }
  5248. async function resetFirewallCounters() {
  5249. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5250. try {
  5251. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5252. if (res.ok) {
  5253. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5254. loadFirewall(false);
  5255. }
  5256. } catch (err) {
  5257. showToast('Error', err.message, 'error');
  5258. }
  5259. }
  5260. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5261. function switchRoutesSubTab(tab) {
  5262. state.routesSubTab = tab;
  5263. const tabs = ['routes', 'rules', 'tables'];
  5264. tabs.forEach(t => {
  5265. const panel = document.getElementById(`routes-subtab-${t}`);
  5266. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5267. if (panel) {
  5268. if (t === tab) panel.classList.remove('hidden');
  5269. else panel.classList.add('hidden');
  5270. }
  5271. if (btn) {
  5272. if (t === tab) {
  5273. 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';
  5274. } else {
  5275. 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';
  5276. }
  5277. }
  5278. });
  5279. setTimeout(initTableSorting, 50);
  5280. }
  5281. async function loadRoutes() {
  5282. try {
  5283. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5284. fetch(`${API_BASE}/routes`),
  5285. fetch(`${API_BASE}/routing/rules`),
  5286. fetch(`${API_BASE}/routing/tables`)
  5287. ]);
  5288. if (routesRes.ok) state.routes = await routesRes.json();
  5289. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5290. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5291. const bRoutes = document.getElementById('routes-badge-routes');
  5292. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5293. const showSystem = document.getElementById('prule-show-system')?.checked;
  5294. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5295. const bRules = document.getElementById('routes-badge-rules');
  5296. if (bRules) bRules.innerText = userRules.length;
  5297. const bTables = document.getElementById('routes-badge-tables');
  5298. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5299. const bRoutesCount = document.getElementById('badge-routes-count');
  5300. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5301. renderRoutesList();
  5302. renderPolicyRules();
  5303. renderRoutingTables();
  5304. } catch (err) {
  5305. console.error('Failed to load routing:', err);
  5306. }
  5307. }
  5308. function renderRoutesList() {
  5309. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5310. const tbody = document.getElementById('routes-table-body');
  5311. const empty = document.getElementById('routes-empty');
  5312. if (!tbody) return;
  5313. tbody.innerHTML = '';
  5314. // Update table filter select
  5315. const sel = document.getElementById('routes-filter-table');
  5316. if (sel) {
  5317. const cur = sel.value;
  5318. sel.innerHTML = '<option value="">All Tables</option>';
  5319. (state.routingTables || []).forEach(t => {
  5320. const opt = document.createElement('option');
  5321. opt.value = t.name;
  5322. opt.innerText = t.name;
  5323. if (t.name === cur) opt.selected = true;
  5324. sel.appendChild(opt);
  5325. });
  5326. }
  5327. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5328. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5329. if (routes.length === 0) {
  5330. empty?.classList.remove('hidden');
  5331. return;
  5332. }
  5333. empty?.classList.add('hidden');
  5334. routes.forEach(r => {
  5335. const tr = document.createElement('tr');
  5336. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5337. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5338. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5339. let flags = '';
  5340. if (r.dynamic) flags += 'D';
  5341. if (r.active) flags += 'A';
  5342. if (r.connect) flags += 'C';
  5343. if (r.static) flags += 'S';
  5344. if (r.disabled) flags += 'X';
  5345. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5346. tr.innerHTML = `
  5347. <td class="py-2.5 px-3 text-center">
  5348. <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'}">
  5349. ${flags || '-'}
  5350. </span>
  5351. </td>
  5352. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5353. <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>
  5354. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5355. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5356. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5357. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5358. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5359. ${r.static ? `
  5360. <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>
  5361. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5362. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5363. ` : `
  5364. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5365. `}
  5366. </td>
  5367. `;
  5368. tbody.appendChild(tr);
  5369. });
  5370. }
  5371. function openAddRouteModal() {
  5372. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5373. document.getElementById('route-modal-id').value = '';
  5374. document.getElementById('route-modal-old-dst').value = '';
  5375. document.getElementById('route-modal-old-gw').value = '';
  5376. document.getElementById('route-modal-old-distance').value = '';
  5377. document.getElementById('route-modal-old-table').value = '';
  5378. document.getElementById('route-modal-old-iface').value = '';
  5379. const dstInput = document.getElementById('route-modal-dst');
  5380. const gwInput = document.getElementById('route-modal-gw');
  5381. const distInput = document.getElementById('route-modal-distance');
  5382. const ifaceSelect = document.getElementById('route-modal-iface');
  5383. const tableSelect = document.getElementById('route-modal-table');
  5384. const commentInput = document.getElementById('route-modal-comment');
  5385. const disCheck = document.getElementById('route-modal-disabled');
  5386. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5387. dstInput.disabled = false;
  5388. dstInput.value = '0.0.0.0/0';
  5389. gwInput.disabled = false;
  5390. gwInput.value = '';
  5391. distInput.disabled = false;
  5392. distInput.value = '1';
  5393. ifaceSelect.disabled = false;
  5394. tableSelect.disabled = false;
  5395. commentInput.disabled = false;
  5396. commentInput.value = '';
  5397. disCheck.disabled = false;
  5398. disCheck.checked = false;
  5399. if (saveBtn) saveBtn.classList.remove('hidden');
  5400. populateInterfaceSelect('route-modal-iface');
  5401. // Populate tables
  5402. tableSelect.innerHTML = '';
  5403. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5404. const opt = document.createElement('option');
  5405. opt.value = t.name;
  5406. opt.innerText = t.name;
  5407. if (t.name === 'main') opt.selected = true;
  5408. tableSelect.appendChild(opt);
  5409. });
  5410. document.getElementById('route-modal').classList.remove('hidden');
  5411. }
  5412. function openEditRouteModal(id) {
  5413. const r = (state.routes || []).find(route => route.id === id);
  5414. if (!r) return;
  5415. const isStatic = !!r.static;
  5416. document.getElementById('route-modal-title').innerText = isStatic
  5417. ? `Edit Route: ${r.dst_address}`
  5418. : `Route Properties (Read Only): ${r.dst_address}`;
  5419. document.getElementById('route-modal-id').value = r.id;
  5420. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5421. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5422. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5423. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5424. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5425. const dstInput = document.getElementById('route-modal-dst');
  5426. const gwInput = document.getElementById('route-modal-gw');
  5427. const distInput = document.getElementById('route-modal-distance');
  5428. const ifaceSelect = document.getElementById('route-modal-iface');
  5429. const tableSelect = document.getElementById('route-modal-table');
  5430. const commentInput = document.getElementById('route-modal-comment');
  5431. const disCheck = document.getElementById('route-modal-disabled');
  5432. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5433. dstInput.value = r.dst_address;
  5434. gwInput.value = r.gateway || '';
  5435. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5436. commentInput.value = r.comment || '';
  5437. disCheck.checked = !!r.disabled;
  5438. dstInput.disabled = !isStatic;
  5439. gwInput.disabled = !isStatic;
  5440. distInput.disabled = !isStatic;
  5441. ifaceSelect.disabled = !isStatic;
  5442. tableSelect.disabled = !isStatic;
  5443. commentInput.disabled = !isStatic;
  5444. disCheck.disabled = !isStatic;
  5445. if (saveBtn) {
  5446. if (isStatic) {
  5447. saveBtn.classList.remove('hidden');
  5448. } else {
  5449. saveBtn.classList.add('hidden');
  5450. }
  5451. }
  5452. populateInterfaceSelect('route-modal-iface', r.interface);
  5453. tableSelect.innerHTML = '';
  5454. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5455. const opt = document.createElement('option');
  5456. opt.value = t.name;
  5457. opt.innerText = t.name;
  5458. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5459. tableSelect.appendChild(opt);
  5460. });
  5461. document.getElementById('route-modal').classList.remove('hidden');
  5462. }
  5463. function closeRouteModal() {
  5464. document.getElementById('route-modal').classList.add('hidden');
  5465. }
  5466. async function submitSaveRoute(e) {
  5467. e.preventDefault();
  5468. const id = document.getElementById('route-modal-id').value;
  5469. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5470. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5471. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5472. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5473. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5474. const dst = document.getElementById('route-modal-dst').value.trim();
  5475. const gw = document.getElementById('route-modal-gw').value.trim();
  5476. const table = document.getElementById('route-modal-table').value;
  5477. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5478. const iface = document.getElementById('route-modal-iface').value;
  5479. const comment = document.getElementById('route-modal-comment').value.trim();
  5480. const disabled = document.getElementById('route-modal-disabled').checked;
  5481. if (!dst) {
  5482. showToast('Error', 'Destination address is required', 'error');
  5483. return;
  5484. }
  5485. if (!gw && !iface) {
  5486. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5487. return;
  5488. }
  5489. const payload = {
  5490. id,
  5491. old_dst_address: oldDst,
  5492. old_gateway: oldGw,
  5493. old_routing_table: oldTable,
  5494. old_interface: oldIface,
  5495. dst_address: dst,
  5496. gateway: gw || iface,
  5497. routing_table: table,
  5498. distance,
  5499. interface: iface,
  5500. comment,
  5501. disabled
  5502. };
  5503. if (oldDistStr !== undefined && oldDistStr !== '') {
  5504. payload.old_distance = parseInt(oldDistStr, 10);
  5505. }
  5506. try {
  5507. const res = await fetch(`${API_BASE}/routes`, {
  5508. method: 'POST',
  5509. headers: { 'Content-Type': 'application/json' },
  5510. body: JSON.stringify(payload)
  5511. });
  5512. if (res.ok) {
  5513. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5514. closeRouteModal();
  5515. loadRoutes();
  5516. } else {
  5517. const err = await res.json();
  5518. showToast('Error', err.message || 'Failed to save route', 'error');
  5519. }
  5520. } catch (err) {
  5521. showToast('Error', err.message, 'error');
  5522. }
  5523. }
  5524. async function toggleRouteState(id, disabled) {
  5525. try {
  5526. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5527. method: 'POST',
  5528. headers: { 'Content-Type': 'application/json' },
  5529. body: JSON.stringify({ disabled })
  5530. });
  5531. if (res.ok) loadRoutes();
  5532. } catch (err) {
  5533. showToast('Error', err.message, 'error');
  5534. }
  5535. }
  5536. async function deleteRoute(id) {
  5537. if (!confirm('Are you sure you want to delete this route?')) return;
  5538. try {
  5539. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5540. if (res.ok) {
  5541. showToast('Deleted', 'Route removed', 'success');
  5542. loadRoutes();
  5543. }
  5544. } catch (err) {
  5545. showToast('Error', err.message, 'error');
  5546. }
  5547. }
  5548. // ----------------- Policy Rules (/ip route rule) -----------------
  5549. function renderPolicyRules() {
  5550. const tbody = document.getElementById('rules-table-body');
  5551. const empty = document.getElementById('rules-empty');
  5552. if (!tbody) return;
  5553. tbody.innerHTML = '';
  5554. const showSystem = document.getElementById('prule-show-system')?.checked;
  5555. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5556. const countBadge = document.getElementById('rules-count-badge');
  5557. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5558. const bRules = document.getElementById('routes-badge-rules');
  5559. if (bRules) bRules.innerText = filtered.length;
  5560. if (filtered.length === 0) {
  5561. empty?.classList.remove('hidden');
  5562. return;
  5563. }
  5564. empty?.classList.add('hidden');
  5565. filtered.forEach(pr => {
  5566. const isSys = pr.is_default || pr.is_system;
  5567. const tr = document.createElement('tr');
  5568. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5569. tr.innerHTML = `
  5570. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5571. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5572. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5573. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5574. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5575. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5576. <td class="py-2.5 px-3 text-right font-sans">
  5577. ${!pr.is_default ? `
  5578. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5579. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5580. </td>
  5581. `;
  5582. tbody.appendChild(tr);
  5583. });
  5584. }
  5585. function openAddPolicyRuleModal() {
  5586. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5587. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5588. document.getElementById('prule-modal-mark').value = '';
  5589. document.getElementById('prule-modal-src').value = '';
  5590. document.getElementById('prule-modal-dst').value = '';
  5591. const sel = document.getElementById('prule-modal-table');
  5592. sel.innerHTML = '';
  5593. (state.routingTables || []).forEach(t => {
  5594. const opt = document.createElement('option');
  5595. opt.value = t.name;
  5596. opt.innerText = t.name;
  5597. sel.appendChild(opt);
  5598. });
  5599. document.getElementById('prule-modal').classList.remove('hidden');
  5600. }
  5601. function closePolicyRuleModal() {
  5602. document.getElementById('prule-modal').classList.add('hidden');
  5603. }
  5604. async function submitSavePolicyRule(e) {
  5605. e.preventDefault();
  5606. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5607. const mark = document.getElementById('prule-modal-mark').value.trim();
  5608. const src = document.getElementById('prule-modal-src').value.trim();
  5609. const dst = document.getElementById('prule-modal-dst').value.trim();
  5610. const table = document.getElementById('prule-modal-table').value;
  5611. const action = document.getElementById('prule-modal-action').value;
  5612. try {
  5613. const res = await fetch(`${API_BASE}/routing/rules`, {
  5614. method: 'POST',
  5615. headers: { 'Content-Type': 'application/json' },
  5616. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5617. });
  5618. if (res.ok) {
  5619. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5620. closePolicyRuleModal();
  5621. loadRoutes();
  5622. } else {
  5623. const err = await res.json();
  5624. showToast('Error', err.message, 'error');
  5625. }
  5626. } catch (err) {
  5627. showToast('Error', err.message, 'error');
  5628. }
  5629. }
  5630. async function deletePolicyRule(id) {
  5631. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5632. try {
  5633. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5634. if (res.ok) {
  5635. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5636. loadRoutes();
  5637. }
  5638. } catch (err) {
  5639. showToast('Error', err.message, 'error');
  5640. }
  5641. }
  5642. // ----------------- Routing Tables -----------------
  5643. function renderRoutingTables() {
  5644. const tbody = document.getElementById('tables-table-body');
  5645. if (!tbody) return;
  5646. tbody.innerHTML = '';
  5647. (state.routingTables || []).forEach(t => {
  5648. const tr = document.createElement('tr');
  5649. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5650. tr.innerHTML = `
  5651. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5652. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5653. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5654. `;
  5655. tbody.appendChild(tr);
  5656. });
  5657. }
  5658. function openAddTableModal() {
  5659. document.getElementById('table-modal-name').value = '';
  5660. document.getElementById('table-modal-id').value = '';
  5661. document.getElementById('table-modal-comment').value = '';
  5662. document.getElementById('table-modal').classList.remove('hidden');
  5663. }
  5664. function closeTableModal() {
  5665. document.getElementById('table-modal').classList.add('hidden');
  5666. }
  5667. async function submitSaveTable(e) {
  5668. e.preventDefault();
  5669. const name = document.getElementById('table-modal-name').value.trim();
  5670. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5671. const comment = document.getElementById('table-modal-comment').value.trim();
  5672. try {
  5673. const res = await fetch(`${API_BASE}/routing/tables`, {
  5674. method: 'POST',
  5675. headers: { 'Content-Type': 'application/json' },
  5676. body: JSON.stringify({ name, table_id: id, comment })
  5677. });
  5678. if (res.ok) {
  5679. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5680. closeTableModal();
  5681. loadRoutes();
  5682. } else {
  5683. const err = await res.json();
  5684. showToast('Error', err.message, 'error');
  5685. }
  5686. } catch (err) {
  5687. showToast('Error', err.message, 'error');
  5688. }
  5689. }
  5690. async function loadDebianConfig() {
  5691. const view = document.getElementById('debian-config-view');
  5692. view.innerText = 'Generating live configuration...';
  5693. try {
  5694. const res = await fetch(`${API_BASE}/debian/config`);
  5695. const data = await res.json();
  5696. view.innerText = data.content || '# Empty config';
  5697. } catch (err) {
  5698. view.innerText = 'Failed to generate Debian network config.';
  5699. }
  5700. }
  5701. async function saveDebianConfig() {
  5702. try {
  5703. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5704. const data = await res.json();
  5705. if (res.ok) {
  5706. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5707. loadDebianConfig();
  5708. }
  5709. } catch (err) {
  5710. showToast('Error', err.message, 'error');
  5711. }
  5712. }
  5713. function showToast(title, message, type = 'info') {
  5714. const container = document.getElementById('toast-container');
  5715. const toast = document.createElement('div');
  5716. const borderColors = {
  5717. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5718. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5719. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5720. };
  5721. 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}`;
  5722. toast.innerHTML = `
  5723. <div class="flex-1">
  5724. <div class="font-bold text-xs text-white">${title}</div>
  5725. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5726. </div>
  5727. `;
  5728. container.appendChild(toast);
  5729. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5730. setTimeout(() => {
  5731. toast.classList.add('opacity-0', 'translate-y-2');
  5732. setTimeout(() => toast.remove(), 300);
  5733. }, 4000);
  5734. }
  5735. function formatTraffic(bytesPerSec) {
  5736. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5737. const kb = bytesPerSec / 1024;
  5738. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5739. const mb = kb / 1024;
  5740. return `${mb.toFixed(2)} MB/s`;
  5741. }
  5742. function toggleSidebar() {
  5743. const sb = document.getElementById('sidebar');
  5744. sb.classList.toggle('-translate-x-full');
  5745. }
  5746. // ======================== EoIP (Ethernet over IP) ========================
  5747. async function loadEoIP(populate = true) {
  5748. try {
  5749. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5750. const data = await res.json();
  5751. state.eoipTunnels = Array.isArray(data) ? data : [];
  5752. const badge = document.getElementById('eoip-count-badge');
  5753. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5754. const sideBadge = document.getElementById('badge-eoip-count');
  5755. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5756. renderEoIPTunnels();
  5757. } catch (err) {
  5758. console.error('Failed to load EoIP:', err);
  5759. }
  5760. }
  5761. function renderEoIPTunnels() {
  5762. const tbody = document.getElementById('eoip-table-body');
  5763. const empty = document.getElementById('eoip-empty');
  5764. if (!tbody) return;
  5765. tbody.innerHTML = '';
  5766. const tunnels = state.eoipTunnels || [];
  5767. if (tunnels.length === 0) {
  5768. empty?.classList.remove('hidden');
  5769. return;
  5770. }
  5771. empty?.classList.add('hidden');
  5772. tunnels.forEach(t => {
  5773. const tr = document.createElement('tr');
  5774. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5775. tr.innerHTML = `
  5776. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5777. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5778. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5779. <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>
  5780. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5781. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5782. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5783. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5784. <td class="py-2.5 px-3 font-mono text-[11px]">
  5785. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5786. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5787. </td>
  5788. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5789. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5790. <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>
  5791. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5792. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5793. </td>
  5794. `;
  5795. tbody.appendChild(tr);
  5796. });
  5797. }
  5798. function openAddEoIPModal() {
  5799. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5800. document.getElementById('eoip-modal-id').value = '';
  5801. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5802. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5803. document.getElementById('eoip-modal-remote').value = '';
  5804. document.getElementById('eoip-modal-ip').value = '';
  5805. document.getElementById('eoip-modal-local').value = '';
  5806. document.getElementById('eoip-modal-mac').value = '';
  5807. document.getElementById('eoip-modal-mtu').value = '1500';
  5808. document.getElementById('eoip-modal-comment').value = '';
  5809. document.getElementById('eoip-modal-clampmss').checked = true;
  5810. document.getElementById('eoip-modal-disabled').checked = false;
  5811. document.getElementById('eoip-modal').classList.remove('hidden');
  5812. }
  5813. function openEditEoIPModal(id) {
  5814. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5815. if (!t) return;
  5816. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5817. document.getElementById('eoip-modal-id').value = t.id;
  5818. document.getElementById('eoip-modal-name').value = t.name;
  5819. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5820. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5821. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5822. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5823. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5824. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5825. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5826. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5827. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5828. document.getElementById('eoip-modal').classList.remove('hidden');
  5829. }
  5830. function closeEoIPModal() {
  5831. document.getElementById('eoip-modal').classList.add('hidden');
  5832. }
  5833. async function submitSaveEoIP(e) {
  5834. e.preventDefault();
  5835. const id = document.getElementById('eoip-modal-id').value;
  5836. const name = document.getElementById('eoip-modal-name').value.trim();
  5837. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5838. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5839. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5840. const local = document.getElementById('eoip-modal-local').value.trim();
  5841. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5842. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5843. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5844. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5845. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5846. try {
  5847. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5848. method: 'POST',
  5849. headers: { 'Content-Type': 'application/json' },
  5850. body: JSON.stringify({
  5851. id,
  5852. name,
  5853. tunnel_id: tunnelId,
  5854. remote_address: remote,
  5855. ip_address: ipAddress,
  5856. local_address: local,
  5857. mac_address: mac,
  5858. mtu,
  5859. clamp_mss: clampMss,
  5860. comment,
  5861. disabled
  5862. })
  5863. });
  5864. if (res.ok) {
  5865. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5866. closeEoIPModal();
  5867. loadEoIP(false);
  5868. fetchData(false);
  5869. } else {
  5870. const err = await res.json();
  5871. showToast('Error', err.message, 'error');
  5872. }
  5873. } catch (err) {
  5874. showToast('Error', err.message, 'error');
  5875. }
  5876. }
  5877. async function toggleEoIPState(id, disabled) {
  5878. try {
  5879. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5880. method: 'POST',
  5881. headers: { 'Content-Type': 'application/json' },
  5882. body: JSON.stringify({ disabled })
  5883. });
  5884. if (res.ok) {
  5885. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5886. loadEoIP(false);
  5887. fetchData(false);
  5888. }
  5889. } catch (err) {
  5890. showToast('Error', err.message, 'error');
  5891. }
  5892. }
  5893. async function deleteEoIP(id) {
  5894. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5895. try {
  5896. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5897. if (res.ok) {
  5898. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5899. loadEoIP(false);
  5900. fetchData(false);
  5901. }
  5902. } catch (err) {
  5903. showToast('Error', err.message, 'error');
  5904. }
  5905. }
  5906. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  5907. async function loadAeroTUN(populate = true) {
  5908. try {
  5909. const [tunnelsRes, statsRes] = await Promise.all([
  5910. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  5911. fetch(`${API_BASE}/vpn/aerotun/stats`)
  5912. ]);
  5913. if (tunnelsRes.ok) {
  5914. const data = await tunnelsRes.json();
  5915. state.aerotunTunnels = Array.isArray(data) ? data : [];
  5916. }
  5917. if (statsRes.ok) {
  5918. state.aerotunStats = await statsRes.json();
  5919. }
  5920. const countBadge = document.getElementById('aerotun-count-badge');
  5921. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  5922. const sideBadge = document.getElementById('badge-aerotun-count');
  5923. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  5924. renderAeroTUN();
  5925. } catch (err) {
  5926. console.error('Failed to load AeroTUN:', err);
  5927. }
  5928. }
  5929. function renderAeroTUN() {
  5930. const tbody = document.getElementById('aerotun-table-body');
  5931. const empty = document.getElementById('aerotun-empty');
  5932. // Update summary cards
  5933. const stats = state.aerotunStats || {};
  5934. const tunnels = state.aerotunTunnels || [];
  5935. const statActive = document.getElementById('aerotun-stat-active');
  5936. if (statActive) {
  5937. const activeCount = tunnels.filter(t => t.running).length;
  5938. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  5939. }
  5940. const statSaved = document.getElementById('aerotun-stat-saved');
  5941. if (statSaved) {
  5942. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  5943. }
  5944. const statRatio = document.getElementById('aerotun-stat-ratio');
  5945. if (statRatio) {
  5946. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  5947. }
  5948. const statTraffic = document.getElementById('aerotun-stat-traffic');
  5949. if (statTraffic) {
  5950. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  5951. }
  5952. if (!tbody) return;
  5953. tbody.innerHTML = '';
  5954. if (tunnels.length === 0) {
  5955. empty?.classList.remove('hidden');
  5956. return;
  5957. }
  5958. empty?.classList.add('hidden');
  5959. tunnels.forEach(t => {
  5960. const tr = document.createElement('tr');
  5961. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5962. const modeBadge = t.mode === 'server'
  5963. ? `<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>`
  5964. : `<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>`;
  5965. const endpointInfo = t.mode === 'server'
  5966. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  5967. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  5968. const compBadge = t.compression
  5969. ? `<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>`
  5970. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  5971. const activePeer = t.active_peer_endpoint
  5972. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  5973. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  5974. const rawRx = formatBytes(t.rx_bytes || 0);
  5975. const rawTx = formatBytes(t.tx_bytes || 0);
  5976. const wireRx = formatBytes(t.wire_bytes_in || 0);
  5977. const wireTx = formatBytes(t.wire_bytes_out || 0);
  5978. tr.innerHTML = `
  5979. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5980. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  5981. <span>${escapeHtml(t.name)}</span>
  5982. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  5983. </td>
  5984. <td class="py-2.5 px-3">${modeBadge}</td>
  5985. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  5986. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  5987. <td class="py-2.5 px-3">${compBadge}</td>
  5988. <td class="py-2.5 px-3">${activePeer}</td>
  5989. <td class="py-2.5 px-3 font-mono text-[11px]">
  5990. <span class="text-emerald-400">↓ ${rawRx}</span>
  5991. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  5992. </td>
  5993. <td class="py-2.5 px-3 font-mono text-[11px]">
  5994. <span class="text-slate-400">↓ ${wireRx}</span>
  5995. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  5996. </td>
  5997. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  5998. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5999. ${t.running
  6000. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6001. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6002. }
  6003. <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>
  6004. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6005. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6006. </td>
  6007. `;
  6008. tbody.appendChild(tr);
  6009. });
  6010. }
  6011. function onAeroTUNModeChange() {
  6012. const mode = document.getElementById('aerotun-modal-mode').value;
  6013. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6014. const portInput = document.getElementById('aerotun-modal-port');
  6015. if (mode === 'server') {
  6016. if (!portInput.value) portInput.value = '51830';
  6017. endpointInput.placeholder = 'Optional / learned roaming peer';
  6018. } else {
  6019. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6020. if (!portInput.value) portInput.value = '';
  6021. }
  6022. }
  6023. async function generateAeroTUNKey() {
  6024. try {
  6025. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6026. if (res.ok) {
  6027. const data = await res.json();
  6028. document.getElementById('aerotun-modal-psk').value = data.key;
  6029. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6030. }
  6031. } catch (err) {
  6032. const arr = new Uint8Array(32);
  6033. crypto.getRandomValues(arr);
  6034. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6035. document.getElementById('aerotun-modal-psk').value = hex;
  6036. }
  6037. }
  6038. function openAddAeroTUNModal() {
  6039. const tunnels = state.aerotunTunnels || [];
  6040. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6041. document.getElementById('aerotun-modal-id').value = '';
  6042. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6043. document.getElementById('aerotun-modal-mode').value = 'server';
  6044. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6045. document.getElementById('aerotun-modal-endpoint').value = '';
  6046. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6047. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6048. document.getElementById('aerotun-modal-psk').value = '';
  6049. document.getElementById('aerotun-modal-mtu').value = '1420';
  6050. document.getElementById('aerotun-modal-comment').value = '';
  6051. document.getElementById('aerotun-modal-compression').checked = true;
  6052. document.getElementById('aerotun-modal-defroute').checked = false;
  6053. document.getElementById('aerotun-modal-disabled').checked = false;
  6054. generateAeroTUNKey();
  6055. onAeroTUNModeChange();
  6056. document.getElementById('aerotun-modal').classList.remove('hidden');
  6057. }
  6058. function openEditAeroTUNModal(id) {
  6059. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6060. if (!t) return;
  6061. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6062. document.getElementById('aerotun-modal-id').value = t.id;
  6063. document.getElementById('aerotun-modal-name').value = t.name;
  6064. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6065. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6066. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6067. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6068. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6069. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6070. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6071. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6072. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6073. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6074. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6075. onAeroTUNModeChange();
  6076. document.getElementById('aerotun-modal').classList.remove('hidden');
  6077. }
  6078. function closeAeroTUNModal() {
  6079. document.getElementById('aerotun-modal').classList.add('hidden');
  6080. }
  6081. async function submitSaveAeroTUN(e) {
  6082. e.preventDefault();
  6083. const id = document.getElementById('aerotun-modal-id').value;
  6084. const name = document.getElementById('aerotun-modal-name').value.trim();
  6085. const mode = document.getElementById('aerotun-modal-mode').value;
  6086. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6087. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6088. const local = document.getElementById('aerotun-modal-local').value.trim();
  6089. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6090. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6091. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6092. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6093. const compression = document.getElementById('aerotun-modal-compression').checked;
  6094. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6095. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6096. if (mode === 'client' && !endpoint) {
  6097. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6098. return;
  6099. }
  6100. if (!psk) {
  6101. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6102. return;
  6103. }
  6104. try {
  6105. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6106. method: 'POST',
  6107. headers: { 'Content-Type': 'application/json' },
  6108. body: JSON.stringify({
  6109. id,
  6110. name,
  6111. mode,
  6112. listen_port: port,
  6113. remote_endpoint: endpoint,
  6114. local_address: local,
  6115. peer_address: peer,
  6116. psk,
  6117. mtu,
  6118. compression,
  6119. default_route: defaultRoute,
  6120. comment,
  6121. disabled
  6122. })
  6123. });
  6124. if (res.ok) {
  6125. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6126. closeAeroTUNModal();
  6127. loadAeroTUN(false);
  6128. fetchData(false);
  6129. } else {
  6130. const err = await res.text();
  6131. showToast('Error Saving Tunnel', err, 'error');
  6132. }
  6133. } catch (err) {
  6134. showToast('Network Error', err.message, 'error');
  6135. }
  6136. }
  6137. async function startAeroTUNTunnel(id) {
  6138. try {
  6139. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6140. if (res.ok) {
  6141. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6142. loadAeroTUN(false);
  6143. fetchData(false);
  6144. } else {
  6145. const err = await res.text();
  6146. showToast('Failed to Start', err, 'error');
  6147. }
  6148. } catch (err) {
  6149. showToast('Error', err.message, 'error');
  6150. }
  6151. }
  6152. async function stopAeroTUNTunnel(id) {
  6153. try {
  6154. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6155. if (res.ok) {
  6156. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6157. loadAeroTUN(false);
  6158. fetchData(false);
  6159. } else {
  6160. const err = await res.text();
  6161. showToast('Failed to Stop', err, 'error');
  6162. }
  6163. } catch (err) {
  6164. showToast('Error', err.message, 'error');
  6165. }
  6166. }
  6167. async function toggleAeroTUNState(id, disabled) {
  6168. try {
  6169. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6170. method: 'POST',
  6171. headers: { 'Content-Type': 'application/json' },
  6172. body: JSON.stringify({ disabled })
  6173. });
  6174. if (res.ok) {
  6175. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6176. loadAeroTUN(false);
  6177. fetchData(false);
  6178. }
  6179. } catch (err) {
  6180. showToast('Error', err.message, 'error');
  6181. }
  6182. }
  6183. async function deleteAeroTUN(id) {
  6184. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6185. try {
  6186. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6187. if (res.ok) {
  6188. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6189. loadAeroTUN(false);
  6190. fetchData(false);
  6191. }
  6192. } catch (err) {
  6193. showToast('Error', err.message, 'error');
  6194. }
  6195. }
  6196. // ======================== PPP Central Hub & Servers ========================
  6197. function switchPPPSubTab(tab) {
  6198. state.pppSubTab = tab;
  6199. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6200. tabs.forEach(t => {
  6201. const panel = document.getElementById(`ppp-subtab-${t}`);
  6202. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6203. if (panel) {
  6204. if (t === tab) panel.classList.remove('hidden');
  6205. else panel.classList.add('hidden');
  6206. }
  6207. if (btn) {
  6208. if (t === tab) {
  6209. 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';
  6210. } else {
  6211. 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';
  6212. }
  6213. }
  6214. });
  6215. const addBtn = document.getElementById('ppp-primary-add-btn');
  6216. if (addBtn) {
  6217. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6218. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6219. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6220. else addBtn.innerHTML = '<span>Save Config</span>';
  6221. }
  6222. if (tab === 'active') loadPPPSessions();
  6223. }
  6224. function openCurrentPPPModal() {
  6225. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6226. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6227. else if (state.pppSubTab === 'active') loadPPPSessions();
  6228. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6229. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6230. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6231. }
  6232. async function loadPPP(populateDropdowns = true) {
  6233. await Promise.all([
  6234. loadPPPSecrets(),
  6235. loadPPPProfiles(),
  6236. loadPPPServers(),
  6237. loadPPPSessions()
  6238. ]);
  6239. }
  6240. async function loadPPPSecrets() {
  6241. try {
  6242. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6243. const data = await res.json();
  6244. state.pppSecrets = Array.isArray(data) ? data : [];
  6245. const b = document.getElementById('ppp-badge-secrets');
  6246. if (b) b.innerText = state.pppSecrets.length;
  6247. const b2 = document.getElementById('secrets-count-badge');
  6248. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6249. renderPPPSecrets();
  6250. } catch (err) {
  6251. console.error('Failed to load PPP secrets:', err);
  6252. }
  6253. }
  6254. function renderPPPSecrets() {
  6255. const tbody = document.getElementById('secrets-table-body');
  6256. const empty = document.getElementById('secrets-empty');
  6257. if (!tbody) return;
  6258. tbody.innerHTML = '';
  6259. const secrets = state.pppSecrets || [];
  6260. if (secrets.length === 0) {
  6261. empty?.classList.remove('hidden');
  6262. return;
  6263. }
  6264. empty?.classList.add('hidden');
  6265. secrets.forEach(s => {
  6266. const tr = document.createElement('tr');
  6267. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6268. tr.innerHTML = `
  6269. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6270. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6271. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6272. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6273. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6274. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6275. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6276. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6277. <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>
  6278. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6279. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6280. </td>
  6281. `;
  6282. tbody.appendChild(tr);
  6283. });
  6284. }
  6285. async function loadPPPProfiles() {
  6286. try {
  6287. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6288. const data = await res.json();
  6289. state.pppProfiles = Array.isArray(data) ? data : [];
  6290. const b = document.getElementById('ppp-badge-profiles');
  6291. if (b) b.innerText = state.pppProfiles.length;
  6292. const b2 = document.getElementById('profiles-count-badge');
  6293. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6294. // Populate profile selects across modals
  6295. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6296. selects.forEach(sid => {
  6297. const el = document.getElementById(sid);
  6298. if (!el) return;
  6299. const cur = el.value;
  6300. el.innerHTML = '';
  6301. state.pppProfiles.forEach(p => {
  6302. const opt = document.createElement('option');
  6303. opt.value = p.name;
  6304. opt.innerText = `${p.name} (${p.remote_address})`;
  6305. if (p.name === cur) opt.selected = true;
  6306. el.appendChild(opt);
  6307. });
  6308. });
  6309. renderPPPProfiles();
  6310. } catch (err) {
  6311. console.error('Failed to load PPP profiles:', err);
  6312. }
  6313. }
  6314. function renderPPPProfiles() {
  6315. const tbody = document.getElementById('profiles-table-body');
  6316. if (!tbody) return;
  6317. tbody.innerHTML = '';
  6318. (state.pppProfiles || []).forEach(p => {
  6319. const isDefault = p.name.startsWith('default');
  6320. const tr = document.createElement('tr');
  6321. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6322. tr.innerHTML = `
  6323. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6324. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6325. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6326. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6327. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6328. <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>
  6329. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6330. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6331. ${!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>`}
  6332. </td>
  6333. `;
  6334. tbody.appendChild(tr);
  6335. });
  6336. }
  6337. async function loadPPPServers() {
  6338. try {
  6339. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6340. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6341. fetch(`${API_BASE}/vpn/servers/pptp`),
  6342. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6343. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6344. ]);
  6345. if (pppoeRes.ok) {
  6346. state.pppoeServer = await pppoeRes.json();
  6347. const s = state.pppoeServer;
  6348. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6349. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6350. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6351. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6352. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6353. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6354. const pill = document.getElementById('pppoe-server-status-pill');
  6355. if (pill) {
  6356. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6357. 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';
  6358. }
  6359. setDotBadge('ppp-badge-pppoe-state', s.running);
  6360. }
  6361. if (pptpRes.ok) {
  6362. state.pptpServer = await pptpRes.json();
  6363. const s = state.pptpServer;
  6364. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6365. document.getElementById('pptp-server-port').value = s.port || 1723;
  6366. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6367. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6368. const pill = document.getElementById('pptp-server-status-pill');
  6369. if (pill) {
  6370. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6371. 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';
  6372. }
  6373. setDotBadge('ppp-badge-pptp-state', s.running);
  6374. }
  6375. if (l2tpRes.ok) {
  6376. state.l2tpServer = await l2tpRes.json();
  6377. const s = state.l2tpServer;
  6378. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6379. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6380. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6381. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6382. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6383. const pill = document.getElementById('l2tp-server-status-pill');
  6384. if (pill) {
  6385. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6386. 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';
  6387. }
  6388. setDotBadge('ppp-badge-l2tp-state', s.running);
  6389. }
  6390. if (ipsecRes.ok) {
  6391. state.ipsecServer = await ipsecRes.json();
  6392. const s = state.ipsecServer;
  6393. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6394. if (modalEn) modalEn.checked = !!s.enabled;
  6395. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6396. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6397. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6398. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6399. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6400. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6401. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6402. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6403. const pill = document.getElementById('modal-ipsec-server-status');
  6404. if (pill) {
  6405. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6406. 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';
  6407. }
  6408. }
  6409. } catch (err) {
  6410. console.error('Failed to load VPN servers:', err);
  6411. }
  6412. }
  6413. async function loadPPPSessions() {
  6414. try {
  6415. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6416. const data = await res.json();
  6417. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6418. const b = document.getElementById('ppp-badge-active');
  6419. if (b) b.innerText = state.pppActiveSessions.length;
  6420. const sideB = document.getElementById('badge-ppp-sessions');
  6421. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6422. renderPPPSessions();
  6423. } catch (err) {
  6424. console.error('Failed to load active PPP sessions:', err);
  6425. }
  6426. }
  6427. function renderPPPSessions() {
  6428. const tbody = document.getElementById('active-ppp-table-body');
  6429. const empty = document.getElementById('active-ppp-empty');
  6430. if (!tbody) return;
  6431. tbody.innerHTML = '';
  6432. const list = state.pppActiveSessions || [];
  6433. if (list.length === 0) {
  6434. empty?.classList.remove('hidden');
  6435. return;
  6436. }
  6437. empty?.classList.add('hidden');
  6438. list.forEach(s => {
  6439. const tr = document.createElement('tr');
  6440. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6441. tr.innerHTML = `
  6442. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6443. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6444. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6445. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6446. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6447. <td class="py-2.5 px-3 text-[11px]">
  6448. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6449. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6450. </td>
  6451. <td class="py-2.5 px-3 text-right font-sans">
  6452. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6453. </td>
  6454. `;
  6455. tbody.appendChild(tr);
  6456. });
  6457. }
  6458. async function disconnectPPPSession(iface) {
  6459. if (!confirm(`Disconnect session ${iface}?`)) return;
  6460. try {
  6461. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6462. if (res.ok) {
  6463. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6464. loadPPPSessions();
  6465. }
  6466. } catch (err) {
  6467. showToast('Error', err.message, 'error');
  6468. }
  6469. }
  6470. // PPP Secret Modal handlers
  6471. function openAddPPPSecretModal() {
  6472. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6473. document.getElementById('secret-modal-id').value = '';
  6474. document.getElementById('secret-modal-name').value = '';
  6475. document.getElementById('secret-modal-password').value = '';
  6476. document.getElementById('secret-modal-service').value = 'any';
  6477. document.getElementById('secret-modal-profile').value = 'default';
  6478. document.getElementById('secret-modal-local').value = '';
  6479. document.getElementById('secret-modal-remote').value = '';
  6480. document.getElementById('secret-modal-comment').value = '';
  6481. document.getElementById('secret-modal-disabled').checked = false;
  6482. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6483. }
  6484. function openEditPPPSecretModal(id) {
  6485. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6486. if (!s) return;
  6487. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6488. document.getElementById('secret-modal-id').value = s.id;
  6489. document.getElementById('secret-modal-name').value = s.name;
  6490. document.getElementById('secret-modal-password').value = s.password;
  6491. document.getElementById('secret-modal-service').value = s.service || 'any';
  6492. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6493. document.getElementById('secret-modal-local').value = s.local_address || '';
  6494. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6495. document.getElementById('secret-modal-comment').value = s.comment || '';
  6496. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6497. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6498. }
  6499. function closePPPSecretModal() {
  6500. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6501. }
  6502. async function submitSavePPPSecret(e) {
  6503. e.preventDefault();
  6504. const id = document.getElementById('secret-modal-id').value;
  6505. const name = document.getElementById('secret-modal-name').value.trim();
  6506. const password = document.getElementById('secret-modal-password').value.trim();
  6507. const service = document.getElementById('secret-modal-service').value;
  6508. const profile = document.getElementById('secret-modal-profile').value;
  6509. const local = document.getElementById('secret-modal-local').value.trim();
  6510. const remote = document.getElementById('secret-modal-remote').value.trim();
  6511. const comment = document.getElementById('secret-modal-comment').value.trim();
  6512. const disabled = document.getElementById('secret-modal-disabled').checked;
  6513. try {
  6514. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6515. method: 'POST',
  6516. headers: { 'Content-Type': 'application/json' },
  6517. body: JSON.stringify({
  6518. id,
  6519. name,
  6520. password,
  6521. service,
  6522. profile,
  6523. local_address: local,
  6524. remote_address: remote,
  6525. comment,
  6526. disabled
  6527. })
  6528. });
  6529. if (res.ok) {
  6530. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6531. closePPPSecretModal();
  6532. loadPPPSecrets();
  6533. } else {
  6534. const err = await res.json();
  6535. showToast('Error', err.message, 'error');
  6536. }
  6537. } catch (err) {
  6538. showToast('Error', err.message, 'error');
  6539. }
  6540. }
  6541. async function togglePPPSecretState(id, disabled) {
  6542. try {
  6543. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6544. method: 'POST',
  6545. headers: { 'Content-Type': 'application/json' },
  6546. body: JSON.stringify({ disabled })
  6547. });
  6548. if (res.ok) {
  6549. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6550. loadPPPSecrets();
  6551. }
  6552. } catch (err) {
  6553. showToast('Error', err.message, 'error');
  6554. }
  6555. }
  6556. async function deletePPPSecret(id) {
  6557. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6558. try {
  6559. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6560. if (res.ok) {
  6561. showToast('Deleted', 'Secret account removed', 'success');
  6562. loadPPPSecrets();
  6563. }
  6564. } catch (err) {
  6565. showToast('Error', err.message, 'error');
  6566. }
  6567. }
  6568. // PPP Profile Modal handlers
  6569. function openAddPPPProfileModal() {
  6570. document.getElementById('profile-modal-name').value = '';
  6571. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6572. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6573. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6574. document.getElementById('profile-modal-encryption').value = 'required';
  6575. document.getElementById('profile-modal-onlyone').checked = true;
  6576. document.getElementById('profile-modal-comment').value = '';
  6577. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6578. }
  6579. function closePPPProfileModal() {
  6580. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6581. }
  6582. async function submitSavePPPProfile(e) {
  6583. e.preventDefault();
  6584. const name = document.getElementById('profile-modal-name').value.trim();
  6585. const local = document.getElementById('profile-modal-local').value.trim();
  6586. const remote = document.getElementById('profile-modal-remote').value.trim();
  6587. const dns = document.getElementById('profile-modal-dns').value.trim();
  6588. const enc = document.getElementById('profile-modal-encryption').value;
  6589. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6590. const comment = document.getElementById('profile-modal-comment').value.trim();
  6591. try {
  6592. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6593. method: 'POST',
  6594. headers: { 'Content-Type': 'application/json' },
  6595. body: JSON.stringify({
  6596. id: name,
  6597. name,
  6598. local_address: local,
  6599. remote_address: remote,
  6600. dns_servers: dns,
  6601. use_encryption: enc,
  6602. only_one: onlyone,
  6603. comment
  6604. })
  6605. });
  6606. if (res.ok) {
  6607. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6608. closePPPProfileModal();
  6609. loadPPPProfiles();
  6610. } else {
  6611. const err = await res.json();
  6612. showToast('Error', err.message, 'error');
  6613. }
  6614. } catch (err) {
  6615. showToast('Error', err.message, 'error');
  6616. }
  6617. }
  6618. async function deletePPPProfile(name) {
  6619. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6620. try {
  6621. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6622. if (res.ok) {
  6623. showToast('Deleted', 'Profile removed', 'success');
  6624. loadPPPProfiles();
  6625. } else {
  6626. const err = await res.json();
  6627. showToast('Error', err.message, 'error');
  6628. }
  6629. } catch (err) {
  6630. showToast('Error', err.message, 'error');
  6631. }
  6632. }
  6633. // Server Config submissions
  6634. async function savePPPoEServerConfig(e) {
  6635. e.preventDefault();
  6636. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6637. const name = document.getElementById('pppoe-server-name').value.trim();
  6638. const iface = document.getElementById('pppoe-server-iface').value;
  6639. const profile = document.getElementById('pppoe-server-profile').value;
  6640. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6641. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6642. try {
  6643. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6644. method: 'POST',
  6645. headers: { 'Content-Type': 'application/json' },
  6646. body: JSON.stringify({
  6647. enabled,
  6648. service_name: name,
  6649. interface: iface,
  6650. default_profile: profile,
  6651. max_mtu: mtu,
  6652. max_mru: mtu,
  6653. one_session_per_host: onesession
  6654. })
  6655. });
  6656. if (res.ok) {
  6657. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6658. loadPPPServers();
  6659. fetchData(false);
  6660. } else {
  6661. const err = await res.json();
  6662. showToast('Error', err.message, 'error');
  6663. }
  6664. } catch (err) {
  6665. showToast('Error', err.message, 'error');
  6666. }
  6667. }
  6668. async function savePPTPServerConfig(e) {
  6669. e.preventDefault();
  6670. const enabled = document.getElementById('pptp-server-enabled').checked;
  6671. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6672. const profile = document.getElementById('pptp-server-profile').value;
  6673. const mppe = document.getElementById('pptp-server-mppe').checked;
  6674. try {
  6675. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6676. method: 'POST',
  6677. headers: { 'Content-Type': 'application/json' },
  6678. body: JSON.stringify({
  6679. enabled,
  6680. port,
  6681. default_profile: profile,
  6682. require_mppe: mppe
  6683. })
  6684. });
  6685. if (res.ok) {
  6686. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6687. loadPPPServers();
  6688. fetchData(false);
  6689. } else {
  6690. const err = await res.json();
  6691. showToast('Error', err.message, 'error');
  6692. }
  6693. } catch (err) {
  6694. showToast('Error', err.message, 'error');
  6695. }
  6696. }
  6697. async function saveL2TPServerConfig(e) {
  6698. e.preventDefault();
  6699. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6700. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6701. const profile = document.getElementById('l2tp-server-profile').value;
  6702. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6703. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6704. try {
  6705. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6706. method: 'POST',
  6707. headers: { 'Content-Type': 'application/json' },
  6708. body: JSON.stringify({
  6709. enabled,
  6710. port,
  6711. default_profile: profile,
  6712. use_ipsec: useipsec,
  6713. ipsec_secret: psk
  6714. })
  6715. });
  6716. if (res.ok) {
  6717. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6718. loadPPPServers();
  6719. fetchData(false);
  6720. } else {
  6721. const err = await res.json();
  6722. showToast('Error', err.message, 'error');
  6723. }
  6724. } catch (err) {
  6725. showToast('Error', err.message, 'error');
  6726. }
  6727. }
  6728. // IPSec Server Modal
  6729. function openIPSecServerModal() {
  6730. loadPPPServers();
  6731. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6732. }
  6733. function closeIPSecServerModal() {
  6734. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6735. }
  6736. async function submitSaveIPSecServer(e) {
  6737. e.preventDefault();
  6738. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6739. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6740. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6741. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6742. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6743. try {
  6744. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6745. method: 'POST',
  6746. headers: { 'Content-Type': 'application/json' },
  6747. body: JSON.stringify({
  6748. enabled,
  6749. preshared_key: psk,
  6750. pool_address: pool,
  6751. dns_servers: dns,
  6752. local_subnet: subnet
  6753. })
  6754. });
  6755. if (res.ok) {
  6756. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6757. closeIPSecServerModal();
  6758. loadPPPServers();
  6759. fetchData(false);
  6760. } else {
  6761. const err = await res.json();
  6762. showToast('Error', err.message, 'error');
  6763. }
  6764. } catch (err) {
  6765. showToast('Error', err.message, 'error');
  6766. }
  6767. }
  6768. // WireGuard Client Config Viewer
  6769. let currentWGClientConf = '';
  6770. async function openWGClientConfModal(iface, clientIP) {
  6771. try {
  6772. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6773. method: 'POST',
  6774. headers: { 'Content-Type': 'application/json' },
  6775. body: JSON.stringify({
  6776. interface: iface,
  6777. address: clientIP || '10.10.0.2/32',
  6778. dns: '1.1.1.1, 8.8.8.8'
  6779. })
  6780. });
  6781. if (res.ok) {
  6782. const data = await res.json();
  6783. currentWGClientConf = data.config;
  6784. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6785. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6786. } else {
  6787. const err = await res.json();
  6788. showToast('Error', err.message, 'error');
  6789. }
  6790. } catch (err) {
  6791. showToast('Error', err.message, 'error');
  6792. }
  6793. }
  6794. function closeWGClientConfModal() {
  6795. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6796. }
  6797. function copyWGClientConf() {
  6798. if (!currentWGClientConf) return;
  6799. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6800. }
  6801. function downloadWGClientConf() {
  6802. if (!currentWGClientConf) return;
  6803. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6804. const a = document.createElement('a');
  6805. a.href = URL.createObjectURL(blob);
  6806. a.download = 'wireguard-client.conf';
  6807. document.body.appendChild(a);
  6808. a.click();
  6809. document.body.removeChild(a);
  6810. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6811. }
  6812. // =========================================================================
  6813. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6814. // =========================================================================
  6815. state.activeDynSubTab = 'bgp-peers';
  6816. state.activeBgpSubTab = 'bgp-peers';
  6817. state.activeOspfTab = 'instances';
  6818. state.bgpInstance = null;
  6819. state.bgpPeers = [];
  6820. state.bgpNets = [];
  6821. state.bgpRoutes = [];
  6822. state.ospfInstance = null;
  6823. state.ospfInstances = [];
  6824. state.ospfAreas = [];
  6825. state.ospfAreaRanges = [];
  6826. state.ospfTemplates = [];
  6827. state.ospfLiveInterfaces = [];
  6828. state.ospfStaticNbrs = [];
  6829. state.ospfNeighbors = [];
  6830. state.ospfLSA = [];
  6831. state.ospfRoutes = [];
  6832. state.selectedOspfRow = {
  6833. instances: null,
  6834. areas: null,
  6835. 'area-ranges': null,
  6836. templates: null,
  6837. interfaces: null,
  6838. 'static-nbrs': null,
  6839. neighbors: null,
  6840. lsa: null,
  6841. };
  6842. state.ospfSort = {
  6843. instances: { col: 'name', asc: true },
  6844. areas: { col: 'name', asc: true },
  6845. ranges: { col: 'area', asc: true },
  6846. templates: { col: 'interfaces', asc: true },
  6847. live_ifaces: { col: 'interface', asc: true },
  6848. snbrs: { col: 'address', asc: true },
  6849. neighbors: { col: 'address', asc: true },
  6850. lsa: { col: 'instance', asc: true },
  6851. };
  6852. function switchBgpSubTab(subTab) {
  6853. state.activeBgpSubTab = subTab;
  6854. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6855. tabs.forEach(t => {
  6856. const el = document.getElementById(`dyn-subtab-${t}`);
  6857. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6858. if (el) el.classList.toggle('hidden', t !== subTab);
  6859. if (btn) {
  6860. if (t === subTab) {
  6861. 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';
  6862. } else {
  6863. 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';
  6864. }
  6865. }
  6866. });
  6867. }
  6868. function switchOspfTab(tabName) {
  6869. state.activeOspfTab = tabName;
  6870. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6871. tabs.forEach(t => {
  6872. const pane = document.getElementById(`ospf-pane-${t}`);
  6873. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6874. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6875. if (btn) {
  6876. if (t === tabName) {
  6877. 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';
  6878. } else {
  6879. 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';
  6880. }
  6881. }
  6882. });
  6883. }
  6884. function switchOspfSubTab(tab) {
  6885. // Legacy alias
  6886. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6887. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6888. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6889. else switchOspfTab('instances');
  6890. }
  6891. function switchDynSubTab(subTab) {
  6892. if (subTab.startsWith('bgp')) {
  6893. if (state.activeTab !== 'bgp') navigate('bgp');
  6894. switchBgpSubTab(subTab);
  6895. } else if (subTab.startsWith('ospf')) {
  6896. if (state.activeTab !== 'ospf') navigate('ospf');
  6897. switchOspfTab('instances');
  6898. }
  6899. }
  6900. async function loadDynamicRouting(showToastMsg = false) {
  6901. try {
  6902. const fetchSafeJson = async (url) => {
  6903. try {
  6904. const r = await fetch(url);
  6905. return r.ok ? await r.json() : null;
  6906. } catch (e) {
  6907. return null;
  6908. }
  6909. };
  6910. const [
  6911. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6912. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6913. selectRules, commLists, asLists
  6914. ] = await Promise.all([
  6915. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6916. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6917. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6918. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6919. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6920. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6921. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6922. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6923. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6924. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6925. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6926. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6927. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6928. fetchSafeJson(`${API_BASE}/routing/filters`),
  6929. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6930. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6931. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6932. ]);
  6933. if (sum) state.dynSummary = sum;
  6934. if (bgpInst) state.bgpInstance = bgpInst;
  6935. if (bgpPeers) state.bgpPeers = bgpPeers;
  6936. if (bgpNets) state.bgpNets = bgpNets;
  6937. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6938. if (ospfInsts) state.ospfInstances = ospfInsts;
  6939. if (ospfAreas) state.ospfAreas = ospfAreas;
  6940. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6941. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6942. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6943. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6944. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6945. if (ospfLsa) state.ospfLSA = ospfLsa;
  6946. if (filters) state.routingFilters = filters;
  6947. if (selectRules) state.routingSelectRules = selectRules;
  6948. if (commLists) state.routingCommunityLists = commLists;
  6949. if (asLists) state.routingASLists = asLists;
  6950. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6951. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6952. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6953. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6954. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6955. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6956. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6957. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6958. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6959. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6960. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6961. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6962. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6963. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6964. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6965. } catch (err) {
  6966. console.error('Failed to load dynamic routing:', err);
  6967. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6968. }
  6969. }
  6970. async function loadOspfAll() {
  6971. await loadDynamicRouting(true);
  6972. }
  6973. function renderBgpStatusPill() {
  6974. const pill = document.getElementById('bgp-live-status-pill');
  6975. if (!pill) return;
  6976. const inst = state.bgpInstance;
  6977. if (!inst || !inst.enabled) {
  6978. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  6979. pill.innerText = 'BGP DISABLED';
  6980. } else if (inst.running) {
  6981. 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';
  6982. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  6983. } else {
  6984. 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';
  6985. pill.innerText = 'BGP STARTING...';
  6986. }
  6987. }
  6988. function renderBgpPeers() {
  6989. const tbody = document.getElementById('bgp-peers-table-body');
  6990. if (!tbody) return;
  6991. const empty = document.getElementById('bgp-peers-empty');
  6992. const countBadge = document.getElementById('bgp-peers-count-badge');
  6993. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  6994. const peers = state.bgpPeers || [];
  6995. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  6996. if (navBadge) navBadge.innerText = peers.length;
  6997. if (peers.length === 0) {
  6998. tbody.innerHTML = '';
  6999. if (empty) empty.classList.remove('hidden');
  7000. return;
  7001. }
  7002. if (empty) empty.classList.add('hidden');
  7003. tbody.innerHTML = peers.map(p => {
  7004. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7005. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7006. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7007. let stateBadge = '';
  7008. if (p.disabled) {
  7009. 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>';
  7010. } else if (p.state === 'Established') {
  7011. 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>';
  7012. } else if (p.state === 'Connect' || p.state === 'Active') {
  7013. 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>`;
  7014. } else {
  7015. 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>`;
  7016. }
  7017. return `
  7018. <tr class="hover:bg-slate-800/40 transition">
  7019. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7020. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7021. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7022. <td class="py-2.5 px-3">
  7023. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7024. ${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>`}
  7025. </td>
  7026. <td class="py-2.5 px-3">${stateBadge}</td>
  7027. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7028. <td class="py-2.5 px-3 text-slate-300">
  7029. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7030. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7031. </td>
  7032. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7033. ${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> ` : ''}
  7034. ${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>` : ''}
  7035. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7036. </td>
  7037. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7038. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7039. <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'}">
  7040. ${p.disabled ? 'Enable' : 'Disable'}
  7041. </button>
  7042. <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">
  7043. Edit
  7044. </button>
  7045. <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">
  7046. Delete
  7047. </button>
  7048. </td>
  7049. </tr>
  7050. `;
  7051. }).join('');
  7052. }
  7053. function renderBgpNetworks() {
  7054. const tbody = document.getElementById('bgp-nets-table-body');
  7055. if (!tbody) return;
  7056. const empty = document.getElementById('bgp-nets-empty');
  7057. const countBadge = document.getElementById('bgp-nets-count-badge');
  7058. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7059. const nets = state.bgpNets || [];
  7060. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7061. if (navBadge) navBadge.innerText = nets.length;
  7062. if (nets.length === 0) {
  7063. tbody.innerHTML = '';
  7064. if (empty) empty.classList.remove('hidden');
  7065. return;
  7066. }
  7067. if (empty) empty.classList.add('hidden');
  7068. tbody.innerHTML = nets.map(n => `
  7069. <tr class="hover:bg-slate-800/40 transition">
  7070. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7071. <td class="py-2.5 px-3">
  7072. ${n.disabled
  7073. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7074. : '<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>'}
  7075. </td>
  7076. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7077. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7078. <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">
  7079. Delete
  7080. </button>
  7081. </td>
  7082. </tr>
  7083. `).join('');
  7084. }
  7085. function renderBgpRoutes() {
  7086. const tbody = document.getElementById('bgp-routes-table-body');
  7087. if (!tbody) return;
  7088. const empty = document.getElementById('bgp-routes-empty');
  7089. const countBadge = document.getElementById('bgp-routes-count-badge');
  7090. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7091. const routes = state.bgpRoutes || [];
  7092. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7093. if (navBadge) navBadge.innerText = routes.length;
  7094. if (routes.length === 0) {
  7095. tbody.innerHTML = '';
  7096. if (empty) empty.classList.remove('hidden');
  7097. return;
  7098. }
  7099. if (empty) empty.classList.add('hidden');
  7100. tbody.innerHTML = routes.map(r => `
  7101. <tr class="hover:bg-slate-800/40 transition">
  7102. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7103. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7104. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7105. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7106. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7107. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7108. </tr>
  7109. `).join('');
  7110. }
  7111. // =========================================================================
  7112. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7113. // =========================================================================
  7114. function sortOspfTable(tab, col) {
  7115. if (!state.ospfSort) state.ospfSort = {};
  7116. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7117. if (state.ospfSort[tab].col === col) {
  7118. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7119. } else {
  7120. state.ospfSort[tab].col = col;
  7121. state.ospfSort[tab].asc = true;
  7122. }
  7123. const asc = state.ospfSort[tab].asc;
  7124. let list = [];
  7125. if (tab === 'instances') list = state.ospfInstances || [];
  7126. else if (tab === 'areas') list = state.ospfAreas || [];
  7127. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7128. else if (tab === 'templates') list = state.ospfTemplates || [];
  7129. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7130. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7131. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7132. else if (tab === 'lsa') list = state.ospfLSA || [];
  7133. list.sort((a, b) => {
  7134. let valA = a[col] ?? '';
  7135. let valB = b[col] ?? '';
  7136. if (typeof valA === 'number' && typeof valB === 'number') {
  7137. return asc ? valA - valB : valB - valA;
  7138. }
  7139. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7140. });
  7141. if (tab === 'instances') renderOspfInstances();
  7142. else if (tab === 'areas') renderOspfAreas();
  7143. else if (tab === 'ranges') renderOspfAreaRanges();
  7144. else if (tab === 'templates') renderOspfTemplates();
  7145. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7146. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7147. else if (tab === 'neighbors') renderOspfNeighbors();
  7148. else if (tab === 'lsa') renderOspfLSA();
  7149. }
  7150. function selectOspfRow(tab, id) {
  7151. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7152. state.selectedOspfRow[tab] = id;
  7153. if (tab === 'instances') {
  7154. renderOspfInstances();
  7155. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7156. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7157. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7158. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7159. if (btnEn) btnEn.disabled = false;
  7160. if (btnDis) btnDis.disabled = false;
  7161. if (btnRem) btnRem.disabled = false;
  7162. if (btnCom) btnCom.disabled = false;
  7163. } else if (tab === 'areas') {
  7164. renderOspfAreas();
  7165. const btnEn = document.getElementById('btn-ospf-area-enable');
  7166. const btnDis = document.getElementById('btn-ospf-area-disable');
  7167. const btnRem = document.getElementById('btn-ospf-area-remove');
  7168. const btnCom = document.getElementById('btn-ospf-area-comment');
  7169. if (btnEn) btnEn.disabled = false;
  7170. if (btnDis) btnDis.disabled = false;
  7171. if (btnRem) btnRem.disabled = false;
  7172. if (btnCom) btnCom.disabled = false;
  7173. } else if (tab === 'ranges') {
  7174. renderOspfAreaRanges();
  7175. const btnEn = document.getElementById('btn-ospf-range-enable');
  7176. const btnDis = document.getElementById('btn-ospf-range-disable');
  7177. const btnRem = document.getElementById('btn-ospf-range-remove');
  7178. const btnCom = document.getElementById('btn-ospf-range-comment');
  7179. if (btnEn) btnEn.disabled = false;
  7180. if (btnDis) btnDis.disabled = false;
  7181. if (btnRem) btnRem.disabled = false;
  7182. if (btnCom) btnCom.disabled = false;
  7183. } else if (tab === 'templates') {
  7184. renderOspfTemplates();
  7185. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7186. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7187. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7188. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7189. if (btnEn) btnEn.disabled = false;
  7190. if (btnDis) btnDis.disabled = false;
  7191. if (btnRem) btnRem.disabled = false;
  7192. if (btnCom) btnCom.disabled = false;
  7193. } else if (tab === 'snbrs') {
  7194. renderOspfStaticNbrs();
  7195. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7196. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7197. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7198. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7199. if (btnEn) btnEn.disabled = false;
  7200. if (btnDis) btnDis.disabled = false;
  7201. if (btnRem) btnRem.disabled = false;
  7202. if (btnCom) btnCom.disabled = false;
  7203. }
  7204. }
  7205. // TAB 1: INSTANCES
  7206. function renderOspfInstances() {
  7207. const tbody = document.getElementById('ospf-instances-table-body');
  7208. if (!tbody) return;
  7209. const countEl = document.getElementById('ospf-instances-footer-count');
  7210. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7211. let list = state.ospfInstances || [];
  7212. if (filter) {
  7213. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7214. }
  7215. if (countEl) countEl.innerText = list.length;
  7216. const selId = state.selectedOspfRow?.instances;
  7217. tbody.innerHTML = list.map((inst, idx) => {
  7218. const isSel = inst.id === selId;
  7219. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7220. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7221. return `
  7222. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7223. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7224. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7225. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7226. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7227. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7228. </td>
  7229. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7230. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7231. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7232. </tr>
  7233. `;
  7234. }).join('');
  7235. }
  7236. // TAB 2: AREAS
  7237. function renderOspfAreas() {
  7238. const tbody = document.getElementById('ospf-areas-table-body');
  7239. if (!tbody) return;
  7240. const countEl = document.getElementById('ospf-areas-footer-count');
  7241. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7242. let list = state.ospfAreas || [];
  7243. if (filter) {
  7244. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7245. }
  7246. if (countEl) countEl.innerText = list.length;
  7247. const selId = state.selectedOspfRow?.areas;
  7248. tbody.innerHTML = list.map((a, idx) => {
  7249. const isSel = a.id === selId;
  7250. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7251. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7252. return `
  7253. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7254. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7255. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7256. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7257. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7258. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7259. </td>
  7260. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7261. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7262. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7263. </tr>
  7264. `;
  7265. }).join('');
  7266. }
  7267. // TAB 3: AREA RANGES
  7268. function renderOspfAreaRanges() {
  7269. const tbody = document.getElementById('ospf-ranges-table-body');
  7270. if (!tbody) return;
  7271. const countEl = document.getElementById('ospf-ranges-footer-count');
  7272. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7273. let list = state.ospfAreaRanges || [];
  7274. if (filter) {
  7275. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7276. }
  7277. if (countEl) countEl.innerText = list.length;
  7278. const selId = state.selectedOspfRow?.['area-ranges'];
  7279. tbody.innerHTML = list.map((r, idx) => {
  7280. const isSel = r.id === selId;
  7281. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7282. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7283. return `
  7284. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7285. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7286. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7287. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7288. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7289. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7290. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7291. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7292. </tr>
  7293. `;
  7294. }).join('');
  7295. }
  7296. // TAB 4: INTERFACE TEMPLATES
  7297. function renderOspfTemplates() {
  7298. const tbody = document.getElementById('ospf-templates-table-body');
  7299. if (!tbody) return;
  7300. const countEl = document.getElementById('ospf-templates-footer-count');
  7301. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7302. let list = state.ospfTemplates || [];
  7303. if (filter) {
  7304. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7305. }
  7306. if (countEl) countEl.innerText = list.length;
  7307. const selId = state.selectedOspfRow?.templates;
  7308. tbody.innerHTML = list.map((t, idx) => {
  7309. const isSel = t.id === selId;
  7310. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7311. const ifaces = t.interfaces || t.interface || 'all';
  7312. const nets = t.networks || t.network || '';
  7313. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7314. return `
  7315. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7316. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7317. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7318. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7319. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7320. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7321. </td>
  7322. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7323. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7324. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7325. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7326. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7327. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7328. </tr>
  7329. `;
  7330. }).join('');
  7331. }
  7332. // TAB 5: LIVE INTERFACES
  7333. function renderOspfLiveInterfaces() {
  7334. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7335. if (!tbody) return;
  7336. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7337. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7338. let list = state.ospfLiveInterfaces || [];
  7339. if (filter) {
  7340. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7341. }
  7342. if (countEl) countEl.innerText = list.length;
  7343. tbody.innerHTML = list.map(i => `
  7344. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7345. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7346. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7347. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7348. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7349. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7350. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7351. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7352. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7353. </tr>
  7354. `).join('');
  7355. }
  7356. // TAB 6: STATIC NEIGHBORS
  7357. function renderOspfStaticNbrs() {
  7358. const tbody = document.getElementById('ospf-snbrs-table-body');
  7359. if (!tbody) return;
  7360. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7361. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7362. let list = state.ospfStaticNbrs || [];
  7363. if (filter) {
  7364. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7365. }
  7366. if (countEl) countEl.innerText = list.length;
  7367. const selId = state.selectedOspfRow?.['static-nbrs'];
  7368. tbody.innerHTML = list.map((n, idx) => {
  7369. const isSel = n.id === selId;
  7370. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7371. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7372. return `
  7373. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7374. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7375. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7376. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7377. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7378. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7379. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7380. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7381. </tr>
  7382. `;
  7383. }).join('');
  7384. }
  7385. // TAB 7: LIVE NEIGHBORS
  7386. function renderOspfNeighbors() {
  7387. const tbody = document.getElementById('ospf-neighbors-table-body');
  7388. if (!tbody) return;
  7389. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7390. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7391. let list = state.ospfNeighbors || [];
  7392. if (filter) {
  7393. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7394. }
  7395. if (countEl) countEl.innerText = list.length;
  7396. tbody.innerHTML = list.map(n => `
  7397. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7398. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7399. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7400. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7401. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7402. </td>
  7403. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7404. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7405. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7406. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7407. </tr>
  7408. `).join('');
  7409. }
  7410. // TAB 8: LINK-STATE DATABASE (LSA)
  7411. function renderOspfLSA() {
  7412. const tbody = document.getElementById('ospf-lsa-table-body');
  7413. if (!tbody) return;
  7414. const countEl = document.getElementById('ospf-lsa-footer-count');
  7415. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7416. let list = state.ospfLSA || [];
  7417. if (filter) {
  7418. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7419. }
  7420. if (countEl) countEl.innerText = list.length;
  7421. tbody.innerHTML = list.map(l => `
  7422. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7423. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7424. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7425. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7426. </td>
  7427. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7428. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7429. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7430. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7431. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7432. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7433. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7434. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7435. </tr>
  7436. `).join('');
  7437. }
  7438. function renderOspfStatusPill() {
  7439. // Maintained for backward compatibility
  7440. const pill = document.getElementById('ospf-live-status-pill');
  7441. if (!pill) return;
  7442. 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';
  7443. pill.innerText = 'OSPF ACTIVE';
  7444. }
  7445. function renderOspfInterfaces() {
  7446. renderOspfTemplates();
  7447. }
  7448. function renderOspfRoutes() {
  7449. // Routes retained in background
  7450. }
  7451. // BGP Modals & Actions
  7452. function openBgpInstanceModal() {
  7453. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7454. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7455. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7456. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7457. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7458. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7459. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7460. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7461. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7462. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7463. }
  7464. function closeBgpInstanceModal() {
  7465. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7466. }
  7467. async function submitBgpInstance(e) {
  7468. e.preventDefault();
  7469. const payload = {
  7470. enabled: document.getElementById('modal-bgp-enabled').checked,
  7471. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7472. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7473. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7474. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7475. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7476. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7477. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7478. };
  7479. try {
  7480. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7481. method: 'POST',
  7482. headers: { 'Content-Type': 'application/json' },
  7483. body: JSON.stringify(payload)
  7484. });
  7485. if (res.ok) {
  7486. closeBgpInstanceModal();
  7487. showToast('Success', 'BGP instance configuration updated', 'success');
  7488. loadDynamicRouting();
  7489. } else {
  7490. const err = await res.json();
  7491. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7492. }
  7493. } catch (err) {
  7494. showToast('Error', err.message, 'error');
  7495. }
  7496. }
  7497. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7498. function switchBgpPeerModalTab(tab) {
  7499. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7500. tabs.forEach(t => {
  7501. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7502. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7503. if (t === tab) {
  7504. if (pane) pane.classList.remove('hidden');
  7505. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7506. } else {
  7507. if (pane) pane.classList.add('hidden');
  7508. 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';
  7509. }
  7510. });
  7511. }
  7512. function addOutputNetworkRow(val = '') {
  7513. const container = document.getElementById('modal-bgp-output-networks-container');
  7514. if (!container) return;
  7515. const row = document.createElement('div');
  7516. row.className = 'flex items-center gap-2 output-net-row';
  7517. row.innerHTML = `
  7518. <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">
  7519. <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>
  7520. `;
  7521. container.appendChild(row);
  7522. }
  7523. function parseBgpTime(val) {
  7524. if (!val) return 0;
  7525. val = String(val).trim();
  7526. if (val.includes(':')) {
  7527. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7528. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7529. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7530. }
  7531. return parseInt(val, 10) || 0;
  7532. }
  7533. function formatBgpTime(secs) {
  7534. if (!secs || secs <= 0) return '00:00:00';
  7535. const h = Math.floor(secs / 3600);
  7536. const m = Math.floor((secs % 3600) / 60);
  7537. const s = secs % 60;
  7538. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7539. }
  7540. function populateBgpRoutingTables() {
  7541. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7542. if (!sel) return;
  7543. const cur = sel.value || 'main';
  7544. sel.innerHTML = '<option value="main">main</option>';
  7545. (state.routingTables || []).forEach(t => {
  7546. if (t.name !== 'main') {
  7547. const opt = document.createElement('option');
  7548. opt.value = t.name;
  7549. opt.innerText = t.name;
  7550. sel.appendChild(opt);
  7551. }
  7552. });
  7553. sel.value = cur;
  7554. }
  7555. function openAddBgpPeerModal() {
  7556. document.getElementById('bgp-peer-form').reset();
  7557. document.getElementById('modal-bgp-peer-id').value = '';
  7558. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7559. // General Tab
  7560. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7561. document.getElementById('modal-bgp-peer-comment').value = '';
  7562. document.getElementById('modal-bgp-peer-name').value = '';
  7563. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7564. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7565. document.getElementById('modal-bgp-peer-local-as').value = '';
  7566. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7567. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7568. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7569. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7570. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7571. document.getElementById('modal-bgp-peer-router-id').value = '';
  7572. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7573. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7574. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7575. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7576. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7577. document.getElementById('modal-bgp-peer-local-port').value = '';
  7578. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7579. document.getElementById('modal-bgp-peer-password').value = '';
  7580. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7581. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7582. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7583. document.getElementById('modal-bgp-peer-connect').checked = true;
  7584. document.getElementById('modal-bgp-peer-listen').checked = true;
  7585. // Extra Tab
  7586. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7587. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7588. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7589. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7590. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7591. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7592. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7593. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7594. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7595. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7596. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7597. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7598. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7599. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7600. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7601. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7602. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7603. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7604. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7605. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7606. // Attributes Tab
  7607. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7608. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7609. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7610. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7611. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7612. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7613. // Filter Tab
  7614. populateFilterChainsDatalist();
  7615. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7616. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7617. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7618. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7619. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7620. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7621. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7622. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7623. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7624. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7625. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7626. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7627. populateBgpRoutingTables();
  7628. const container = document.getElementById('modal-bgp-output-networks-container');
  7629. if (container) {
  7630. container.innerHTML = '';
  7631. addOutputNetworkRow('');
  7632. }
  7633. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7634. if (removeBtn) removeBtn.classList.add('hidden');
  7635. switchBgpPeerModalTab('general');
  7636. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7637. }
  7638. function populateFilterChainsDatalist() {
  7639. const dl = document.getElementById('filter-chains-list');
  7640. if (!dl) return;
  7641. const chains = new Set();
  7642. (state.routingFilters || []).forEach(f => {
  7643. if (f.chain) chains.add(f.chain);
  7644. });
  7645. if (chains.size === 0) {
  7646. chains.add('awmn');
  7647. chains.add('bgp-in');
  7648. chains.add('bgp-out');
  7649. }
  7650. dl.innerHTML = '';
  7651. chains.forEach(c => {
  7652. const opt = document.createElement('option');
  7653. opt.value = c;
  7654. dl.appendChild(opt);
  7655. });
  7656. }
  7657. function openEditBgpPeerModal(id) {
  7658. const p = (state.bgpPeers || []).find(item => item.id === id);
  7659. if (!p) return;
  7660. populateBgpRoutingTables();
  7661. populateFilterChainsDatalist();
  7662. document.getElementById('modal-bgp-peer-id').value = p.id;
  7663. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7664. // General Tab
  7665. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7666. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7667. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7668. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7669. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7670. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7671. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7672. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7673. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7674. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7675. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7676. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7677. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7678. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7679. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7680. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7681. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7682. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7683. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7684. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7685. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7686. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7687. // Extra Tab
  7688. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7689. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7690. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7691. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7692. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7693. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7694. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7695. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7696. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7697. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7698. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7699. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7700. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7701. 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;
  7702. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7703. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7704. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7705. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7706. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7707. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7708. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7709. // Attributes Tab
  7710. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7711. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7712. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7713. 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;
  7714. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7715. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7716. // Filter Tab
  7717. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7718. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7719. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7720. 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 || '';
  7721. 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 || '';
  7722. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7723. 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 || '';
  7724. 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 || '';
  7725. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7726. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7727. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7728. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7729. // Output Networks
  7730. const container = document.getElementById('modal-bgp-output-networks-container');
  7731. if (container) {
  7732. container.innerHTML = '';
  7733. if (p.output_networks && p.output_networks.length > 0) {
  7734. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7735. } else {
  7736. addOutputNetworkRow('');
  7737. }
  7738. }
  7739. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7740. if (removeBtn) removeBtn.classList.remove('hidden');
  7741. switchBgpPeerModalTab('general');
  7742. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7743. }
  7744. function copyCurrentBgpPeer() {
  7745. document.getElementById('modal-bgp-peer-id').value = '';
  7746. const nameEl = document.getElementById('modal-bgp-peer-name');
  7747. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7748. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7749. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7750. if (removeBtn) removeBtn.classList.add('hidden');
  7751. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7752. }
  7753. function removeCurrentBgpPeer() {
  7754. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7755. if (!id) return;
  7756. deleteBgpPeer(id);
  7757. closeBgpPeerModal();
  7758. }
  7759. function closeBgpPeerModal() {
  7760. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7761. }
  7762. function getBgpPeerFormData() {
  7763. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7764. const outputNetworks = [];
  7765. netInputs.forEach(inp => {
  7766. const v = inp.value.trim();
  7767. if (v) outputNetworks.push(v);
  7768. });
  7769. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7770. return {
  7771. id: document.getElementById('modal-bgp-peer-id').value,
  7772. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7773. enabled: enabled,
  7774. disabled: !enabled,
  7775. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7776. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7777. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7778. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7779. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7780. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7781. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7782. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7783. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7784. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7785. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7786. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7787. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7788. password: document.getElementById('modal-bgp-peer-password').value,
  7789. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7790. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7791. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7792. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7793. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7794. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7795. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7796. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7797. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7798. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7799. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7800. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7801. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7802. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7803. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7804. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7805. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7806. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7807. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7808. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7809. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7810. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7811. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7812. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7813. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7814. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7815. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7816. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7817. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7818. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7819. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7820. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7821. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7822. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7823. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7824. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7825. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7826. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7827. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7828. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7829. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7830. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7831. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7832. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7833. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7834. output_networks: outputNetworks
  7835. };
  7836. }
  7837. async function submitBgpPeer(e) {
  7838. if (e) e.preventDefault();
  7839. const payload = getBgpPeerFormData();
  7840. try {
  7841. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7842. method: 'POST',
  7843. headers: { 'Content-Type': 'application/json' },
  7844. body: JSON.stringify(payload)
  7845. });
  7846. if (res.ok) {
  7847. closeBgpPeerModal();
  7848. showToast('Success', 'BGP Connection saved', 'success');
  7849. loadDynamicRouting();
  7850. } else {
  7851. const err = await res.json();
  7852. showToast('Error', err.error || 'Failed to save peer', 'error');
  7853. }
  7854. } catch (err) {
  7855. showToast('Error', err.message, 'error');
  7856. }
  7857. }
  7858. async function applyBgpPeerModal(e) {
  7859. if (e) e.preventDefault();
  7860. const payload = getBgpPeerFormData();
  7861. try {
  7862. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7863. method: 'POST',
  7864. headers: { 'Content-Type': 'application/json' },
  7865. body: JSON.stringify(payload)
  7866. });
  7867. if (res.ok) {
  7868. const data = await res.json();
  7869. if (data.peer && data.peer.id) {
  7870. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7871. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7872. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7873. }
  7874. showToast('Applied', 'BGP Connection applied', 'success');
  7875. loadDynamicRouting();
  7876. } else {
  7877. const err = await res.json();
  7878. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7879. }
  7880. } catch (err) {
  7881. showToast('Error', err.message, 'error');
  7882. }
  7883. }
  7884. async function deleteBgpPeer(id) {
  7885. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7886. try {
  7887. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7888. if (res.ok) {
  7889. showToast('Deleted', 'BGP peer removed', 'success');
  7890. loadDynamicRouting();
  7891. }
  7892. } catch (err) {
  7893. showToast('Error', err.message, 'error');
  7894. }
  7895. }
  7896. async function toggleBgpPeerState(id, disabled) {
  7897. try {
  7898. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7899. method: 'POST',
  7900. headers: { 'Content-Type': 'application/json' },
  7901. body: JSON.stringify({ disabled })
  7902. });
  7903. if (res.ok) {
  7904. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7905. loadDynamicRouting();
  7906. }
  7907. } catch (err) {
  7908. showToast('Error', err.message, 'error');
  7909. }
  7910. }
  7911. function openAddBgpNetworkModal() {
  7912. document.getElementById('bgp-network-form').reset();
  7913. document.getElementById('modal-bgp-net-id').value = '';
  7914. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7915. }
  7916. function closeBgpNetworkModal() {
  7917. document.getElementById('bgp-network-modal').classList.add('hidden');
  7918. }
  7919. async function submitBgpNetwork(e) {
  7920. e.preventDefault();
  7921. const payload = {
  7922. id: document.getElementById('modal-bgp-net-id').value,
  7923. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7924. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7925. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7926. };
  7927. try {
  7928. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7929. method: 'POST',
  7930. headers: { 'Content-Type': 'application/json' },
  7931. body: JSON.stringify(payload)
  7932. });
  7933. if (res.ok) {
  7934. closeBgpNetworkModal();
  7935. showToast('Success', 'BGP network advertisement saved', 'success');
  7936. loadDynamicRouting();
  7937. } else {
  7938. const err = await res.json();
  7939. showToast('Error', err.error || 'Failed to save network', 'error');
  7940. }
  7941. } catch (err) {
  7942. showToast('Error', err.message, 'error');
  7943. }
  7944. }
  7945. async function deleteBgpNetwork(id) {
  7946. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7947. try {
  7948. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7949. if (res.ok) {
  7950. showToast('Deleted', 'Network advertisement removed', 'success');
  7951. loadDynamicRouting();
  7952. }
  7953. } catch (err) {
  7954. showToast('Error', err.message, 'error');
  7955. }
  7956. }
  7957. // =========================================================================
  7958. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7959. // =========================================================================
  7960. // --- 1. OSPF INSTANCE ---
  7961. function openOspfInstanceModal(id = null) {
  7962. const isEdit = !!id;
  7963. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7964. id: '',
  7965. name: 'Default',
  7966. version: 2,
  7967. vrf: 'main',
  7968. router_id: '192.168.131.56',
  7969. routing_table: 'main',
  7970. enabled: true,
  7971. redistribute_connected: false,
  7972. redistribute_static: true,
  7973. redistribute_bgp: false,
  7974. comment: ''
  7975. };
  7976. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7977. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7978. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  7979. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  7980. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  7981. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  7982. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  7983. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  7984. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  7985. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  7986. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  7987. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  7988. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  7989. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  7990. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  7991. }
  7992. function openEditOspfInstanceModal(id) {
  7993. openOspfInstanceModal(id);
  7994. }
  7995. function closeOspfInstanceModal() {
  7996. document.getElementById('ospf-instance-modal').classList.add('hidden');
  7997. }
  7998. async function submitOspfInstance(e) {
  7999. if (e) e.preventDefault();
  8000. const payload = {
  8001. id: document.getElementById('modal-ospf-inst-id').value,
  8002. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8003. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8004. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8005. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8006. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8007. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8008. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8009. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8010. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8011. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8012. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8013. };
  8014. try {
  8015. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8016. method: 'POST',
  8017. headers: { 'Content-Type': 'application/json' },
  8018. body: JSON.stringify(payload)
  8019. });
  8020. if (res.ok) {
  8021. closeOspfInstanceModal();
  8022. showToast('Saved', 'OSPF instance updated', 'success');
  8023. loadDynamicRouting();
  8024. } else {
  8025. const err = await res.json();
  8026. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8027. }
  8028. } catch (err) {
  8029. showToast('Error', err.message, 'error');
  8030. }
  8031. }
  8032. function applyOspfInstanceForm() {
  8033. submitOspfInstance(null);
  8034. }
  8035. function copyOspfInstance() {
  8036. document.getElementById('modal-ospf-inst-id').value = '';
  8037. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8038. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8039. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8040. }
  8041. async function deleteCurrentOspfInstance() {
  8042. const id = document.getElementById('modal-ospf-inst-id').value;
  8043. if (!id) return;
  8044. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8045. try {
  8046. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8047. if (res.ok) {
  8048. closeOspfInstanceModal();
  8049. showToast('Removed', 'OSPF instance deleted', 'success');
  8050. loadDynamicRouting();
  8051. }
  8052. } catch (err) {
  8053. showToast('Error', err.message, 'error');
  8054. }
  8055. }
  8056. async function enableSelectedOspfInstance() {
  8057. const id = state.selectedOspfRow?.instances;
  8058. if (!id) return;
  8059. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8060. method: 'POST',
  8061. headers: { 'Content-Type': 'application/json' },
  8062. body: JSON.stringify({ disabled: false })
  8063. });
  8064. loadDynamicRouting();
  8065. }
  8066. async function disableSelectedOspfInstance() {
  8067. const id = state.selectedOspfRow?.instances;
  8068. if (!id) return;
  8069. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8070. method: 'POST',
  8071. headers: { 'Content-Type': 'application/json' },
  8072. body: JSON.stringify({ disabled: true })
  8073. });
  8074. loadDynamicRouting();
  8075. }
  8076. async function removeSelectedOspfInstance() {
  8077. const id = state.selectedOspfRow?.instances;
  8078. if (!id) return;
  8079. if (!confirm('Delete selected OSPF instance?')) return;
  8080. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8081. loadDynamicRouting();
  8082. }
  8083. async function promptCommentOspfInstance() {
  8084. const id = state.selectedOspfRow?.instances;
  8085. if (!id) return;
  8086. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8087. if (!inst) return;
  8088. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8089. if (comment === null) return;
  8090. inst.comment = comment;
  8091. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8092. method: 'POST',
  8093. headers: { 'Content-Type': 'application/json' },
  8094. body: JSON.stringify(inst)
  8095. });
  8096. loadDynamicRouting();
  8097. }
  8098. // --- 2. OSPF AREA ---
  8099. function populateOspfAreaDropdowns() {
  8100. const instSelect = document.getElementById('modal-ospf-area-instance');
  8101. if (instSelect) {
  8102. const cur = instSelect.value;
  8103. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8104. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8105. if (cur) instSelect.value = cur;
  8106. }
  8107. }
  8108. function openOspfAreaModal(id = null) {
  8109. const isEdit = !!id;
  8110. populateOspfAreaDropdowns();
  8111. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8112. id: '',
  8113. name: 'Default',
  8114. instance: 'Default',
  8115. area_id: '0.0.0.0',
  8116. area_type: 'default',
  8117. default_cost: 1,
  8118. no_summaries: false,
  8119. disabled: false,
  8120. comment: ''
  8121. };
  8122. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8123. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8124. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8125. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8126. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8127. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8128. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8129. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8130. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8131. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8132. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8133. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8134. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8135. }
  8136. function openEditOspfAreaModal(id) {
  8137. openOspfAreaModal(id);
  8138. }
  8139. function closeOspfAreaModal() {
  8140. document.getElementById('ospf-area-modal').classList.add('hidden');
  8141. }
  8142. async function submitOspfArea(e) {
  8143. if (e) e.preventDefault();
  8144. const payload = {
  8145. id: document.getElementById('modal-ospf-area-id').value,
  8146. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8147. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8148. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8149. area_type: document.getElementById('modal-ospf-area-type').value,
  8150. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8151. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8152. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8153. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8154. };
  8155. try {
  8156. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8157. method: 'POST',
  8158. headers: { 'Content-Type': 'application/json' },
  8159. body: JSON.stringify(payload)
  8160. });
  8161. if (res.ok) {
  8162. closeOspfAreaModal();
  8163. showToast('Saved', 'OSPF area saved', 'success');
  8164. loadDynamicRouting();
  8165. } else {
  8166. const err = await res.json();
  8167. showToast('Error', err.error || 'Failed to save area', 'error');
  8168. }
  8169. } catch (err) {
  8170. showToast('Error', err.message, 'error');
  8171. }
  8172. }
  8173. function applyOspfAreaForm() {
  8174. submitOspfArea(null);
  8175. }
  8176. function copyOspfArea() {
  8177. document.getElementById('modal-ospf-area-id').value = '';
  8178. document.getElementById('modal-ospf-area-name').value += '-copy';
  8179. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8180. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8181. }
  8182. async function deleteCurrentOspfArea() {
  8183. const id = document.getElementById('modal-ospf-area-id').value;
  8184. if (!id) return;
  8185. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8186. try {
  8187. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8188. if (res.ok) {
  8189. closeOspfAreaModal();
  8190. showToast('Removed', 'OSPF area deleted', 'success');
  8191. loadDynamicRouting();
  8192. }
  8193. } catch (err) {
  8194. showToast('Error', err.message, 'error');
  8195. }
  8196. }
  8197. async function enableSelectedOspfArea() {
  8198. const id = state.selectedOspfRow?.areas;
  8199. if (!id) return;
  8200. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8201. method: 'POST',
  8202. headers: { 'Content-Type': 'application/json' },
  8203. body: JSON.stringify({ disabled: false })
  8204. });
  8205. loadDynamicRouting();
  8206. }
  8207. async function disableSelectedOspfArea() {
  8208. const id = state.selectedOspfRow?.areas;
  8209. if (!id) return;
  8210. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8211. method: 'POST',
  8212. headers: { 'Content-Type': 'application/json' },
  8213. body: JSON.stringify({ disabled: true })
  8214. });
  8215. loadDynamicRouting();
  8216. }
  8217. async function removeSelectedOspfArea() {
  8218. const id = state.selectedOspfRow?.areas;
  8219. if (!id) return;
  8220. if (!confirm('Delete selected OSPF area?')) return;
  8221. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8222. loadDynamicRouting();
  8223. }
  8224. async function promptCommentOspfArea() {
  8225. const id = state.selectedOspfRow?.areas;
  8226. if (!id) return;
  8227. const area = (state.ospfAreas || []).find(a => a.id === id);
  8228. if (!area) return;
  8229. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8230. if (comment === null) return;
  8231. area.comment = comment;
  8232. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8233. method: 'POST',
  8234. headers: { 'Content-Type': 'application/json' },
  8235. body: JSON.stringify(area)
  8236. });
  8237. loadDynamicRouting();
  8238. }
  8239. // --- 3. OSPF AREA RANGE ---
  8240. function populateAreaRangeDropdowns() {
  8241. const select = document.getElementById('modal-ospf-range-area');
  8242. if (select) {
  8243. const cur = select.value;
  8244. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8245. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8246. if (cur) select.value = cur;
  8247. }
  8248. }
  8249. function openOspfAreaRangeModal(id = null) {
  8250. const isEdit = !!id;
  8251. populateAreaRangeDropdowns();
  8252. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8253. id: '',
  8254. area: 'Default',
  8255. prefix: '',
  8256. cost: 1,
  8257. advertise: true,
  8258. disabled: false,
  8259. comment: ''
  8260. };
  8261. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8262. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8263. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8264. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8265. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8266. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8267. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8268. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8269. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8270. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8271. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8272. }
  8273. function openEditOspfAreaRangeModal(id) {
  8274. openOspfAreaRangeModal(id);
  8275. }
  8276. function closeOspfAreaRangeModal() {
  8277. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8278. }
  8279. async function submitOspfAreaRange(e) {
  8280. if (e) e.preventDefault();
  8281. const payload = {
  8282. id: document.getElementById('modal-ospf-range-id').value,
  8283. area: document.getElementById('modal-ospf-range-area').value,
  8284. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8285. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8286. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8287. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8288. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8289. };
  8290. try {
  8291. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8292. method: 'POST',
  8293. headers: { 'Content-Type': 'application/json' },
  8294. body: JSON.stringify(payload)
  8295. });
  8296. if (res.ok) {
  8297. closeOspfAreaRangeModal();
  8298. showToast('Saved', 'Area range saved', 'success');
  8299. loadDynamicRouting();
  8300. } else {
  8301. const err = await res.json();
  8302. showToast('Error', err.error || 'Failed to save area range', 'error');
  8303. }
  8304. } catch (err) {
  8305. showToast('Error', err.message, 'error');
  8306. }
  8307. }
  8308. function applyOspfAreaRangeForm() {
  8309. submitOspfAreaRange(null);
  8310. }
  8311. async function deleteCurrentOspfAreaRange() {
  8312. const id = document.getElementById('modal-ospf-range-id').value;
  8313. if (!id) return;
  8314. if (!confirm('Delete this area range?')) return;
  8315. try {
  8316. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8317. closeOspfAreaRangeModal();
  8318. showToast('Removed', 'Area range removed', 'success');
  8319. loadDynamicRouting();
  8320. } catch (err) {
  8321. showToast('Error', err.message, 'error');
  8322. }
  8323. }
  8324. async function enableSelectedOspfAreaRange() {
  8325. const id = state.selectedOspfRow?.['area-ranges'];
  8326. if (!id) return;
  8327. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8328. if (!r) return;
  8329. r.disabled = false;
  8330. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8331. loadDynamicRouting();
  8332. }
  8333. async function disableSelectedOspfAreaRange() {
  8334. const id = state.selectedOspfRow?.['area-ranges'];
  8335. if (!id) return;
  8336. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8337. if (!r) return;
  8338. r.disabled = true;
  8339. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8340. loadDynamicRouting();
  8341. }
  8342. async function removeSelectedOspfAreaRange() {
  8343. const id = state.selectedOspfRow?.['area-ranges'];
  8344. if (!id) return;
  8345. if (!confirm('Delete selected area range?')) return;
  8346. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8347. loadDynamicRouting();
  8348. }
  8349. async function promptCommentOspfAreaRange() {
  8350. const id = state.selectedOspfRow?.['area-ranges'];
  8351. if (!id) return;
  8352. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8353. if (!r) return;
  8354. const comment = prompt('Enter comment for area range:', r.comment || '');
  8355. if (comment === null) return;
  8356. r.comment = comment;
  8357. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8358. loadDynamicRouting();
  8359. }
  8360. // --- 4. OSPF INTERFACE TEMPLATE ---
  8361. function switchOspfTemplateTab(tab) {
  8362. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8363. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8364. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8365. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8366. if (tab === 'general') {
  8367. if (tabGen) tabGen.classList.remove('hidden');
  8368. if (tabAuth) tabAuth.classList.add('hidden');
  8369. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8370. 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';
  8371. } else {
  8372. if (tabGen) tabGen.classList.add('hidden');
  8373. if (tabAuth) tabAuth.classList.remove('hidden');
  8374. 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';
  8375. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8376. }
  8377. }
  8378. function populateTemplateAreaDropdowns() {
  8379. const select = document.getElementById('modal-ospf-tmpl-area');
  8380. if (select) {
  8381. const cur = select.value;
  8382. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8383. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8384. if (cur) select.value = cur;
  8385. }
  8386. }
  8387. function openOspfTemplateModal(id = null) {
  8388. const isEdit = !!id;
  8389. populateTemplateAreaDropdowns();
  8390. switchOspfTemplateTab('general');
  8391. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8392. id: '',
  8393. interfaces: '',
  8394. area: 'Default',
  8395. networks: '',
  8396. network_type: 'broadcast',
  8397. cost: 1,
  8398. priority: 128,
  8399. passive: false,
  8400. hello_interval: 10,
  8401. dead_interval: 40,
  8402. auth: 'none',
  8403. auth_key: '',
  8404. disabled: false,
  8405. comment: ''
  8406. };
  8407. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8408. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8409. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8410. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8411. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8412. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8413. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8414. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8415. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8416. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8417. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8418. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8419. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8420. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8421. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8422. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8423. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8424. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8425. }
  8426. function openEditOspfTemplateModal(id) {
  8427. openOspfTemplateModal(id);
  8428. }
  8429. function closeOspfTemplateModal() {
  8430. document.getElementById('ospf-template-modal').classList.add('hidden');
  8431. }
  8432. async function submitOspfTemplate(e) {
  8433. if (e) e.preventDefault();
  8434. const payload = {
  8435. id: document.getElementById('modal-ospf-tmpl-id').value,
  8436. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8437. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8438. area: document.getElementById('modal-ospf-tmpl-area').value,
  8439. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8440. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8441. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8442. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8443. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8444. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8445. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8446. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8447. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8448. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8449. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8450. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8451. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8452. };
  8453. try {
  8454. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8455. method: 'POST',
  8456. headers: { 'Content-Type': 'application/json' },
  8457. body: JSON.stringify(payload)
  8458. });
  8459. if (res.ok) {
  8460. closeOspfTemplateModal();
  8461. showToast('Saved', 'Interface template saved', 'success');
  8462. loadDynamicRouting();
  8463. } else {
  8464. const err = await res.json();
  8465. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8466. }
  8467. } catch (err) {
  8468. showToast('Error', err.message, 'error');
  8469. }
  8470. }
  8471. function applyOspfTemplateForm() {
  8472. submitOspfTemplate(null);
  8473. }
  8474. function copyOspfTemplate() {
  8475. document.getElementById('modal-ospf-tmpl-id').value = '';
  8476. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8477. showToast('Copied', 'Duplicated as new template', 'info');
  8478. }
  8479. async function deleteCurrentOspfTemplate() {
  8480. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8481. if (!id) return;
  8482. if (!confirm('Delete this interface template?')) return;
  8483. try {
  8484. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8485. closeOspfTemplateModal();
  8486. showToast('Removed', 'Interface template deleted', 'success');
  8487. loadDynamicRouting();
  8488. } catch (err) {
  8489. showToast('Error', err.message, 'error');
  8490. }
  8491. }
  8492. async function enableSelectedOspfTemplate() {
  8493. const id = state.selectedOspfRow?.templates;
  8494. if (!id) return;
  8495. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8496. method: 'POST',
  8497. headers: { 'Content-Type': 'application/json' },
  8498. body: JSON.stringify({ disabled: false })
  8499. });
  8500. loadDynamicRouting();
  8501. }
  8502. async function disableSelectedOspfTemplate() {
  8503. const id = state.selectedOspfRow?.templates;
  8504. if (!id) return;
  8505. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8506. method: 'POST',
  8507. headers: { 'Content-Type': 'application/json' },
  8508. body: JSON.stringify({ disabled: true })
  8509. });
  8510. loadDynamicRouting();
  8511. }
  8512. async function removeSelectedOspfTemplate() {
  8513. const id = state.selectedOspfRow?.templates;
  8514. if (!id) return;
  8515. if (!confirm('Delete selected interface template?')) return;
  8516. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8517. loadDynamicRouting();
  8518. }
  8519. async function promptCommentOspfTemplate() {
  8520. const id = state.selectedOspfRow?.templates;
  8521. if (!id) return;
  8522. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8523. if (!tmpl) return;
  8524. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8525. if (comment === null) return;
  8526. tmpl.comment = comment;
  8527. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8528. method: 'POST',
  8529. headers: { 'Content-Type': 'application/json' },
  8530. body: JSON.stringify(tmpl)
  8531. });
  8532. loadDynamicRouting();
  8533. }
  8534. // --- 5. OSPF STATIC NEIGHBOR ---
  8535. function populateStaticNbrAreaDropdowns() {
  8536. const select = document.getElementById('modal-ospf-snbr-area');
  8537. if (select) {
  8538. const cur = select.value;
  8539. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8540. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8541. if (cur) select.value = cur;
  8542. }
  8543. }
  8544. function openOspfStaticNbrModal(id = null) {
  8545. const isEdit = !!id;
  8546. populateStaticNbrAreaDropdowns();
  8547. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8548. id: '',
  8549. address: '',
  8550. area: 'Default',
  8551. poll_interval: 120,
  8552. cost: 1,
  8553. disabled: false,
  8554. comment: ''
  8555. };
  8556. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8557. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8558. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8559. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8560. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8561. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8562. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8563. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8564. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8565. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8566. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8567. }
  8568. function openEditOspfStaticNbrModal(id) {
  8569. openOspfStaticNbrModal(id);
  8570. }
  8571. function closeOspfStaticNbrModal() {
  8572. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8573. }
  8574. async function submitOspfStaticNbr(e) {
  8575. if (e) e.preventDefault();
  8576. const payload = {
  8577. id: document.getElementById('modal-ospf-snbr-id').value,
  8578. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8579. area: document.getElementById('modal-ospf-snbr-area').value,
  8580. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8581. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8582. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8583. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8584. };
  8585. try {
  8586. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8587. method: 'POST',
  8588. headers: { 'Content-Type': 'application/json' },
  8589. body: JSON.stringify(payload)
  8590. });
  8591. if (res.ok) {
  8592. closeOspfStaticNbrModal();
  8593. showToast('Saved', 'Static neighbor saved', 'success');
  8594. loadDynamicRouting();
  8595. } else {
  8596. const err = await res.json();
  8597. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8598. }
  8599. } catch (err) {
  8600. showToast('Error', err.message, 'error');
  8601. }
  8602. }
  8603. function applyOspfStaticNbrForm() {
  8604. submitOspfStaticNbr(null);
  8605. }
  8606. async function deleteCurrentOspfStaticNbr() {
  8607. const id = document.getElementById('modal-ospf-snbr-id').value;
  8608. if (!id) return;
  8609. if (!confirm('Delete this static neighbor?')) return;
  8610. try {
  8611. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8612. closeOspfStaticNbrModal();
  8613. showToast('Removed', 'Static neighbor removed', 'success');
  8614. loadDynamicRouting();
  8615. } catch (err) {
  8616. showToast('Error', err.message, 'error');
  8617. }
  8618. }
  8619. async function enableSelectedOspfStaticNbr() {
  8620. const id = state.selectedOspfRow?.['static-nbrs'];
  8621. if (!id) return;
  8622. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8623. if (!n) return;
  8624. n.disabled = false;
  8625. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8626. loadDynamicRouting();
  8627. }
  8628. async function disableSelectedOspfStaticNbr() {
  8629. const id = state.selectedOspfRow?.['static-nbrs'];
  8630. if (!id) return;
  8631. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8632. if (!n) return;
  8633. n.disabled = true;
  8634. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8635. loadDynamicRouting();
  8636. }
  8637. async function removeSelectedOspfStaticNbr() {
  8638. const id = state.selectedOspfRow?.['static-nbrs'];
  8639. if (!id) return;
  8640. if (!confirm('Delete selected static neighbor?')) return;
  8641. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8642. loadDynamicRouting();
  8643. }
  8644. async function promptCommentOspfStaticNbr() {
  8645. const id = state.selectedOspfRow?.['static-nbrs'];
  8646. if (!id) return;
  8647. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8648. if (!n) return;
  8649. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8650. if (comment === null) return;
  8651. n.comment = comment;
  8652. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8653. loadDynamicRouting();
  8654. }
  8655. // Backward-compat aliases
  8656. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8657. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8658. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8659. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8660. function deleteOspfInterface(id) {
  8661. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8662. }
  8663. function toggleOspfInterfaceState(id, disabled) {
  8664. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8665. method: 'POST',
  8666. headers: { 'Content-Type': 'application/json' },
  8667. body: JSON.stringify({ disabled })
  8668. }).then(() => loadDynamicRouting());
  8669. }
  8670. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8671. function deleteOspfArea(id) {
  8672. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8673. }
  8674. // ============================================================================
  8675. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8676. // ============================================================================
  8677. function switchBridgeSubTab(tab) {
  8678. state.bridgeSubTab = tab;
  8679. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8680. tabs.forEach(t => {
  8681. const panel = document.getElementById(`bridge-subtab-${t}`);
  8682. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8683. if (panel) {
  8684. if (t === tab) panel.classList.remove('hidden');
  8685. else panel.classList.add('hidden');
  8686. }
  8687. if (btn) {
  8688. if (t === tab) {
  8689. 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';
  8690. } else {
  8691. 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';
  8692. }
  8693. }
  8694. });
  8695. const addBtn = document.getElementById('bridge-top-action-btn');
  8696. if (addBtn) {
  8697. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8698. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8699. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8700. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8701. }
  8702. if (tab === 'hosts') loadBridgeHosts();
  8703. setTimeout(initTableSorting, 50);
  8704. }
  8705. function openCurrentBridgeModal() {
  8706. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8707. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8708. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8709. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8710. }
  8711. async function loadBridge() {
  8712. try {
  8713. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8714. fetch(`${API_BASE}/bridge/bridges`),
  8715. fetch(`${API_BASE}/bridge/ports`),
  8716. fetch(`${API_BASE}/bridge/vlans`),
  8717. fetch(`${API_BASE}/bridge/summary`),
  8718. fetch(`${API_BASE}/vpn/eoip`),
  8719. fetch(`${API_BASE}/vlans`)
  8720. ]);
  8721. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8722. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8723. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8724. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8725. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8726. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8727. // Badges & Stats
  8728. const bBridges = document.getElementById('bridge-badge-bridges');
  8729. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8730. const bPorts = document.getElementById('bridge-badge-ports');
  8731. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8732. const bVlans = document.getElementById('bridge-badge-vlans');
  8733. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8734. const bHosts = document.getElementById('bridge-badge-hosts');
  8735. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8736. const sBr = document.getElementById('bridge-stat-bridges');
  8737. if (sBr) sBr.innerText = (state.bridges || []).length;
  8738. const sPorts = document.getElementById('bridge-stat-ports');
  8739. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8740. const sHosts = document.getElementById('bridge-stat-hosts');
  8741. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8742. renderBridges();
  8743. renderBridgePorts();
  8744. renderBridgeVLANs();
  8745. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8746. } catch (err) {
  8747. console.error('Failed to load bridge subsystem:', err);
  8748. }
  8749. }
  8750. // ----------------- Bridges -----------------
  8751. function renderBridges() {
  8752. const tbody = document.getElementById('bridge-table-body');
  8753. const empty = document.getElementById('bridge-empty-bridges');
  8754. const countBadge = document.getElementById('bridge-count-badge');
  8755. if (!tbody) return;
  8756. tbody.innerHTML = '';
  8757. const bridges = state.bridges || [];
  8758. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8759. if (bridges.length === 0) {
  8760. empty?.classList.remove('hidden');
  8761. return;
  8762. }
  8763. empty?.classList.add('hidden');
  8764. bridges.forEach((b, idx) => {
  8765. const tr = document.createElement('tr');
  8766. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8767. // Format IP addresses pill list
  8768. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8769. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8770. ipsHtml = b.ip_addresses.map(ip => `
  8771. <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">
  8772. <span>${ip}</span>
  8773. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8774. </span>
  8775. `).join(' ');
  8776. }
  8777. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8778. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8779. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8780. tr.innerHTML = `
  8781. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8782. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8783. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8784. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8785. </td>
  8786. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8787. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8788. <td class="py-2.5 px-3">
  8789. <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>
  8790. </td>
  8791. <td class="py-2.5 px-3 text-center">
  8792. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8793. </td>
  8794. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8795. <td class="py-2.5 px-3">
  8796. <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>
  8797. </td>
  8798. <td class="py-2.5 px-3">
  8799. <div class="flex items-center gap-1.5 flex-wrap">
  8800. ${ipsHtml}
  8801. <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>
  8802. </div>
  8803. </td>
  8804. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8805. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8806. </td>
  8807. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8808. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8809. <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>
  8810. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8811. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8812. </td>
  8813. `;
  8814. tbody.appendChild(tr);
  8815. });
  8816. }
  8817. function openAddBridgeModal() {
  8818. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8819. document.getElementById('bridge-modal-id').value = '';
  8820. document.getElementById('bridge-modal-name').value = 'bridge1';
  8821. document.getElementById('bridge-modal-name').disabled = false;
  8822. document.getElementById('bridge-modal-mtu').value = '1500';
  8823. document.getElementById('bridge-modal-mac').value = '';
  8824. document.getElementById('bridge-modal-stp').value = 'rstp';
  8825. document.getElementById('bridge-modal-priority').value = '32768';
  8826. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8827. document.getElementById('bridge-modal-pvid').value = '1';
  8828. document.getElementById('bridge-modal-fastforward').checked = true;
  8829. document.getElementById('bridge-modal-comment').value = '';
  8830. document.getElementById('bridge-modal-disabled').checked = false;
  8831. toggleBridgeModalVlanFiltering();
  8832. document.getElementById('bridge-modal').classList.remove('hidden');
  8833. }
  8834. function openEditBridgeModal(id) {
  8835. const b = (state.bridges || []).find(x => x.id === id);
  8836. if (!b) return;
  8837. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8838. document.getElementById('bridge-modal-id').value = b.id;
  8839. document.getElementById('bridge-modal-name').value = b.name;
  8840. document.getElementById('bridge-modal-name').disabled = true;
  8841. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8842. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8843. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8844. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8845. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8846. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8847. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8848. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8849. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8850. toggleBridgeModalVlanFiltering();
  8851. document.getElementById('bridge-modal').classList.remove('hidden');
  8852. }
  8853. function closeBridgeModal() {
  8854. document.getElementById('bridge-modal').classList.add('hidden');
  8855. }
  8856. function toggleBridgeModalVlanFiltering() {
  8857. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8858. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8859. if (pvidBox) {
  8860. if (chk) pvidBox.classList.remove('opacity-40');
  8861. else pvidBox.classList.add('opacity-40');
  8862. }
  8863. }
  8864. async function submitSaveBridge(e) {
  8865. e.preventDefault();
  8866. const id = document.getElementById('bridge-modal-id').value;
  8867. const name = document.getElementById('bridge-modal-name').value.trim();
  8868. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8869. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8870. const stp = document.getElementById('bridge-modal-stp').value;
  8871. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8872. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8873. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8874. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8875. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8876. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8877. try {
  8878. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8879. method: 'POST',
  8880. headers: { 'Content-Type': 'application/json' },
  8881. body: JSON.stringify({
  8882. id,
  8883. name,
  8884. mtu,
  8885. mac_address: mac,
  8886. stp,
  8887. priority,
  8888. vlan_filtering: vlanFiltering,
  8889. pvid,
  8890. fast_forward: fastForward,
  8891. comment,
  8892. disabled
  8893. })
  8894. });
  8895. if (res.ok) {
  8896. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8897. closeBridgeModal();
  8898. loadBridge();
  8899. fetchData(false);
  8900. } else {
  8901. const err = await res.json();
  8902. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8903. }
  8904. } catch (err) {
  8905. showToast('Error', err.message, 'error');
  8906. }
  8907. }
  8908. async function toggleBridgeState(id, disabled) {
  8909. try {
  8910. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8911. method: 'POST',
  8912. headers: { 'Content-Type': 'application/json' },
  8913. body: JSON.stringify({ disabled })
  8914. });
  8915. if (res.ok) {
  8916. loadBridge();
  8917. fetchData(false);
  8918. }
  8919. } catch (err) {
  8920. showToast('Error', err.message, 'error');
  8921. }
  8922. }
  8923. async function deleteBridge(id) {
  8924. const b = (state.bridges || []).find(x => x.id === id);
  8925. const name = b ? b.name : id;
  8926. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8927. try {
  8928. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8929. if (res.ok) {
  8930. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8931. loadBridge();
  8932. fetchData(false);
  8933. } else {
  8934. const err = await res.json();
  8935. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8936. }
  8937. } catch (err) {
  8938. showToast('Error', err.message, 'error');
  8939. }
  8940. }
  8941. // ----------------- Bridge IP Assignments -----------------
  8942. function openAddBridgeIPModal(id, name) {
  8943. document.getElementById('bridge-ip-modal-id').value = id;
  8944. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8945. document.getElementById('bridge-ip-modal-cidr').value = '';
  8946. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8947. }
  8948. function closeBridgeIPModal() {
  8949. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8950. }
  8951. async function submitAddBridgeIP(e) {
  8952. e.preventDefault();
  8953. const id = document.getElementById('bridge-ip-modal-id').value;
  8954. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8955. try {
  8956. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8957. method: 'POST',
  8958. headers: { 'Content-Type': 'application/json' },
  8959. body: JSON.stringify({ ip })
  8960. });
  8961. if (res.ok) {
  8962. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8963. closeBridgeIPModal();
  8964. loadBridge();
  8965. fetchData(false);
  8966. } else {
  8967. const err = await res.json();
  8968. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8969. }
  8970. } catch (err) {
  8971. showToast('Error', err.message, 'error');
  8972. }
  8973. }
  8974. async function deleteBridgeIP(id, ip) {
  8975. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8976. try {
  8977. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8978. method: 'DELETE',
  8979. headers: { 'Content-Type': 'application/json' },
  8980. body: JSON.stringify({ ip })
  8981. });
  8982. if (res.ok) {
  8983. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  8984. loadBridge();
  8985. fetchData(false);
  8986. }
  8987. } catch (err) {
  8988. showToast('Error', err.message, 'error');
  8989. }
  8990. }
  8991. // ----------------- Bridge Ports -----------------
  8992. function renderBridgePorts() {
  8993. const tbody = document.getElementById('bridge-ports-table-body');
  8994. const empty = document.getElementById('bridge-empty-ports');
  8995. const countBadge = document.getElementById('bridge-ports-count-badge');
  8996. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  8997. if (!tbody) return;
  8998. tbody.innerHTML = '';
  8999. // Update filter select
  9000. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9001. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9002. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9003. if (ports.length === 0) {
  9004. empty?.classList.remove('hidden');
  9005. return;
  9006. }
  9007. empty?.classList.add('hidden');
  9008. ports.forEach((p, idx) => {
  9009. const tr = document.createElement('tr');
  9010. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9011. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9012. tr.innerHTML = `
  9013. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9014. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9015. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9016. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9017. </td>
  9018. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9019. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9020. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9021. <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>
  9022. <td class="py-2.5 px-3">
  9023. ${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>'}
  9024. </td>
  9025. <td class="py-2.5 px-3">
  9026. <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>
  9027. </td>
  9028. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9029. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9030. <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>
  9031. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9032. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9033. </td>
  9034. `;
  9035. tbody.appendChild(tr);
  9036. });
  9037. }
  9038. function openAddBridgePortModal() {
  9039. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9040. document.getElementById('bridge-port-modal-id').value = '';
  9041. populateBridgeSelect('bridge-port-modal-bridge');
  9042. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9043. document.getElementById('bridge-port-modal-pvid').value = '1';
  9044. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9045. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9046. document.getElementById('bridge-port-modal-horizon').value = '0';
  9047. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9048. document.getElementById('bridge-port-modal-priority').value = '128';
  9049. document.getElementById('bridge-port-modal-learn').checked = true;
  9050. document.getElementById('bridge-port-modal-comment').value = '';
  9051. document.getElementById('bridge-port-modal-disabled').checked = false;
  9052. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9053. }
  9054. function openEditBridgePortModal(id) {
  9055. const p = (state.bridgePorts || []).find(x => x.id === id);
  9056. if (!p) return;
  9057. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9058. document.getElementById('bridge-port-modal-id').value = p.id;
  9059. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9060. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9061. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9062. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9063. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9064. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9065. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9066. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9067. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9068. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9069. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9070. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9071. }
  9072. function closeBridgePortModal() {
  9073. document.getElementById('bridge-port-modal').classList.add('hidden');
  9074. }
  9075. async function submitSaveBridgePort(e) {
  9076. e.preventDefault();
  9077. const id = document.getElementById('bridge-port-modal-id').value;
  9078. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9079. const iface = document.getElementById('bridge-port-modal-interface').value;
  9080. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9081. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9082. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9083. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9084. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9085. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9086. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9087. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9088. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9089. try {
  9090. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9091. method: 'POST',
  9092. headers: { 'Content-Type': 'application/json' },
  9093. body: JSON.stringify({
  9094. id,
  9095. bridge,
  9096. interface: iface,
  9097. pvid,
  9098. frame_types: frameTypes,
  9099. ingress_filtering: ingressFiltering,
  9100. horizon,
  9101. path_cost: pathCost,
  9102. priority,
  9103. learn,
  9104. comment,
  9105. disabled
  9106. })
  9107. });
  9108. if (res.ok) {
  9109. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9110. closeBridgePortModal();
  9111. loadBridge();
  9112. fetchData(false);
  9113. } else {
  9114. const err = await res.json();
  9115. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9116. }
  9117. } catch (err) {
  9118. showToast('Error', err.message, 'error');
  9119. }
  9120. }
  9121. async function toggleBridgePortState(id, disabled) {
  9122. try {
  9123. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9124. method: 'POST',
  9125. headers: { 'Content-Type': 'application/json' },
  9126. body: JSON.stringify({ disabled })
  9127. });
  9128. if (res.ok) {
  9129. loadBridge();
  9130. fetchData(false);
  9131. }
  9132. } catch (err) {
  9133. showToast('Error', err.message, 'error');
  9134. }
  9135. }
  9136. async function deleteBridgePort(id) {
  9137. const p = (state.bridgePorts || []).find(x => x.id === id);
  9138. const iface = p ? p.interface : id;
  9139. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9140. try {
  9141. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9142. if (res.ok) {
  9143. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9144. loadBridge();
  9145. fetchData(false);
  9146. }
  9147. } catch (err) {
  9148. showToast('Error', err.message, 'error');
  9149. }
  9150. }
  9151. // ----------------- Bridge VLANs -----------------
  9152. function renderBridgeVLANs() {
  9153. const tbody = document.getElementById('bridge-vlans-table-body');
  9154. const empty = document.getElementById('bridge-empty-vlans');
  9155. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9156. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9157. if (!tbody) return;
  9158. tbody.innerHTML = '';
  9159. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9160. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9161. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9162. if (vlans.length === 0) {
  9163. empty?.classList.remove('hidden');
  9164. return;
  9165. }
  9166. empty?.classList.add('hidden');
  9167. vlans.forEach((v, idx) => {
  9168. const tr = document.createElement('tr');
  9169. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9170. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9171. ? 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(' ')
  9172. : '<span class="text-slate-600">none</span>';
  9173. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9174. ? 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(' ')
  9175. : '<span class="text-slate-600">none</span>';
  9176. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9177. tr.innerHTML = `
  9178. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9179. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9180. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9181. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9182. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9183. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9184. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9185. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9186. <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>
  9187. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9188. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9189. </td>
  9190. `;
  9191. tbody.appendChild(tr);
  9192. });
  9193. }
  9194. function openAddBridgeVLANModal() {
  9195. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9196. document.getElementById('bridge-vlan-modal-id').value = '';
  9197. populateBridgeSelect('bridge-vlan-modal-bridge');
  9198. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9199. document.getElementById('bridge-vlan-modal-comment').value = '';
  9200. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9201. updateBridgeVlanPortCheckboxes();
  9202. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9203. }
  9204. function openEditBridgeVLANModal(id) {
  9205. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9206. if (!v) return;
  9207. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9208. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9209. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9210. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9211. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9212. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9213. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9214. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9215. }
  9216. function closeBridgeVlanModal() {
  9217. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9218. }
  9219. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9220. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9221. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9222. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9223. if (!taggedBox || !untaggedBox) return;
  9224. // Ports belonging to the selected bridge
  9225. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9226. if (memberPorts.length === 0) {
  9227. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9228. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9229. return;
  9230. }
  9231. taggedBox.innerHTML = memberPorts.map(p => `
  9232. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9233. <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">
  9234. <span>${p.interface}</span>
  9235. </label>
  9236. `).join('');
  9237. untaggedBox.innerHTML = memberPorts.map(p => `
  9238. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9239. <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">
  9240. <span>${p.interface}</span>
  9241. </label>
  9242. `).join('');
  9243. }
  9244. async function submitSaveBridgeVLAN(e) {
  9245. e.preventDefault();
  9246. const id = document.getElementById('bridge-vlan-modal-id').value;
  9247. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9248. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9249. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9250. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9251. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9252. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9253. try {
  9254. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9255. method: 'POST',
  9256. headers: { 'Content-Type': 'application/json' },
  9257. body: JSON.stringify({
  9258. id,
  9259. bridge,
  9260. vlan_ids: vlanIDs,
  9261. tagged,
  9262. untagged,
  9263. comment,
  9264. disabled
  9265. })
  9266. });
  9267. if (res.ok) {
  9268. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9269. closeBridgeVlanModal();
  9270. loadBridge();
  9271. } else {
  9272. const err = await res.json();
  9273. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9274. }
  9275. } catch (err) {
  9276. showToast('Error', err.message, 'error');
  9277. }
  9278. }
  9279. async function toggleBridgeVLANState(id, disabled) {
  9280. try {
  9281. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9282. method: 'POST',
  9283. headers: { 'Content-Type': 'application/json' },
  9284. body: JSON.stringify({ disabled })
  9285. });
  9286. if (res.ok) loadBridge();
  9287. } catch (err) {
  9288. showToast('Error', err.message, 'error');
  9289. }
  9290. }
  9291. async function deleteBridgeVLAN(id) {
  9292. if (!confirm('Delete this bridge VLAN entry?')) return;
  9293. try {
  9294. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9295. if (res.ok) {
  9296. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9297. loadBridge();
  9298. }
  9299. } catch (err) {
  9300. showToast('Error', err.message, 'error');
  9301. }
  9302. }
  9303. // ----------------- Hosts / MAC Table -----------------
  9304. async function loadBridgeHosts() {
  9305. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9306. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9307. try {
  9308. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9309. const res = await fetch(url);
  9310. if (res.ok) {
  9311. state.bridgeHosts = await res.json();
  9312. renderBridgeHosts();
  9313. }
  9314. } catch (err) {
  9315. console.error('Failed to load bridge hosts:', err);
  9316. }
  9317. }
  9318. function renderBridgeHosts() {
  9319. const tbody = document.getElementById('bridge-hosts-table-body');
  9320. const empty = document.getElementById('bridge-empty-hosts');
  9321. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9322. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9323. if (!tbody) return;
  9324. tbody.innerHTML = '';
  9325. const hosts = (state.bridgeHosts || []).filter(h => {
  9326. if (!search) return true;
  9327. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9328. });
  9329. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9330. if (hosts.length === 0) {
  9331. empty?.classList.remove('hidden');
  9332. return;
  9333. }
  9334. empty?.classList.add('hidden');
  9335. hosts.forEach(h => {
  9336. const tr = document.createElement('tr');
  9337. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9338. let flagBadges = '';
  9339. 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>';
  9340. 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>';
  9341. 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>';
  9342. tr.innerHTML = `
  9343. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9344. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9345. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9346. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9347. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9348. <td class="py-2.5 px-3">${flagBadges}</td>
  9349. `;
  9350. tbody.appendChild(tr);
  9351. });
  9352. }
  9353. async function flushBridgeHosts() {
  9354. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9355. if (!selBridge) {
  9356. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9357. return;
  9358. }
  9359. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9360. try {
  9361. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9362. method: 'POST',
  9363. headers: { 'Content-Type': 'application/json' },
  9364. body: JSON.stringify({ bridge: selBridge })
  9365. });
  9366. if (res.ok) {
  9367. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9368. loadBridgeHosts();
  9369. }
  9370. } catch (err) {
  9371. showToast('Error', err.message, 'error');
  9372. }
  9373. }
  9374. // ----------------- Helpers -----------------
  9375. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9376. const sel = document.getElementById(selectId);
  9377. if (!sel) return;
  9378. const prevVal = currentVal || sel.value;
  9379. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9380. (state.bridges || []).forEach(b => {
  9381. const opt = document.createElement('option');
  9382. opt.value = b.name;
  9383. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9384. if (b.name === prevVal) opt.selected = true;
  9385. sel.appendChild(opt);
  9386. });
  9387. }
  9388. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9389. const sel = document.getElementById(selectId);
  9390. if (!sel) return;
  9391. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9392. // 1. Physical Interfaces
  9393. const grpPhys = document.createElement('optgroup');
  9394. grpPhys.label = 'Physical Interfaces';
  9395. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9396. const opt = document.createElement('option');
  9397. opt.value = i.name;
  9398. opt.innerText = `${i.name} (${i.role || i.type})`;
  9399. if (i.name === currentVal) opt.selected = true;
  9400. grpPhys.appendChild(opt);
  9401. });
  9402. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9403. // 2. VLAN Sub-interfaces
  9404. const grpVlans = document.createElement('optgroup');
  9405. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9406. (state.vlans || []).forEach(v => {
  9407. const opt = document.createElement('option');
  9408. opt.value = v.name;
  9409. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9410. if (v.name === currentVal) opt.selected = true;
  9411. grpVlans.appendChild(opt);
  9412. });
  9413. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9414. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9415. const grpEoip = document.createElement('optgroup');
  9416. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9417. (state.eoipTunnels || []).forEach(t => {
  9418. const opt = document.createElement('option');
  9419. opt.value = t.name;
  9420. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9421. if (t.name === currentVal) opt.selected = true;
  9422. grpEoip.appendChild(opt);
  9423. });
  9424. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9425. }
  9426. // -------------------------------------------------------------
  9427. // RouterOS v7 Routing Filters Management (/routing filter)
  9428. // -------------------------------------------------------------
  9429. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9430. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9431. if (!state.rfSort) state.rfSort = {};
  9432. function switchRoutingFilterTab(tab) {
  9433. state.activeRoutingFilterTab = tab;
  9434. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9435. tabs.forEach(t => {
  9436. const btn = document.getElementById(`tab-rf-${t}`);
  9437. const content = document.getElementById(`tab-content-rf-${t}`);
  9438. if (btn) {
  9439. if (t === tab) {
  9440. 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';
  9441. } else {
  9442. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9443. }
  9444. }
  9445. if (content) {
  9446. if (t === tab) content.classList.remove('hidden');
  9447. else content.classList.add('hidden');
  9448. }
  9449. });
  9450. const chainContainer = document.getElementById('rf-chain-filter-container');
  9451. if (chainContainer) {
  9452. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9453. else chainContainer.classList.add('hidden');
  9454. }
  9455. renderRoutingFilters();
  9456. }
  9457. function selectFilterRow(tab, id) {
  9458. if (state.selectedFilterRow[tab] === id) {
  9459. delete state.selectedFilterRow[tab];
  9460. } else {
  9461. state.selectedFilterRow[tab] = id;
  9462. }
  9463. if (tab === 'rules') renderRoutingFilterRules();
  9464. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9465. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9466. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9467. }
  9468. function openRoutingFilterNewModal() {
  9469. const tab = state.activeRoutingFilterTab || 'rules';
  9470. if (tab === 'rules') openAddRoutingFilterModal();
  9471. else if (tab === 'select-rules') openAddSelectRuleModal();
  9472. else if (tab === 'community-lists') openAddCommunityListModal();
  9473. else if (tab === 'as-lists') openAddASListModal();
  9474. }
  9475. function toggleSelectedRoutingFilter(disabled) {
  9476. const tab = state.activeRoutingFilterTab || 'rules';
  9477. const id = state.selectedFilterRow[tab];
  9478. if (!id) {
  9479. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9480. return;
  9481. }
  9482. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9483. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9484. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9485. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9486. }
  9487. function removeSelectedRoutingFilter() {
  9488. const tab = state.activeRoutingFilterTab || 'rules';
  9489. const id = state.selectedFilterRow[tab];
  9490. if (!id) {
  9491. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9492. return;
  9493. }
  9494. if (tab === 'rules') deleteRoutingFilter(id);
  9495. else if (tab === 'select-rules') deleteSelectRule(id);
  9496. else if (tab === 'community-lists') deleteCommunityList(id);
  9497. else if (tab === 'as-lists') deleteASList(id);
  9498. }
  9499. function searchRoutingFilters(q) {
  9500. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9501. renderRoutingFilters();
  9502. }
  9503. function sortFilterTable(tab, col) {
  9504. if (!state.rfSort) state.rfSort = {};
  9505. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9506. if (state.rfSort[tab].col === col) {
  9507. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9508. } else {
  9509. state.rfSort[tab].col = col;
  9510. state.rfSort[tab].asc = true;
  9511. }
  9512. const asc = state.rfSort[tab].asc;
  9513. let list = [];
  9514. if (tab === 'rules') list = state.routingFilters || [];
  9515. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9516. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9517. else if (tab === 'as-lists') list = state.routingASLists || [];
  9518. list.sort((a, b) => {
  9519. let valA = a[col] ?? '';
  9520. let valB = b[col] ?? '';
  9521. if (col === 'flags') {
  9522. valA = a.disabled ? 'X' : 'A';
  9523. valB = b.disabled ? 'X' : 'A';
  9524. }
  9525. if (typeof valA === 'number' && typeof valB === 'number') {
  9526. return asc ? valA - valB : valB - valA;
  9527. }
  9528. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9529. });
  9530. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9531. allCols.forEach(c => {
  9532. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9533. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9534. });
  9535. if (tab === 'rules') renderRoutingFilterRules();
  9536. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9537. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9538. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9539. }
  9540. function renderRoutingFilters() {
  9541. const navBadge = document.getElementById('badge-filters-count');
  9542. const allRules = state.routingFilters || [];
  9543. if (navBadge) navBadge.innerText = allRules.length;
  9544. // Populate chain filter select options and datalist
  9545. const chainSelect = document.getElementById('routing-filter-chain-select');
  9546. const chainDatalist = document.getElementById('dl-routing-chains');
  9547. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9548. if (chainSelect) {
  9549. const currentVal = state.filterChainSelected || 'all';
  9550. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9551. uniqueChains.map(ch => {
  9552. const count = allRules.filter(r => r.chain === ch).length;
  9553. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9554. }).join('');
  9555. chainSelect.value = currentVal;
  9556. }
  9557. if (chainDatalist) {
  9558. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9559. }
  9560. renderRoutingFilterRules();
  9561. renderRoutingFilterSelectRules();
  9562. renderRoutingFilterCommunityLists();
  9563. renderRoutingFilterASLists();
  9564. }
  9565. function filterRoutingFiltersByChain(chain) {
  9566. state.filterChainSelected = chain;
  9567. renderRoutingFilters();
  9568. }
  9569. // -------------------------------------------------------------
  9570. // TAB 1: RULES (/routing filter rule)
  9571. // -------------------------------------------------------------
  9572. function renderRoutingFilterRules() {
  9573. const tbody = document.getElementById('routing-filter-rules-tbody');
  9574. if (!tbody) return;
  9575. const empty = document.getElementById('rf-rules-empty');
  9576. const statusCount = document.getElementById('rf-status-count');
  9577. let list = (state.routingFilters || []).slice();
  9578. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9579. list = list.filter(r => r.chain === state.filterChainSelected);
  9580. }
  9581. const q = state.rfSearchQuery;
  9582. if (q) {
  9583. list = list.filter(r =>
  9584. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9585. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9586. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9587. (r.comment && r.comment.toLowerCase().includes(q))
  9588. );
  9589. }
  9590. if (!state.rfSort?.['rules']) {
  9591. list.sort((a, b) => {
  9592. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9593. return (a.rule_order || 0) - (b.rule_order || 0);
  9594. });
  9595. }
  9596. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9597. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9598. }
  9599. if (list.length === 0) {
  9600. tbody.innerHTML = '';
  9601. if (empty) empty.classList.remove('hidden');
  9602. return;
  9603. }
  9604. if (empty) empty.classList.add('hidden');
  9605. tbody.innerHTML = list.map(r => {
  9606. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9607. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9608. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9609. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9610. let ruleDisplay = '';
  9611. if (r.rule && r.rule.trim() !== '') {
  9612. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9613. } else {
  9614. let conds = [];
  9615. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9616. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9617. let act = r.action || 'accept';
  9618. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9619. }
  9620. return `
  9621. <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'}">
  9622. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9623. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9624. <td class="py-2 px-3">
  9625. <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>
  9626. </td>
  9627. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9628. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9629. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9630. <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>
  9631. <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>
  9632. <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'}">
  9633. ${r.disabled ? 'Enable' : 'Disable'}
  9634. </button>
  9635. <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">
  9636. Edit
  9637. </button>
  9638. <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">
  9639. ✕
  9640. </button>
  9641. </td>
  9642. </tr>
  9643. `;
  9644. }).join('');
  9645. }
  9646. // -------------------------------------------------------------
  9647. // TAB 2: SELECT RULES (/routing filter select-rule)
  9648. // -------------------------------------------------------------
  9649. function renderRoutingFilterSelectRules() {
  9650. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9651. if (!tbody) return;
  9652. const empty = document.getElementById('rf-select-rules-empty');
  9653. const statusCount = document.getElementById('rf-status-count');
  9654. let list = (state.routingSelectRules || []).slice();
  9655. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9656. list = list.filter(r => r.chain === state.filterChainSelected);
  9657. }
  9658. const q = state.rfSearchQuery;
  9659. if (q) {
  9660. list = list.filter(r =>
  9661. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9662. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9663. (r.comment && r.comment.toLowerCase().includes(q))
  9664. );
  9665. }
  9666. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9667. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9668. }
  9669. if (list.length === 0) {
  9670. tbody.innerHTML = '';
  9671. if (empty) empty.classList.remove('hidden');
  9672. return;
  9673. }
  9674. if (empty) empty.classList.add('hidden');
  9675. tbody.innerHTML = list.map(r => {
  9676. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9677. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9678. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9679. return `
  9680. <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'}">
  9681. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9682. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9683. <td class="py-2 px-3">
  9684. <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>
  9685. </td>
  9686. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9687. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9688. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9689. <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'}">
  9690. ${r.disabled ? 'Enable' : 'Disable'}
  9691. </button>
  9692. <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">
  9693. Edit
  9694. </button>
  9695. <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">
  9696. ✕
  9697. </button>
  9698. </td>
  9699. </tr>
  9700. `;
  9701. }).join('');
  9702. }
  9703. // -------------------------------------------------------------
  9704. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9705. // -------------------------------------------------------------
  9706. function renderRoutingFilterCommunityLists() {
  9707. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9708. if (!tbody) return;
  9709. const empty = document.getElementById('rf-comm-lists-empty');
  9710. const statusCount = document.getElementById('rf-status-count');
  9711. let list = (state.routingCommunityLists || []).slice();
  9712. const q = state.rfSearchQuery;
  9713. if (q) {
  9714. list = list.filter(cl =>
  9715. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9716. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9717. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9718. );
  9719. }
  9720. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9721. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9722. }
  9723. if (list.length === 0) {
  9724. tbody.innerHTML = '';
  9725. if (empty) empty.classList.remove('hidden');
  9726. return;
  9727. }
  9728. if (empty) empty.classList.add('hidden');
  9729. tbody.innerHTML = list.map(cl => {
  9730. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9731. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9732. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9733. const commBadges = (cl.communities || []).map(c =>
  9734. `<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>`
  9735. ).join(' ');
  9736. return `
  9737. <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'}">
  9738. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9739. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9740. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9741. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9742. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9743. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9744. <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'}">
  9745. ${cl.disabled ? 'Enable' : 'Disable'}
  9746. </button>
  9747. <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">
  9748. Edit
  9749. </button>
  9750. <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">
  9751. ✕
  9752. </button>
  9753. </td>
  9754. </tr>
  9755. `;
  9756. }).join('');
  9757. }
  9758. // -------------------------------------------------------------
  9759. // TAB 4: AS LISTS (/routing filter num-list)
  9760. // -------------------------------------------------------------
  9761. function renderRoutingFilterASLists() {
  9762. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9763. if (!tbody) return;
  9764. const empty = document.getElementById('rf-as-lists-empty');
  9765. const statusCount = document.getElementById('rf-status-count');
  9766. let list = (state.routingASLists || []).slice();
  9767. const q = state.rfSearchQuery;
  9768. if (q) {
  9769. list = list.filter(al =>
  9770. (al.name && al.name.toLowerCase().includes(q)) ||
  9771. (al.range && al.range.toLowerCase().includes(q)) ||
  9772. (al.comment && al.comment.toLowerCase().includes(q))
  9773. );
  9774. }
  9775. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9776. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9777. }
  9778. if (list.length === 0) {
  9779. tbody.innerHTML = '';
  9780. if (empty) empty.classList.remove('hidden');
  9781. return;
  9782. }
  9783. if (empty) empty.classList.add('hidden');
  9784. tbody.innerHTML = list.map(al => {
  9785. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9786. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9787. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9788. return `
  9789. <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'}">
  9790. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9791. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9792. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9793. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9794. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9795. <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'}">
  9796. ${al.disabled ? 'Enable' : 'Disable'}
  9797. </button>
  9798. <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">
  9799. Edit
  9800. </button>
  9801. <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">
  9802. ✕
  9803. </button>
  9804. </td>
  9805. </tr>
  9806. `;
  9807. }).join('');
  9808. }
  9809. // -------------------------------------------------------------
  9810. // SNIPPETS & WIZARD HELPERS
  9811. // -------------------------------------------------------------
  9812. function insertRuleSnippet(type) {
  9813. const textarea = document.getElementById('modal-rf-rule');
  9814. if (!textarea) return;
  9815. let snippet = '';
  9816. switch (type) {
  9817. case 'accept-default':
  9818. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9819. break;
  9820. case 'drop-rfc1918':
  9821. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9822. break;
  9823. case 'len-24':
  9824. snippet = 'if (dst-len > 24) { reject; }';
  9825. break;
  9826. case 'local-pref-150':
  9827. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9828. break;
  9829. case 'as-prepend-2':
  9830. snippet = 'set bgp-path-prepend 2; accept;';
  9831. break;
  9832. case 'set-comm':
  9833. snippet = 'set bgp-communities.add 65000:100; accept;';
  9834. break;
  9835. case 'match-comm':
  9836. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9837. break;
  9838. case 'reject-all':
  9839. snippet = 'reject;';
  9840. break;
  9841. }
  9842. if (!snippet) return;
  9843. if (!textarea.value.trim()) {
  9844. textarea.value = snippet;
  9845. } else {
  9846. textarea.value = textarea.value.trim() + '\n' + snippet;
  9847. }
  9848. }
  9849. function generateScriptFromWizard() {
  9850. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9851. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9852. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9853. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9854. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9855. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9856. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9857. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9858. const conds = [];
  9859. if (pfx) {
  9860. if (pfxLen) {
  9861. if (pfxLen.includes('-')) {
  9862. const parts = pfxLen.split('-');
  9863. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9864. } else {
  9865. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9866. }
  9867. } else {
  9868. conds.push(`dst in ${pfx}`);
  9869. }
  9870. }
  9871. if (proto && proto !== 'any') {
  9872. conds.push(`protocol ${proto}`);
  9873. }
  9874. if (asp) {
  9875. conds.push(`bgp-as-path "${asp}"`);
  9876. }
  9877. if (comm) {
  9878. conds.push(`bgp-communities includes ${comm}`);
  9879. }
  9880. const actions = [];
  9881. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9882. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9883. actions.push(`${act};`);
  9884. let code = '';
  9885. if (conds.length > 0) {
  9886. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9887. } else {
  9888. code = actions.join(' ');
  9889. }
  9890. const textarea = document.getElementById('modal-rf-rule');
  9891. if (textarea) textarea.value = code;
  9892. }
  9893. // -------------------------------------------------------------
  9894. // MODAL CRUD: RULES (/routing filter rule)
  9895. // -------------------------------------------------------------
  9896. function openAddRoutingFilterModal(defaultChain = '') {
  9897. const form = document.getElementById('routing-filter-form');
  9898. if (form) form.reset();
  9899. const idEl = document.getElementById('modal-rf-id');
  9900. if (idEl) idEl.value = '';
  9901. const titleEl = document.getElementById('modal-rf-title');
  9902. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9903. const chainEl = document.getElementById('modal-rf-chain');
  9904. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9905. const orderEl = document.getElementById('modal-rf-order');
  9906. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9907. const ruleEl = document.getElementById('modal-rf-rule');
  9908. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9909. const disEl = document.getElementById('modal-rf-disabled');
  9910. if (disEl) disEl.checked = false;
  9911. const modal = document.getElementById('modal-routing-filter');
  9912. if (modal) modal.classList.remove('hidden');
  9913. }
  9914. function openEditRoutingFilterModal(id) {
  9915. const r = (state.routingFilters || []).find(item => item.id === id);
  9916. if (!r) return;
  9917. const idEl = document.getElementById('modal-rf-id');
  9918. if (idEl) idEl.value = r.id;
  9919. const titleEl = document.getElementById('modal-rf-title');
  9920. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9921. const chainEl = document.getElementById('modal-rf-chain');
  9922. if (chainEl) chainEl.value = r.chain || '';
  9923. const orderEl = document.getElementById('modal-rf-order');
  9924. if (orderEl) orderEl.value = r.rule_order || 10;
  9925. const ruleEl = document.getElementById('modal-rf-rule');
  9926. if (ruleEl) {
  9927. if (r.rule) {
  9928. ruleEl.value = r.rule;
  9929. } else {
  9930. let conds = [];
  9931. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9932. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9933. let act = r.action || 'accept';
  9934. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9935. }
  9936. }
  9937. const comEl = document.getElementById('modal-rf-comment');
  9938. if (comEl) comEl.value = r.comment || '';
  9939. const disEl = document.getElementById('modal-rf-disabled');
  9940. if (disEl) disEl.checked = !!r.disabled;
  9941. const modal = document.getElementById('modal-routing-filter');
  9942. if (modal) modal.classList.remove('hidden');
  9943. }
  9944. function closeRoutingFilterModal() {
  9945. const modal = document.getElementById('modal-routing-filter');
  9946. if (modal) modal.classList.add('hidden');
  9947. }
  9948. async function submitRoutingFilter(e) {
  9949. if (e) e.preventDefault();
  9950. const payload = {
  9951. id: document.getElementById('modal-rf-id').value,
  9952. chain: document.getElementById('modal-rf-chain').value.trim(),
  9953. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9954. rule: document.getElementById('modal-rf-rule').value.trim(),
  9955. comment: document.getElementById('modal-rf-comment').value.trim(),
  9956. disabled: document.getElementById('modal-rf-disabled').checked
  9957. };
  9958. try {
  9959. const res = await fetch(`${API_BASE}/routing/filters`, {
  9960. method: 'POST',
  9961. headers: { 'Content-Type': 'application/json' },
  9962. body: JSON.stringify(payload)
  9963. });
  9964. if (res.ok) {
  9965. closeRoutingFilterModal();
  9966. showToast('Success', 'Routing filter rule saved', 'success');
  9967. loadDynamicRouting();
  9968. } else {
  9969. const err = await res.json();
  9970. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9971. }
  9972. } catch (err) {
  9973. showToast('Error', err.message, 'error');
  9974. }
  9975. }
  9976. async function applyRoutingFilterForm() {
  9977. const payload = {
  9978. id: document.getElementById('modal-rf-id').value,
  9979. chain: document.getElementById('modal-rf-chain').value.trim(),
  9980. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9981. rule: document.getElementById('modal-rf-rule').value.trim(),
  9982. comment: document.getElementById('modal-rf-comment').value.trim(),
  9983. disabled: document.getElementById('modal-rf-disabled').checked
  9984. };
  9985. try {
  9986. const res = await fetch(`${API_BASE}/routing/filters`, {
  9987. method: 'POST',
  9988. headers: { 'Content-Type': 'application/json' },
  9989. body: JSON.stringify(payload)
  9990. });
  9991. if (res.ok) {
  9992. const data = await res.json();
  9993. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  9994. showToast('Applied', 'Routing filter configuration applied', 'success');
  9995. loadDynamicRouting();
  9996. } else {
  9997. const err = await res.json();
  9998. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  9999. }
  10000. } catch (err) {
  10001. showToast('Error', err.message, 'error');
  10002. }
  10003. }
  10004. async function moveRoutingFilterOrder(id, delta) {
  10005. const list = state.routingFilters || [];
  10006. const idx = list.findIndex(r => r.id === id);
  10007. if (idx < 0) return;
  10008. const targetIdx = idx + delta;
  10009. if (targetIdx < 0 || targetIdx >= list.length) return;
  10010. const currentOrder = list[idx].rule_order || 10;
  10011. const targetOrder = list[targetIdx].rule_order || 20;
  10012. list[idx].rule_order = targetOrder;
  10013. list[targetIdx].rule_order = currentOrder;
  10014. try {
  10015. await fetch(`${API_BASE}/routing/filters`, {
  10016. method: 'POST',
  10017. headers: { 'Content-Type': 'application/json' },
  10018. body: JSON.stringify(list[idx])
  10019. });
  10020. await fetch(`${API_BASE}/routing/filters`, {
  10021. method: 'POST',
  10022. headers: { 'Content-Type': 'application/json' },
  10023. body: JSON.stringify(list[targetIdx])
  10024. });
  10025. loadDynamicRouting();
  10026. } catch (e) {
  10027. console.error('Reorder error:', e);
  10028. }
  10029. }
  10030. async function deleteRoutingFilter(id) {
  10031. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10032. try {
  10033. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10034. if (res.ok) {
  10035. showToast('Deleted', 'Routing filter rule removed', 'info');
  10036. loadDynamicRouting();
  10037. } else {
  10038. const err = await res.json();
  10039. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10040. }
  10041. } catch (err) {
  10042. showToast('Error', err.message, 'error');
  10043. }
  10044. }
  10045. async function toggleRoutingFilterState(id, disabled) {
  10046. try {
  10047. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10048. method: 'POST',
  10049. headers: { 'Content-Type': 'application/json' },
  10050. body: JSON.stringify({ disabled })
  10051. });
  10052. if (res.ok) {
  10053. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10054. loadDynamicRouting();
  10055. } else {
  10056. const err = await res.json();
  10057. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10058. }
  10059. } catch (err) {
  10060. showToast('Error', err.message, 'error');
  10061. }
  10062. }
  10063. // -------------------------------------------------------------
  10064. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10065. // -------------------------------------------------------------
  10066. function openAddSelectRuleModal() {
  10067. document.getElementById('modal-rf-sr-id').value = '';
  10068. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10069. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10070. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10071. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10072. document.getElementById('modal-rf-sr-comment').value = '';
  10073. document.getElementById('modal-rf-sr-disabled').checked = false;
  10074. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10075. }
  10076. function openEditSelectRuleModal(id) {
  10077. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10078. if (!r) return;
  10079. document.getElementById('modal-rf-sr-id').value = r.id;
  10080. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10081. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10082. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10083. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10084. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10085. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10086. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10087. }
  10088. function closeSelectRuleModal() {
  10089. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10090. }
  10091. async function submitSelectRule(e) {
  10092. e.preventDefault();
  10093. const payload = {
  10094. id: document.getElementById('modal-rf-sr-id').value,
  10095. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10096. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10097. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10098. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10099. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10100. };
  10101. try {
  10102. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10103. method: 'POST',
  10104. headers: { 'Content-Type': 'application/json' },
  10105. body: JSON.stringify(payload)
  10106. });
  10107. if (res.ok) {
  10108. closeSelectRuleModal();
  10109. showToast('Success', 'Select rule saved', 'success');
  10110. loadDynamicRouting();
  10111. } else {
  10112. const err = await res.json();
  10113. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10114. }
  10115. } catch (err) {
  10116. showToast('Error', err.message, 'error');
  10117. }
  10118. }
  10119. async function deleteSelectRule(id) {
  10120. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10121. try {
  10122. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10123. if (res.ok) {
  10124. showToast('Deleted', 'Select rule removed', 'info');
  10125. loadDynamicRouting();
  10126. } else {
  10127. const err = await res.json();
  10128. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10129. }
  10130. } catch (err) {
  10131. showToast('Error', err.message, 'error');
  10132. }
  10133. }
  10134. async function toggleSelectRuleState(id, disabled) {
  10135. try {
  10136. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10137. method: 'POST',
  10138. headers: { 'Content-Type': 'application/json' },
  10139. body: JSON.stringify({ disabled })
  10140. });
  10141. if (res.ok) {
  10142. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10143. loadDynamicRouting();
  10144. } else {
  10145. const err = await res.json();
  10146. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10147. }
  10148. } catch (err) {
  10149. showToast('Error', err.message, 'error');
  10150. }
  10151. }
  10152. // -------------------------------------------------------------
  10153. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10154. // -------------------------------------------------------------
  10155. function openAddCommunityListModal() {
  10156. document.getElementById('modal-rf-cl-id').value = '';
  10157. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10158. document.getElementById('modal-rf-cl-name').value = '';
  10159. document.getElementById('modal-rf-cl-communities').value = '';
  10160. document.getElementById('modal-rf-cl-regexp').value = '';
  10161. document.getElementById('modal-rf-cl-comment').value = '';
  10162. document.getElementById('modal-rf-cl-disabled').checked = false;
  10163. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10164. }
  10165. function openEditCommunityListModal(id) {
  10166. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10167. if (!cl) return;
  10168. document.getElementById('modal-rf-cl-id').value = cl.id;
  10169. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10170. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10171. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10172. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10173. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10174. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10175. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10176. }
  10177. function closeCommunityListModal() {
  10178. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10179. }
  10180. async function submitCommunityList(e) {
  10181. e.preventDefault();
  10182. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10183. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10184. const payload = {
  10185. id: document.getElementById('modal-rf-cl-id').value,
  10186. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10187. communities: comms,
  10188. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10189. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10190. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10191. };
  10192. try {
  10193. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10194. method: 'POST',
  10195. headers: { 'Content-Type': 'application/json' },
  10196. body: JSON.stringify(payload)
  10197. });
  10198. if (res.ok) {
  10199. closeCommunityListModal();
  10200. showToast('Success', 'Community list saved', 'success');
  10201. loadDynamicRouting();
  10202. } else {
  10203. const err = await res.json();
  10204. showToast('Error', err.error || 'Failed to save community list', 'error');
  10205. }
  10206. } catch (err) {
  10207. showToast('Error', err.message, 'error');
  10208. }
  10209. }
  10210. async function deleteCommunityList(id) {
  10211. if (!confirm('Are you sure you want to delete this community list?')) return;
  10212. try {
  10213. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10214. if (res.ok) {
  10215. showToast('Deleted', 'Community list removed', 'info');
  10216. loadDynamicRouting();
  10217. } else {
  10218. const err = await res.json();
  10219. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10220. }
  10221. } catch (err) {
  10222. showToast('Error', err.message, 'error');
  10223. }
  10224. }
  10225. async function toggleCommunityListState(id, disabled) {
  10226. try {
  10227. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10228. method: 'POST',
  10229. headers: { 'Content-Type': 'application/json' },
  10230. body: JSON.stringify({ disabled })
  10231. });
  10232. if (res.ok) {
  10233. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10234. loadDynamicRouting();
  10235. } else {
  10236. const err = await res.json();
  10237. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10238. }
  10239. } catch (err) {
  10240. showToast('Error', err.message, 'error');
  10241. }
  10242. }
  10243. // -------------------------------------------------------------
  10244. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10245. // -------------------------------------------------------------
  10246. function openAddASListModal() {
  10247. document.getElementById('modal-rf-al-id').value = '';
  10248. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10249. document.getElementById('modal-rf-al-name').value = '';
  10250. document.getElementById('modal-rf-al-range').value = '';
  10251. document.getElementById('modal-rf-al-comment').value = '';
  10252. document.getElementById('modal-rf-al-disabled').checked = false;
  10253. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10254. }
  10255. function openEditASListModal(id) {
  10256. const al = (state.routingASLists || []).find(item => item.id === id);
  10257. if (!al) return;
  10258. document.getElementById('modal-rf-al-id').value = al.id;
  10259. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10260. document.getElementById('modal-rf-al-name').value = al.name || '';
  10261. document.getElementById('modal-rf-al-range').value = al.range || '';
  10262. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10263. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10264. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10265. }
  10266. function closeASListModal() {
  10267. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10268. }
  10269. async function submitASList(e) {
  10270. e.preventDefault();
  10271. const payload = {
  10272. id: document.getElementById('modal-rf-al-id').value,
  10273. name: document.getElementById('modal-rf-al-name').value.trim(),
  10274. range: document.getElementById('modal-rf-al-range').value.trim(),
  10275. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10276. disabled: document.getElementById('modal-rf-al-disabled').checked
  10277. };
  10278. try {
  10279. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10280. method: 'POST',
  10281. headers: { 'Content-Type': 'application/json' },
  10282. body: JSON.stringify(payload)
  10283. });
  10284. if (res.ok) {
  10285. closeASListModal();
  10286. showToast('Success', 'AS number list saved', 'success');
  10287. loadDynamicRouting();
  10288. } else {
  10289. const err = await res.json();
  10290. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10291. }
  10292. } catch (err) {
  10293. showToast('Error', err.message, 'error');
  10294. }
  10295. }
  10296. async function deleteASList(id) {
  10297. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10298. try {
  10299. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10300. if (res.ok) {
  10301. showToast('Deleted', 'AS list removed', 'info');
  10302. loadDynamicRouting();
  10303. } else {
  10304. const err = await res.json();
  10305. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10306. }
  10307. } catch (err) {
  10308. showToast('Error', err.message, 'error');
  10309. }
  10310. }
  10311. async function toggleASListState(id, disabled) {
  10312. try {
  10313. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10314. method: 'POST',
  10315. headers: { 'Content-Type': 'application/json' },
  10316. body: JSON.stringify({ disabled })
  10317. });
  10318. if (res.ok) {
  10319. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10320. loadDynamicRouting();
  10321. } else {
  10322. const err = await res.json();
  10323. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10324. }
  10325. } catch (err) {
  10326. showToast('Error', err.message, 'error');
  10327. }
  10328. }
  10329. // ==========================================
  10330. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10331. // ==========================================
  10332. function loadToolsView() {
  10333. populateToolsInterfaces();
  10334. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10335. }
  10336. function populateToolsInterfaces() {
  10337. const pingSel = document.getElementById('tools-ping-iface');
  10338. const traceSel = document.getElementById('tools-tr-iface');
  10339. let opts = '<option value="">Auto (Default Route)</option>';
  10340. if (Array.isArray(state.interfaces)) {
  10341. state.interfaces.forEach(iface => {
  10342. if (iface.name) {
  10343. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10344. }
  10345. });
  10346. }
  10347. if (pingSel) {
  10348. const cur = pingSel.value;
  10349. pingSel.innerHTML = opts;
  10350. if (cur) pingSel.value = cur;
  10351. }
  10352. if (traceSel) {
  10353. const cur = traceSel.value;
  10354. traceSel.innerHTML = opts;
  10355. if (cur) traceSel.value = cur;
  10356. }
  10357. }
  10358. function switchToolsSubTab(subTab) {
  10359. state.activeToolsSubTab = subTab;
  10360. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10361. tabs.forEach(t => {
  10362. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10363. const view = document.getElementById(`tools-view-${t}`);
  10364. if (btn) {
  10365. if (t === subTab) {
  10366. 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';
  10367. } else {
  10368. 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';
  10369. }
  10370. }
  10371. if (view) {
  10372. if (t === subTab) {
  10373. view.classList.remove('hidden');
  10374. } else {
  10375. view.classList.add('hidden');
  10376. }
  10377. }
  10378. });
  10379. }
  10380. function setPortPreset(port) {
  10381. const input = document.getElementById('tools-port-num');
  10382. if (input) input.value = port;
  10383. }
  10384. let pingAbortController = null;
  10385. let tracerouteAbortController = null;
  10386. function clearPingTable() {
  10387. const tbody = document.getElementById('tools-ping-tbody');
  10388. if (tbody) tbody.innerHTML = '';
  10389. const rawEl = document.getElementById('tools-ping-raw');
  10390. if (rawEl) rawEl.innerText = '';
  10391. const sentEl = document.getElementById('tools-ping-stat-sent');
  10392. if (sentEl) sentEl.innerText = '0';
  10393. const recvEl = document.getElementById('tools-ping-stat-recv');
  10394. if (recvEl) recvEl.innerText = '0';
  10395. const lossEl = document.getElementById('tools-ping-stat-loss');
  10396. if (lossEl) lossEl.innerText = '0%';
  10397. const avgEl = document.getElementById('tools-ping-stat-avg');
  10398. if (avgEl) avgEl.innerText = '0 ms';
  10399. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10400. if (minMaxEl) minMaxEl.innerText = '-';
  10401. const badge = document.getElementById('tools-ping-status-badge');
  10402. if (badge) {
  10403. badge.className = '';
  10404. badge.innerText = '';
  10405. }
  10406. }
  10407. function clearTracerouteTable() {
  10408. const tbody = document.getElementById('tools-tr-tbody');
  10409. if (tbody) tbody.innerHTML = '';
  10410. const rawEl = document.getElementById('tools-tr-raw');
  10411. if (rawEl) rawEl.innerText = '';
  10412. const statHops = document.getElementById('tools-tr-hops-count');
  10413. if (statHops) statHops.innerText = '0 Hops';
  10414. }
  10415. function resetPingButton() {
  10416. const btn = document.getElementById('tools-ping-btn');
  10417. const btnText = document.getElementById('tools-ping-btn-text');
  10418. const spinner = document.getElementById('tools-ping-spinner');
  10419. if (btn) {
  10420. btn.disabled = false;
  10421. 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';
  10422. }
  10423. if (btnText) btnText.innerText = 'Start Ping';
  10424. if (spinner) spinner.classList.add('hidden');
  10425. }
  10426. function setPingRunningButton() {
  10427. const btn = document.getElementById('tools-ping-btn');
  10428. const btnText = document.getElementById('tools-ping-btn-text');
  10429. const spinner = document.getElementById('tools-ping-spinner');
  10430. if (btn) {
  10431. btn.disabled = false;
  10432. 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';
  10433. }
  10434. if (btnText) btnText.innerText = 'Stop Ping';
  10435. if (spinner) spinner.classList.remove('hidden');
  10436. }
  10437. function resetTracerouteButton() {
  10438. const btn = document.getElementById('tools-tr-btn');
  10439. const btnText = document.getElementById('tools-tr-btn-text');
  10440. const spinner = document.getElementById('tools-tr-spinner');
  10441. if (btn) {
  10442. btn.disabled = false;
  10443. 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';
  10444. }
  10445. if (btnText) btnText.innerText = 'Start Traceroute';
  10446. if (spinner) spinner.classList.add('hidden');
  10447. }
  10448. function setTracerouteRunningButton() {
  10449. const btn = document.getElementById('tools-tr-btn');
  10450. const btnText = document.getElementById('tools-tr-btn-text');
  10451. const spinner = document.getElementById('tools-tr-spinner');
  10452. if (btn) {
  10453. btn.disabled = false;
  10454. 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';
  10455. }
  10456. if (btnText) btnText.innerText = 'Stop Traceroute';
  10457. if (spinner) spinner.classList.remove('hidden');
  10458. }
  10459. async function executePing(e) {
  10460. if (e) e.preventDefault();
  10461. // If already running, clicking the button stops the stream!
  10462. if (pingAbortController) {
  10463. pingAbortController.abort();
  10464. pingAbortController = null;
  10465. resetPingButton();
  10466. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10467. return;
  10468. }
  10469. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10470. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10471. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10472. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10473. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10474. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10475. if (!target) {
  10476. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10477. return;
  10478. }
  10479. clearPingTable();
  10480. const resCard = document.getElementById('tools-ping-results');
  10481. if (resCard) resCard.classList.remove('hidden');
  10482. pingAbortController = new AbortController();
  10483. setPingRunningButton();
  10484. try {
  10485. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10486. method: 'POST',
  10487. headers: { 'Content-Type': 'application/json' },
  10488. body: JSON.stringify({
  10489. target,
  10490. count,
  10491. size,
  10492. timeout,
  10493. interface: iface,
  10494. dont_frag: dontFrag
  10495. }),
  10496. signal: pingAbortController.signal
  10497. });
  10498. if (!res.ok) {
  10499. const errText = await res.text();
  10500. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10501. resetPingButton();
  10502. pingAbortController = null;
  10503. return;
  10504. }
  10505. const reader = res.body.getReader();
  10506. const decoder = new TextDecoder('utf-8');
  10507. let buffer = '';
  10508. while (true) {
  10509. const { done, value } = await reader.read();
  10510. if (done) break;
  10511. buffer += decoder.decode(value, { stream: true });
  10512. const blocks = buffer.split('\n\n');
  10513. buffer = blocks.pop() || '';
  10514. for (const block of blocks) {
  10515. const trimmed = block.trim();
  10516. if (!trimmed) continue;
  10517. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10518. try {
  10519. const evt = JSON.parse(line);
  10520. handleLivePingEvent(evt);
  10521. } catch (parseErr) {
  10522. console.warn('Ping SSE parse error:', parseErr, line);
  10523. }
  10524. }
  10525. }
  10526. } catch (err) {
  10527. if (err.name === 'AbortError') {
  10528. // User aborted normally
  10529. } else {
  10530. showToast('Ping Error', err.message, 'error');
  10531. }
  10532. } finally {
  10533. pingAbortController = null;
  10534. resetPingButton();
  10535. }
  10536. }
  10537. function handleLivePingEvent(evt) {
  10538. const sentEl = document.getElementById('tools-ping-stat-sent');
  10539. const recvEl = document.getElementById('tools-ping-stat-recv');
  10540. const lossEl = document.getElementById('tools-ping-stat-loss');
  10541. const avgEl = document.getElementById('tools-ping-stat-avg');
  10542. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10543. const badge = document.getElementById('tools-ping-status-badge');
  10544. const tbody = document.getElementById('tools-ping-tbody');
  10545. const rawEl = document.getElementById('tools-ping-raw');
  10546. if (evt.raw && rawEl) {
  10547. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10548. rawEl.scrollTop = rawEl.scrollHeight;
  10549. }
  10550. if (evt.type === 'reply') {
  10551. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10552. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10553. if (lossEl && evt.packet_loss_pct !== undefined) {
  10554. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10555. lossEl.className = evt.packet_loss_pct === 0
  10556. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10557. : (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');
  10558. }
  10559. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10560. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10561. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10562. }
  10563. if (badge) {
  10564. if (evt.packet_loss_pct === 0) {
  10565. 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';
  10566. badge.innerText = '100% OK';
  10567. } else {
  10568. 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';
  10569. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10570. }
  10571. }
  10572. if (tbody) {
  10573. const tr = document.createElement('tr');
  10574. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10575. tr.innerHTML = `
  10576. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10577. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10578. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10579. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10580. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10581. <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>
  10582. `;
  10583. tbody.appendChild(tr);
  10584. }
  10585. } else if (evt.type === 'timeout') {
  10586. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10587. if (lossEl && evt.packet_loss_pct !== undefined) {
  10588. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10589. 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';
  10590. }
  10591. if (badge) {
  10592. 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';
  10593. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10594. }
  10595. if (tbody) {
  10596. const tr = document.createElement('tr');
  10597. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10598. tr.innerHTML = `
  10599. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10600. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10601. <td class="py-2 px-3 text-slate-600">--</td>
  10602. <td class="py-2 px-3 text-slate-600">--</td>
  10603. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10604. <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>
  10605. `;
  10606. tbody.appendChild(tr);
  10607. }
  10608. } else if (evt.type === 'unreach') {
  10609. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10610. if (lossEl && evt.packet_loss_pct !== undefined) {
  10611. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10612. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10613. }
  10614. if (badge) {
  10615. 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';
  10616. badge.innerText = 'UNREACHABLE';
  10617. }
  10618. if (tbody) {
  10619. const tr = document.createElement('tr');
  10620. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10621. tr.innerHTML = `
  10622. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10623. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10624. <td class="py-2 px-3 text-slate-600">--</td>
  10625. <td class="py-2 px-3 text-slate-600">--</td>
  10626. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10627. <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>
  10628. `;
  10629. tbody.appendChild(tr);
  10630. }
  10631. } else if (evt.type === 'stats') {
  10632. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10633. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10634. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10635. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10636. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10637. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10638. }
  10639. } else if (evt.type === 'done') {
  10640. 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');
  10641. }
  10642. }
  10643. async function executeTraceroute(e) {
  10644. if (e) e.preventDefault();
  10645. if (tracerouteAbortController) {
  10646. tracerouteAbortController.abort();
  10647. tracerouteAbortController = null;
  10648. resetTracerouteButton();
  10649. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10650. return;
  10651. }
  10652. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10653. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10654. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10655. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10656. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10657. if (!target) {
  10658. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10659. return;
  10660. }
  10661. clearTracerouteTable();
  10662. const resCard = document.getElementById('tools-tr-results');
  10663. if (resCard) resCard.classList.remove('hidden');
  10664. tracerouteAbortController = new AbortController();
  10665. setTracerouteRunningButton();
  10666. try {
  10667. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10668. method: 'POST',
  10669. headers: { 'Content-Type': 'application/json' },
  10670. body: JSON.stringify({
  10671. target,
  10672. max_hops: maxHops,
  10673. protocol,
  10674. interface: iface,
  10675. resolve
  10676. }),
  10677. signal: tracerouteAbortController.signal
  10678. });
  10679. if (!res.ok) {
  10680. const errText = await res.text();
  10681. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10682. resetTracerouteButton();
  10683. tracerouteAbortController = null;
  10684. return;
  10685. }
  10686. const reader = res.body.getReader();
  10687. const decoder = new TextDecoder('utf-8');
  10688. let buffer = '';
  10689. while (true) {
  10690. const { done, value } = await reader.read();
  10691. if (done) break;
  10692. buffer += decoder.decode(value, { stream: true });
  10693. const blocks = buffer.split('\n\n');
  10694. buffer = blocks.pop() || '';
  10695. for (const block of blocks) {
  10696. const trimmed = block.trim();
  10697. if (!trimmed) continue;
  10698. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10699. try {
  10700. const evt = JSON.parse(line);
  10701. handleLiveTracerouteEvent(evt);
  10702. } catch (parseErr) {
  10703. console.warn('Traceroute SSE parse error:', parseErr, line);
  10704. }
  10705. }
  10706. }
  10707. } catch (err) {
  10708. if (err.name === 'AbortError') {
  10709. // User aborted normally
  10710. } else {
  10711. showToast('Traceroute Error', err.message, 'error');
  10712. }
  10713. } finally {
  10714. tracerouteAbortController = null;
  10715. resetTracerouteButton();
  10716. }
  10717. }
  10718. function handleLiveTracerouteEvent(evt) {
  10719. const statHops = document.getElementById('tools-tr-hops-count');
  10720. const tbody = document.getElementById('tools-tr-tbody');
  10721. const rawEl = document.getElementById('tools-tr-raw');
  10722. if (evt.raw && rawEl) {
  10723. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10724. rawEl.scrollTop = rawEl.scrollHeight;
  10725. }
  10726. if (evt.hops_count !== undefined && statHops) {
  10727. statHops.innerText = `${evt.hops_count} Hops`;
  10728. }
  10729. if (evt.type === 'hop' && evt.hop && tbody) {
  10730. const h = evt.hop;
  10731. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10732. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10733. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10734. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10735. const tr = document.createElement('tr');
  10736. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10737. tr.innerHTML = `
  10738. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10739. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10740. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10741. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10742. <td class="py-2.5 px-3 text-right">
  10743. ${isTimeout
  10744. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10745. : '<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>'}
  10746. </td>
  10747. `;
  10748. tbody.appendChild(tr);
  10749. } else if (evt.type === 'done') {
  10750. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10751. }
  10752. }
  10753. async function executeMTR(e) {
  10754. if (e) e.preventDefault();
  10755. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10756. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10757. if (!target) {
  10758. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10759. return;
  10760. }
  10761. const btn = document.getElementById('tools-mtr-btn');
  10762. const spinner = document.getElementById('tools-mtr-spinner');
  10763. if (btn) btn.disabled = true;
  10764. if (spinner) spinner.classList.remove('hidden');
  10765. try {
  10766. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10767. method: 'POST',
  10768. headers: { 'Content-Type': 'application/json' },
  10769. body: JSON.stringify({ target, count: cycles })
  10770. });
  10771. const data = await res.json();
  10772. if (!res.ok) {
  10773. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10774. return;
  10775. }
  10776. const resCard = document.getElementById('tools-mtr-results');
  10777. if (resCard) resCard.classList.remove('hidden');
  10778. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10779. const statHops = document.getElementById('tools-mtr-hops-count');
  10780. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10781. const tbody = document.getElementById('tools-mtr-tbody');
  10782. if (tbody) {
  10783. if (hopsCount > 0) {
  10784. tbody.innerHTML = data.hops.map(h => {
  10785. 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');
  10786. return `
  10787. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10788. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10789. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10790. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10791. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10792. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10793. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10794. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10795. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10796. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10797. </tr>
  10798. `;
  10799. }).join('');
  10800. } else {
  10801. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10802. }
  10803. }
  10804. const rawEl = document.getElementById('tools-mtr-raw');
  10805. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10806. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10807. } catch (err) {
  10808. showToast('MTR Error', err.message, 'error');
  10809. } finally {
  10810. if (btn) btn.disabled = false;
  10811. if (spinner) spinner.classList.add('hidden');
  10812. }
  10813. }
  10814. async function executeDNS(e) {
  10815. if (e) e.preventDefault();
  10816. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10817. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10818. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10819. if (!domain) {
  10820. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10821. return;
  10822. }
  10823. const btn = document.getElementById('tools-dns-btn');
  10824. const spinner = document.getElementById('tools-dns-spinner');
  10825. if (btn) btn.disabled = true;
  10826. if (spinner) spinner.classList.remove('hidden');
  10827. try {
  10828. const res = await fetch(`${API_BASE}/tools/dns`, {
  10829. method: 'POST',
  10830. headers: { 'Content-Type': 'application/json' },
  10831. body: JSON.stringify({ domain, type, server })
  10832. });
  10833. const data = await res.json();
  10834. if (!res.ok) {
  10835. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10836. return;
  10837. }
  10838. const resCard = document.getElementById('tools-dns-results');
  10839. if (resCard) resCard.classList.remove('hidden');
  10840. const metaEl = document.getElementById('tools-dns-meta');
  10841. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10842. const tbody = document.getElementById('tools-dns-tbody');
  10843. if (tbody) {
  10844. if (Array.isArray(data.records) && data.records.length > 0) {
  10845. tbody.innerHTML = data.records.map(r => `
  10846. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10847. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10848. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10849. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10850. <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>
  10851. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10852. </tr>
  10853. `).join('');
  10854. } else {
  10855. 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>`;
  10856. }
  10857. }
  10858. const rawEl = document.getElementById('tools-dns-raw');
  10859. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10860. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10861. } catch (err) {
  10862. showToast('DNS Error', err.message, 'error');
  10863. } finally {
  10864. if (btn) btn.disabled = false;
  10865. if (spinner) spinner.classList.add('hidden');
  10866. }
  10867. }
  10868. async function executePortProbe(e) {
  10869. if (e) e.preventDefault();
  10870. const target = document.getElementById('tools-port-target')?.value?.trim();
  10871. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10872. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10873. if (!target || !port) {
  10874. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10875. return;
  10876. }
  10877. const btn = document.getElementById('tools-port-btn');
  10878. const spinner = document.getElementById('tools-port-spinner');
  10879. if (btn) btn.disabled = true;
  10880. if (spinner) spinner.classList.remove('hidden');
  10881. try {
  10882. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10883. method: 'POST',
  10884. headers: { 'Content-Type': 'application/json' },
  10885. body: JSON.stringify({ target, port, timeout })
  10886. });
  10887. const data = await res.json();
  10888. if (!res.ok) {
  10889. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10890. return;
  10891. }
  10892. const resCard = document.getElementById('tools-port-results');
  10893. if (resCard) resCard.classList.remove('hidden');
  10894. const banner = document.getElementById('tools-port-banner');
  10895. const icon = document.getElementById('tools-port-icon');
  10896. const title = document.getElementById('tools-port-title');
  10897. const sub = document.getElementById('tools-port-sub');
  10898. const latency = document.getElementById('tools-port-latency');
  10899. if (data.open) {
  10900. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10901. if (icon) {
  10902. 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';
  10903. icon.innerText = '✓';
  10904. }
  10905. if (title) {
  10906. title.className = 'text-sm font-bold text-emerald-300';
  10907. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10908. }
  10909. if (sub) {
  10910. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10911. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10912. }
  10913. if (latency) {
  10914. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10915. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10916. }
  10917. } else {
  10918. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10919. if (icon) {
  10920. 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';
  10921. icon.innerText = '✕';
  10922. }
  10923. if (title) {
  10924. title.className = 'text-sm font-bold text-rose-300';
  10925. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10926. }
  10927. if (sub) {
  10928. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10929. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10930. }
  10931. if (latency) {
  10932. latency.className = 'text-base font-bold font-mono text-slate-500';
  10933. latency.innerText = '--';
  10934. }
  10935. }
  10936. const rawEl = document.getElementById('tools-port-raw');
  10937. 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'}`);
  10938. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10939. } catch (err) {
  10940. showToast('Probe Error', err.message, 'error');
  10941. } finally {
  10942. if (btn) btn.disabled = false;
  10943. if (spinner) spinner.classList.add('hidden');
  10944. }
  10945. }
  10946. // ==========================================
  10947. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10948. // ==========================================
  10949. async function loadDHCPClients(showToastMsg = false) {
  10950. try {
  10951. const [clientsRes, sumRes] = await Promise.all([
  10952. fetch(`${API_BASE}/dhcp/clients`),
  10953. fetch(`${API_BASE}/dhcp/clients/summary`)
  10954. ]);
  10955. if (clientsRes.ok) {
  10956. state.dhcpClients = await clientsRes.json();
  10957. }
  10958. if (sumRes.ok) {
  10959. state.dhcpSummary = await sumRes.json();
  10960. }
  10961. renderDHCPClients();
  10962. updateDHCPSummaryCards();
  10963. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10964. if (bDhcp && state.dhcpSummary) {
  10965. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10966. }
  10967. if (showToastMsg) {
  10968. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10969. }
  10970. } catch (err) {
  10971. console.error('Failed to load DHCP clients:', err);
  10972. if (showToastMsg) {
  10973. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10974. }
  10975. }
  10976. }
  10977. function updateDHCPSummaryCards() {
  10978. const sum = state.dhcpSummary || {
  10979. total_clients: (state.dhcpClients || []).length,
  10980. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  10981. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  10982. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  10983. };
  10984. const totalEl = document.getElementById('dhcp-stat-total');
  10985. const boundEl = document.getElementById('dhcp-stat-bound');
  10986. const searchEl = document.getElementById('dhcp-stat-searching');
  10987. const disEl = document.getElementById('dhcp-stat-disabled');
  10988. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  10989. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  10990. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  10991. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  10992. }
  10993. function renderDHCPClients() {
  10994. const tbody = document.getElementById('dhcp-clients-tbody');
  10995. const emptyState = document.getElementById('dhcp-clients-empty');
  10996. if (!tbody) return;
  10997. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  10998. if (clients.length === 0) {
  10999. tbody.innerHTML = '';
  11000. if (emptyState) emptyState.classList.remove('hidden');
  11001. return;
  11002. }
  11003. if (emptyState) emptyState.classList.add('hidden');
  11004. tbody.innerHTML = clients.map(c => {
  11005. let statusBadge = '';
  11006. if (!c.enabled) {
  11007. 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>';
  11008. } else if (c.status === 'bound') {
  11009. 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>';
  11010. } else if (c.status === 'searching') {
  11011. 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>';
  11012. } else if (c.status === 'stopped') {
  11013. 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>';
  11014. } else {
  11015. 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>`;
  11016. }
  11017. 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>';
  11018. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11019. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11020. 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>';
  11021. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11022. // Option flags
  11023. const flags = [];
  11024. 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>');
  11025. 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>');
  11026. 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>');
  11027. 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>`);
  11028. return `
  11029. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11030. <td class="py-3 px-4">
  11031. <div class="flex items-center gap-2">
  11032. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11033. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11034. </div>
  11035. </td>
  11036. <td class="py-3 px-4">${statusBadge}</td>
  11037. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11038. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11039. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11040. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11041. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11042. <td class="py-3 px-4">
  11043. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11044. </td>
  11045. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11046. ${c.enabled ? `
  11047. <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>
  11048. <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>
  11049. <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>
  11050. ` : `
  11051. <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>
  11052. `}
  11053. <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>
  11054. <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>
  11055. </td>
  11056. </tr>
  11057. `;
  11058. }).join('');
  11059. }
  11060. function openDHCPClientModal(clientId = null) {
  11061. const modal = document.getElementById('modal-dhcp-client');
  11062. if (!modal) return;
  11063. const title = document.getElementById('modal-dhcp-title');
  11064. const idInput = document.getElementById('modal-dhcp-id');
  11065. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11066. const distInput = document.getElementById('modal-dhcp-distance');
  11067. const commentInput = document.getElementById('modal-dhcp-comment');
  11068. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11069. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11070. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11071. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11072. // Populate interfaces
  11073. if (ifaceSelect) {
  11074. let opts = '<option value="">Select interface...</option>';
  11075. const allIfaces = state.interfaces || [];
  11076. const allVlans = state.vlans || [];
  11077. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11078. // Group 1: Physical & Bridge Interfaces
  11079. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11080. allIfaces.forEach(i => {
  11081. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11082. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11083. });
  11084. opts += '</optgroup>';
  11085. // Group 2: VLAN Interfaces
  11086. if (allVlans.length > 0) {
  11087. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11088. allVlans.forEach(v => {
  11089. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11090. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11091. });
  11092. opts += '</optgroup>';
  11093. }
  11094. ifaceSelect.innerHTML = opts;
  11095. }
  11096. if (clientId) {
  11097. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11098. if (client) {
  11099. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11100. if (idInput) idInput.value = client.id;
  11101. if (ifaceSelect) {
  11102. ifaceSelect.value = client.interface;
  11103. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11104. }
  11105. if (distInput) distInput.value = client.default_route_distance || 1;
  11106. if (commentInput) commentInput.value = client.comment || '';
  11107. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11108. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11109. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11110. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11111. }
  11112. } else {
  11113. if (title) title.innerText = 'Add DHCP Client';
  11114. if (idInput) idInput.value = '';
  11115. if (ifaceSelect) {
  11116. ifaceSelect.value = '';
  11117. ifaceSelect.disabled = false;
  11118. }
  11119. if (distInput) distInput.value = 1;
  11120. if (commentInput) commentInput.value = '';
  11121. if (defRouteCheck) defRouteCheck.checked = true;
  11122. if (peerDnsCheck) peerDnsCheck.checked = true;
  11123. if (peerNtpCheck) peerNtpCheck.checked = true;
  11124. if (enabledCheck) enabledCheck.checked = true;
  11125. }
  11126. modal.classList.remove('hidden');
  11127. }
  11128. function openDHCPClientModalForIface(ifaceName) {
  11129. openDHCPClientModal();
  11130. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11131. if (ifaceSelect && ifaceName) {
  11132. ifaceSelect.value = ifaceName;
  11133. }
  11134. }
  11135. function closeDHCPClientModal() {
  11136. const modal = document.getElementById('modal-dhcp-client');
  11137. if (modal) modal.classList.add('hidden');
  11138. }
  11139. async function submitSaveDHCPClient(e) {
  11140. if (e) e.preventDefault();
  11141. const id = document.getElementById('modal-dhcp-id')?.value;
  11142. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11143. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11144. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11145. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11146. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11147. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11148. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11149. if (!id && !iface) {
  11150. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11151. return;
  11152. }
  11153. try {
  11154. let res;
  11155. if (id) {
  11156. // PUT update
  11157. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11158. method: 'PUT',
  11159. headers: { 'Content-Type': 'application/json' },
  11160. body: JSON.stringify({
  11161. enabled,
  11162. add_default_route: defRoute,
  11163. default_route_distance: distance,
  11164. use_peer_dns: peerDns,
  11165. use_peer_ntp: peerNtp,
  11166. comment
  11167. })
  11168. });
  11169. } else {
  11170. // POST create
  11171. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11172. method: 'POST',
  11173. headers: { 'Content-Type': 'application/json' },
  11174. body: JSON.stringify({
  11175. interface: iface,
  11176. enabled,
  11177. add_default_route: defRoute,
  11178. default_route_distance: distance,
  11179. use_peer_dns: peerDns,
  11180. use_peer_ntp: peerNtp,
  11181. comment
  11182. })
  11183. });
  11184. }
  11185. const data = await res.json();
  11186. if (!res.ok) {
  11187. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11188. return;
  11189. }
  11190. closeDHCPClientModal();
  11191. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11192. await loadDHCPClients();
  11193. fetchData(); // refresh interfaces list with new lease/status
  11194. } catch (err) {
  11195. showToast('Error', err.message, 'error');
  11196. }
  11197. }
  11198. async function toggleDHCPClientState(id, enabled) {
  11199. try {
  11200. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11201. method: 'POST',
  11202. headers: { 'Content-Type': 'application/json' },
  11203. body: JSON.stringify({ enabled })
  11204. });
  11205. const data = await res.json();
  11206. if (!res.ok) {
  11207. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11208. return;
  11209. }
  11210. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11211. await loadDHCPClients();
  11212. fetchData();
  11213. } catch (err) {
  11214. showToast('Error', err.message, 'error');
  11215. }
  11216. }
  11217. async function renewDHCPClient(id) {
  11218. try {
  11219. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11220. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11221. method: 'POST'
  11222. });
  11223. const data = await res.json();
  11224. if (!res.ok) {
  11225. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11226. return;
  11227. }
  11228. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11229. setTimeout(() => {
  11230. loadDHCPClients();
  11231. fetchData();
  11232. }, 1500);
  11233. } catch (err) {
  11234. showToast('Error', err.message, 'error');
  11235. }
  11236. }
  11237. async function releaseDHCPClient(id) {
  11238. try {
  11239. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11240. method: 'POST'
  11241. });
  11242. const data = await res.json();
  11243. if (!res.ok) {
  11244. showToast('Error', data.error || 'Failed to release lease', 'error');
  11245. return;
  11246. }
  11247. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11248. await loadDHCPClients();
  11249. fetchData();
  11250. } catch (err) {
  11251. showToast('Error', err.message, 'error');
  11252. }
  11253. }
  11254. async function deleteDHCPClient(id, ifaceName) {
  11255. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11256. return;
  11257. }
  11258. try {
  11259. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11260. method: 'DELETE'
  11261. });
  11262. const data = await res.json();
  11263. if (!res.ok) {
  11264. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11265. return;
  11266. }
  11267. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11268. await loadDHCPClients();
  11269. fetchData();
  11270. } catch (err) {
  11271. showToast('Error', err.message, 'error');
  11272. }
  11273. }
  11274. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  11275. function initTableSorting() {
  11276. document.querySelectorAll('table').forEach(setupSortableTable);
  11277. }
  11278. function setupSortableTable(table) {
  11279. const thead = table.querySelector('thead');
  11280. const tbody = table.querySelector('tbody');
  11281. if (!thead || !tbody) return;
  11282. const headerRows = thead.querySelectorAll('tr');
  11283. if (headerRows.length === 0) return;
  11284. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  11285. ths.forEach((th, colIdx) => {
  11286. if (th._sortBound) return;
  11287. th._sortBound = true;
  11288. const rawText = th.innerText.trim().toLowerCase();
  11289. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  11290. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  11291. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  11292. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  11293. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  11294. return;
  11295. }
  11296. th.classList.add('table-sortable', 'group');
  11297. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  11298. let icon = th.querySelector('.table-sort-icon');
  11299. if (!icon) {
  11300. icon = document.createElement('span');
  11301. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  11302. icon.innerHTML = '⇅';
  11303. th.appendChild(icon);
  11304. }
  11305. th.addEventListener('click', (e) => {
  11306. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  11307. handleHeaderClick(table, th, colIdx);
  11308. });
  11309. });
  11310. if (!tbody._sortObserved) {
  11311. tbody._sortObserved = true;
  11312. let sortDebounceTimer = null;
  11313. const observer = new MutationObserver((mutations) => {
  11314. if (tbody._isSorting) return;
  11315. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  11316. if (!hasChildChanges) return;
  11317. clearTimeout(sortDebounceTimer);
  11318. sortDebounceTimer = setTimeout(() => {
  11319. if (tbody._isSorting) return;
  11320. if (table._activeSort && table._activeSort.dir !== 'none') {
  11321. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  11322. } else {
  11323. tagOriginalRowOrder(tbody);
  11324. }
  11325. }, 10);
  11326. });
  11327. observer.observe(tbody, { childList: true });
  11328. }
  11329. tagOriginalRowOrder(tbody);
  11330. }
  11331. function tagOriginalRowOrder(tbody) {
  11332. let idx = 0;
  11333. Array.from(tbody.children).forEach(tr => {
  11334. if (!tr.querySelector('td[colspan]')) {
  11335. if (!tr.hasAttribute('data-orig-idx')) {
  11336. tr.setAttribute('data-orig-idx', idx++);
  11337. }
  11338. }
  11339. });
  11340. }
  11341. function handleHeaderClick(table, th, colIdx) {
  11342. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  11343. let newDir = 'asc';
  11344. if (currentSort.colIdx === colIdx) {
  11345. if (currentSort.dir === 'asc') newDir = 'desc';
  11346. else if (currentSort.dir === 'desc') newDir = 'none';
  11347. else newDir = 'asc';
  11348. } else {
  11349. newDir = 'asc';
  11350. }
  11351. table._activeSort = { colIdx, dir: newDir };
  11352. updateHeaderIcons(table, colIdx, newDir);
  11353. applyTableSort(table, colIdx, newDir, true);
  11354. }
  11355. function updateHeaderIcons(table, activeColIdx, dir) {
  11356. const thead = table.querySelector('thead');
  11357. if (!thead) return;
  11358. const ths = thead.querySelectorAll('th');
  11359. ths.forEach((th, idx) => {
  11360. const icon = th.querySelector('.table-sort-icon');
  11361. if (!icon) return;
  11362. if (idx === activeColIdx && dir !== 'none') {
  11363. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  11364. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  11365. th.classList.add('table-sorted-active');
  11366. } else {
  11367. icon.innerHTML = '⇅';
  11368. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  11369. th.classList.remove('table-sorted-active');
  11370. }
  11371. });
  11372. }
  11373. function applyTableSort(table, colIdx, dir, userInitiated) {
  11374. const tbody = table.querySelector('tbody');
  11375. if (!tbody || tbody.children.length <= 1) return;
  11376. tbody._isSorting = true;
  11377. tagOriginalRowOrder(tbody);
  11378. // Group parent rows and any attached drawer/sub-rows
  11379. const groups = [];
  11380. let currentGroup = null;
  11381. Array.from(tbody.children).forEach(tr => {
  11382. if (tr.querySelector('td[colspan]')) {
  11383. if (currentGroup) {
  11384. currentGroup.subRows.push(tr);
  11385. } else {
  11386. groups.push({ mainRow: tr, subRows: [] });
  11387. }
  11388. } else {
  11389. currentGroup = { mainRow: tr, subRows: [] };
  11390. groups.push(currentGroup);
  11391. }
  11392. });
  11393. if (dir === 'none') {
  11394. groups.sort((a, b) => {
  11395. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11396. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  11397. return idxA - idxB;
  11398. });
  11399. } else {
  11400. groups.sort((a, b) => {
  11401. const cellA = a.mainRow.children[colIdx];
  11402. const cellB = b.mainRow.children[colIdx];
  11403. const res = compareTableCells(cellA, cellB);
  11404. return dir === 'asc' ? res : -res;
  11405. });
  11406. }
  11407. // Re-append rows in sorted order
  11408. groups.forEach(g => {
  11409. tbody.appendChild(g.mainRow);
  11410. g.subRows.forEach(sub => tbody.appendChild(sub));
  11411. });
  11412. tbody._isSorting = false;
  11413. }
  11414. function getCellRawText(cell) {
  11415. if (!cell) return '';
  11416. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  11417. const input = cell.querySelector('input, select');
  11418. if (input) {
  11419. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  11420. return input.value;
  11421. }
  11422. return cell.innerText.trim();
  11423. }
  11424. function parseTrafficToNumber(str) {
  11425. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  11426. if (!m) return null;
  11427. const num = parseFloat(m[1].replace(/,/g, ''));
  11428. if (isNaN(num)) return null;
  11429. const unit = m[2].toUpperCase();
  11430. let mult = 1;
  11431. if (unit.startsWith('K')) mult = 1024;
  11432. else if (unit.startsWith('M')) mult = 1024 * 1024;
  11433. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  11434. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  11435. return num * mult;
  11436. }
  11437. function parseIpToNumber(str) {
  11438. const clean = str.replace(/^[!~]/, '').trim();
  11439. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  11440. if (!m) return null;
  11441. const o1 = parseInt(m[1], 10);
  11442. const o2 = parseInt(m[2], 10);
  11443. const o3 = parseInt(m[3], 10);
  11444. const o4 = parseInt(m[4], 10);
  11445. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  11446. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  11447. }
  11448. function parseCompoundPackets(str) {
  11449. const m = str.match(/^([\d,]+)p/);
  11450. if (!m) return null;
  11451. return parseInt(m[1].replace(/,/g, ''), 10);
  11452. }
  11453. function compareTableCells(cellA, cellB) {
  11454. const a = getCellRawText(cellA);
  11455. const b = getCellRawText(cellB);
  11456. if (a === '' && b !== '') return 1;
  11457. if (b === '' && a !== '') return -1;
  11458. if (a === b) return 0;
  11459. // 1. IP Addresses / CIDR
  11460. const ipA = parseIpToNumber(a);
  11461. const ipB = parseIpToNumber(b);
  11462. if (ipA !== null && ipB !== null) return ipA - ipB;
  11463. // 2. Packet counts (e.g. "1,250p / 45 KB")
  11464. const pktA = parseCompoundPackets(a);
  11465. const pktB = parseCompoundPackets(b);
  11466. if (pktA !== null && pktB !== null) return pktA - pktB;
  11467. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  11468. const trafA = parseTrafficToNumber(a);
  11469. const trafB = parseTrafficToNumber(b);
  11470. if (trafA !== null && trafB !== null) return trafA - trafB;
  11471. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  11472. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11473. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  11474. const numA = Number(cleanNumA);
  11475. const numB = Number(cleanNumB);
  11476. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  11477. return numA - numB;
  11478. }
  11479. // 5. Natural case-insensitive string compare
  11480. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  11481. }
  11482. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  11483. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  11484. const docTableObserver = new MutationObserver((mutations) => {
  11485. let needsInit = false;
  11486. for (const m of mutations) {
  11487. for (const node of m.addedNodes) {
  11488. if (node.nodeType === 1) {
  11489. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  11490. needsInit = true;
  11491. break;
  11492. }
  11493. }
  11494. }
  11495. if (needsInit) break;
  11496. }
  11497. if (needsInit) {
  11498. initTableSorting();
  11499. }
  11500. });
  11501. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  11502. }