app.js 574 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620
  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. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. // Live polling every 2.5 seconds
  80. setInterval(() => {
  81. if (state.isPolling) {
  82. fetchData(false);
  83. }
  84. }, 2500);
  85. });
  86. // Navigation Handler
  87. function navigate(tabName) {
  88. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  89. navigate('bgp');
  90. return;
  91. }
  92. if (tabName === 'vlans') {
  93. navigate('interfaces');
  94. return;
  95. }
  96. state.activeTab = tabName;
  97. window.location.hash = tabName;
  98. // Update nav links styling
  99. document.querySelectorAll('.nav-link').forEach(link => {
  100. 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';
  101. });
  102. const activeNav = document.getElementById(`nav-${tabName}`);
  103. if (activeNav) {
  104. 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';
  105. }
  106. // Update page headers
  107. const titles = {
  108. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  109. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  110. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  111. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  112. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  113. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  114. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  115. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  116. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  117. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  118. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  119. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  120. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  121. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  122. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  123. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  124. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  125. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  126. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  127. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  128. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  129. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  130. };
  131. const header = titles[tabName] || titles.dashboard;
  132. const pTitle = document.getElementById('page-title');
  133. if (pTitle) pTitle.innerText = header.title;
  134. const pSub = document.getElementById('page-subtitle');
  135. if (pSub) pSub.innerText = header.sub;
  136. // Toggle sections dynamically for all section elements
  137. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  138. if (el.id === `section-${tabName}`) {
  139. el.classList.remove('hidden');
  140. } else {
  141. el.classList.add('hidden');
  142. }
  143. });
  144. if (tabName === 'bridge') loadBridge();
  145. if (tabName === 'firewall') loadFirewall();
  146. if (tabName === 'routes') loadRoutes();
  147. if (tabName === 'bgp') {
  148. loadDynamicRouting();
  149. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  150. }
  151. if (tabName === 'ospf') {
  152. loadDynamicRouting();
  153. switchOspfTab(state.activeOspfTab || 'instances');
  154. }
  155. if (tabName === 'routing-filters') loadDynamicRouting();
  156. if (tabName === 'dynamic-routing') loadDynamicRouting();
  157. if (tabName === 'ppp') loadPPP();
  158. if (tabName === 'eoip') loadEoIP();
  159. if (tabName === 'aerotun') loadAeroTUN();
  160. if (tabName === 'persistence') loadDebianConfig();
  161. if (tabName === 'pppoe') loadPPPoE();
  162. if (tabName === 'wireguard') loadWireGuard();
  163. if (tabName === 'ipsec') loadIPSec();
  164. if (tabName === 'l2tp') loadL2TP();
  165. if (tabName === 'pptp') loadPPTP();
  166. if (tabName === 'tools') loadToolsView();
  167. if (tabName === 'dhcp-client') loadDHCPClients();
  168. if (tabName === 'dhcp-server') loadDHCPServer();
  169. setTimeout(initTableSorting, 50);
  170. }
  171. // Fetch all core system, network and VPN telemetry
  172. async function fetchData(isManual = false) {
  173. const spinner = document.getElementById('refresh-spinner');
  174. if (isManual && spinner) spinner.classList.add('animate-spin');
  175. try {
  176. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  177. fetch(`${API_BASE}/system/status`),
  178. fetch(`${API_BASE}/interfaces`),
  179. fetch(`${API_BASE}/vlans`),
  180. fetch(`${API_BASE}/vpn/status`),
  181. fetch(`${API_BASE}/firewall/summary`),
  182. fetch(`${API_BASE}/routing/dynamic/summary`),
  183. fetch(`${API_BASE}/bridge/summary`),
  184. fetch(`${API_BASE}/dhcp/clients/summary`),
  185. fetch(`${API_BASE}/dhcp/clients`)
  186. ]);
  187. if (dhcpSumRes && dhcpSumRes.ok) {
  188. state.dhcpSummary = await dhcpSumRes.json();
  189. const bDhcp = document.getElementById('badge-dhcp-client-count');
  190. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  191. }
  192. if (dhcpClientsRes && dhcpClientsRes.ok) {
  193. state.dhcpClients = await dhcpClientsRes.json();
  194. }
  195. if (brSummaryRes.ok) {
  196. state.bridgeSummary = await brSummaryRes.json();
  197. const bBridge = document.getElementById('badge-bridge-count');
  198. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  199. const sBr = document.getElementById('bridge-stat-bridges');
  200. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  201. const sPorts = document.getElementById('bridge-stat-ports');
  202. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  203. const sHosts = document.getElementById('bridge-stat-hosts');
  204. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  205. }
  206. if (statusRes.ok) state.systemStatus = await statusRes.json();
  207. if (ifacesRes.ok) {
  208. const ifacesData = await ifacesRes.json();
  209. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  210. state.interfaces = rawIfaces.filter(i => {
  211. if (!i.name) return false;
  212. if (i.name.startsWith('ep_')) return false;
  213. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  214. });
  215. try { populateToolsInterfaces(); } catch (e) {}
  216. }
  217. if (vlansRes.ok) {
  218. const vlansData = await vlansRes.json();
  219. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  220. }
  221. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  222. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  223. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  224. updateSystemMetrics();
  225. updateBadges();
  226. if (state.activeTab === 'dashboard') renderDashboard();
  227. if (state.activeTab === 'interfaces') renderInterfacesList();
  228. if (state.activeTab === 'vlans') renderVlansList();
  229. if (state.activeTab === 'firewall') loadFirewall(false);
  230. if (state.activeTab === 'routes') loadRoutes(false);
  231. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  232. if (state.activeTab === 'ppp') loadPPP(false);
  233. if (state.activeTab === 'eoip') loadEoIP(false);
  234. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  235. if (state.activeTab === 'pppoe') loadPPPoE(false);
  236. if (state.activeTab === 'wireguard') loadWireGuard(false);
  237. if (state.activeTab === 'ipsec') loadIPSec(false);
  238. if (state.activeTab === 'l2tp') loadL2TP(false);
  239. if (state.activeTab === 'pptp') loadPPTP(false);
  240. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  241. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  242. } catch (err) {
  243. console.error('Failed to fetch router state:', err);
  244. } finally {
  245. if (isManual && spinner) {
  246. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  247. }
  248. }
  249. }
  250. // Update Top KPI and Sidebar Telemetry
  251. function updateSystemMetrics() {
  252. const s = state.systemStatus;
  253. const v = state.vpnStatus;
  254. if (!s) return;
  255. // Sidebar Host & Uptime
  256. const sideHost = document.getElementById('side-hostname');
  257. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  258. const sideUp = document.getElementById('side-uptime');
  259. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  260. const sideGw = document.getElementById('side-gateway-ip');
  261. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  262. // Compute CPU Metrics
  263. let cpuPct = 0;
  264. if (s.cpu_pct !== undefined) {
  265. cpuPct = s.cpu_pct;
  266. } else if (s.cpu_load && s.cpu_load.length > 0) {
  267. const cores = s.cpu_cores || 1;
  268. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  269. }
  270. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  271. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  272. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  273. // Sidebar CPU
  274. const sideCpuVal = document.getElementById('side-cpu-val');
  275. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  276. const sideCpuBar = document.getElementById('side-cpu-bar');
  277. if (sideCpuBar) {
  278. sideCpuBar.style.width = cpuWidth;
  279. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  280. }
  281. // Dashboard CPU Card
  282. const dashCpuVal = document.getElementById('dash-cpu-val');
  283. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  284. const dashCpuBar = document.getElementById('dash-cpu-bar');
  285. if (dashCpuBar) {
  286. dashCpuBar.style.width = cpuWidth;
  287. if (cpuPct > 85) {
  288. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  289. } else if (cpuPct > 65) {
  290. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  291. } else {
  292. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  293. }
  294. }
  295. const dashCpuCores = document.getElementById('dash-cpu-cores');
  296. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  297. const dashCpuLoad = document.getElementById('dash-cpu-load');
  298. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  299. const dashCpuStatus = document.getElementById('dash-cpu-status');
  300. if (dashCpuStatus) {
  301. if (cpuPct > 85) {
  302. dashCpuStatus.innerText = 'High';
  303. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  304. } else if (cpuPct > 65) {
  305. dashCpuStatus.innerText = 'Heavy';
  306. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  307. } else {
  308. dashCpuStatus.innerText = 'Normal';
  309. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  310. }
  311. }
  312. // Compute RAM Metrics
  313. const memPct = Math.round(s.mem_usage_pct || 0);
  314. const memPctStr = `${memPct}%`;
  315. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  316. const usedMB = s.mem_used_mb || 0;
  317. const totalMB = s.mem_total_mb || 0;
  318. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  319. function fmtMemMB(mb) {
  320. if (mb >= 1024) {
  321. return `${(mb / 1024).toFixed(1)} GB`;
  322. }
  323. return `${mb} MB`;
  324. }
  325. // Sidebar RAM
  326. const sideRamVal = document.getElementById('side-ram-val');
  327. if (sideRamVal) sideRamVal.innerText = memPctStr;
  328. const sideRamBar = document.getElementById('side-ram-bar');
  329. if (sideRamBar) sideRamBar.style.width = memWidth;
  330. // Dashboard RAM Card
  331. const dashRamVal = document.getElementById('dash-ram-val');
  332. if (dashRamVal) dashRamVal.innerText = memPctStr;
  333. const dashRamBar = document.getElementById('dash-ram-bar');
  334. if (dashRamBar) {
  335. dashRamBar.style.width = memWidth;
  336. if (memPct > 85) {
  337. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  338. } else if (memPct > 70) {
  339. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  340. } else {
  341. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  342. }
  343. }
  344. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  345. if (dashRamUsedTotal) {
  346. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  347. }
  348. const dashRamFree = document.getElementById('dash-ram-free');
  349. if (dashRamFree) {
  350. dashRamFree.innerText = fmtMemMB(freeMB);
  351. }
  352. const dashRamStatus = document.getElementById('dash-ram-status');
  353. if (dashRamStatus) {
  354. if (memPct > 85) {
  355. dashRamStatus.innerText = 'High';
  356. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  357. } else {
  358. dashRamStatus.innerText = 'Active';
  359. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  360. }
  361. }
  362. // Legacy Dashboard Stats (Safe checks)
  363. const elIfacesUp = document.getElementById('stat-ifaces-up');
  364. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  365. const elIfacesTot = document.getElementById('stat-ifaces-total');
  366. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  367. const elIfacesDown = document.getElementById('stat-ifaces-down');
  368. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  369. const elVlans = document.getElementById('stat-vlans-count');
  370. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  371. // VPN Status Indicators
  372. if (v) {
  373. const totalActive = v.total_active_tunnels || 0;
  374. const statVpnActive = document.getElementById('stat-vpn-active');
  375. if (statVpnActive) statVpnActive.innerText = totalActive;
  376. const tunnelsDot = document.getElementById('tunnels-dot');
  377. const tunnelsLabel = document.getElementById('tunnels-label');
  378. if (tunnelsDot && tunnelsLabel) {
  379. if (totalActive > 0) {
  380. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  381. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  382. } else {
  383. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  384. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  385. }
  386. }
  387. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  388. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  389. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  390. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  391. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  392. }
  393. // Total Live Bandwidth Rate
  394. let totalRx = 0;
  395. let totalTx = 0;
  396. (state.interfaces || []).forEach(i => {
  397. if (i.rate) {
  398. totalRx += i.rate.rx_bytes_sec || 0;
  399. totalTx += i.rate.tx_bytes_sec || 0;
  400. }
  401. });
  402. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  403. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  404. }
  405. function setDotBadge(id, active) {
  406. const el = document.getElementById(id);
  407. if (!el) return;
  408. if (active) {
  409. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  410. } else {
  411. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  412. }
  413. }
  414. function updateBadges() {
  415. const bIfaces = document.getElementById('badge-ifaces-count');
  416. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  417. const bVlans = document.getElementById('badge-vlans-count');
  418. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  419. if (state.fwSummary) {
  420. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  421. const badgeFw = document.getElementById('badge-firewall-count');
  422. if (badgeFw) badgeFw.innerText = totalFwRules;
  423. }
  424. if (state.vpnStatus) {
  425. const v = state.vpnStatus;
  426. const bEoIP = document.getElementById('badge-eoip-count');
  427. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  428. const bAero = document.getElementById('badge-aerotun-count');
  429. if (bAero) bAero.innerText = v.total_aerotun || 0;
  430. const bPPPSess = document.getElementById('badge-ppp-sessions');
  431. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  432. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  433. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  434. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  435. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  436. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  437. }
  438. if (state.dynSummary) {
  439. const d = state.dynSummary;
  440. setDotBadge('badge-bgp-dot', d.bgp_running);
  441. setDotBadge('badge-ospf-dot', d.ospf_running);
  442. const bBgp = document.getElementById('badge-bgp-count');
  443. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  444. const bOspf = document.getElementById('badge-ospf-count');
  445. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  446. const bFilters = document.getElementById('badge-filters-count');
  447. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  448. }
  449. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  450. if (bDhcpServer) {
  451. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  452. }
  453. }
  454. // Render Dashboard View
  455. function renderDashboard() {
  456. const matrix = document.getElementById('port-matrix');
  457. matrix.innerHTML = '';
  458. (state.interfaces || []).forEach(iface => {
  459. const isUp = iface.state === 'UP';
  460. const isVlan = iface.is_vlan;
  461. const portCard = document.createElement('div');
  462. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  463. isUp
  464. ? (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')
  465. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  466. }`;
  467. portCard.onclick = () => openIfaceModal(iface.name);
  468. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  469. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  470. portCard.innerHTML = `
  471. <div class="flex items-center justify-between mb-2">
  472. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  473. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  474. </div>
  475. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  476. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  477. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  478. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  479. </div>
  480. `;
  481. matrix.appendChild(portCard);
  482. });
  483. const ifaceTbody = document.getElementById('quick-interfaces-table');
  484. if (ifaceTbody) {
  485. ifaceTbody.innerHTML = '';
  486. (state.interfaces || []).forEach(i => {
  487. const isUp = i.state === 'UP';
  488. const tr = document.createElement('tr');
  489. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  490. tr.onclick = () => openIfaceModal(i.name);
  491. const rxStr = i.rate?.rx_human || '0 B/s';
  492. const txStr = i.rate?.tx_human || '0 B/s';
  493. tr.innerHTML = `
  494. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  495. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  496. <span>${i.name}</span>
  497. </td>
  498. <td class="py-2.5 text-slate-300 font-sans">
  499. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  500. </td>
  501. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  502. <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>
  503. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  504. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  505. </td>
  506. <td class="py-2.5 text-right font-sans font-semibold">
  507. <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>
  508. </td>
  509. `;
  510. ifaceTbody.appendChild(tr);
  511. });
  512. }
  513. const vlanTbody = document.getElementById('quick-vlans-table');
  514. if (vlanTbody) {
  515. vlanTbody.innerHTML = '';
  516. }
  517. }
  518. // Expand / Collapse Handlers
  519. function toggleExpand(parentName) {
  520. if (state.expandedParents.has(parentName)) {
  521. state.expandedParents.delete(parentName);
  522. } else {
  523. state.expandedParents.add(parentName);
  524. }
  525. renderInterfacesList();
  526. }
  527. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  528. function supportsVLAN(iface) {
  529. if (!iface) return false;
  530. if (iface.is_vlan) return false;
  531. const name = (iface.name || '').toLowerCase();
  532. const type = (iface.type || '').toLowerCase();
  533. const role = (iface.role || '').toLowerCase();
  534. // Exclude loopback
  535. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  536. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  537. if (type === 'wireguard' || name.startsWith('wg')) return false;
  538. // Exclude PPP / PPPoE
  539. if (type === 'ppp' || name.startsWith('ppp')) return false;
  540. // Exclude other Layer 3 tunnels and dummy devices
  541. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  542. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  543. return false;
  544. }
  545. // If name already contains a dot, it's already a sub-interface
  546. if (name.includes('.')) return false;
  547. return true;
  548. }
  549. // Expand / Collapse Handlers
  550. function toggleExpand(parentName) {
  551. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  552. if (childVlans.length === 0) {
  553. // Cannot expand an interface with no VLANs
  554. state.expandedParents.delete(parentName);
  555. return;
  556. }
  557. if (state.expandedParents.has(parentName)) {
  558. state.expandedParents.delete(parentName);
  559. } else {
  560. state.expandedParents.add(parentName);
  561. }
  562. renderInterfacesList();
  563. }
  564. function expandAllIfaces(expand) {
  565. if (expand) {
  566. (state.interfaces || []).forEach(i => {
  567. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  568. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  569. });
  570. } else {
  571. state.expandedParents.clear();
  572. }
  573. renderInterfacesList();
  574. }
  575. // Filter and Render Hierarchical Interfaces List
  576. function filterIfaces(filter) {
  577. state.ifaceFilter = filter || 'all';
  578. renderInterfacesList();
  579. }
  580. function renderInterfacesList() {
  581. const tbody = document.getElementById('interfaces-tree-tbody');
  582. const emptyState = document.getElementById('interfaces-empty-state');
  583. const summary = document.getElementById('ifaces-list-summary');
  584. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  585. tbody.innerHTML = '';
  586. const allIfaces = state.interfaces || [];
  587. const allVlans = state.vlans || [];
  588. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  589. const filteredParents = parentIfaces.filter(parent => {
  590. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  591. if (query) {
  592. const matchName = parent.name.toLowerCase().includes(query);
  593. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  594. const matchRole = (parent.role || '').toLowerCase().includes(query);
  595. const matchType = (parent.type || '').toLowerCase().includes(query);
  596. const matchVlan = childVlans.some(v =>
  597. v.name.toLowerCase().includes(query) ||
  598. String(v.vlan_id).includes(query) ||
  599. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  600. (v.description || '').toLowerCase().includes(query)
  601. );
  602. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  603. }
  604. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  605. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  606. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  607. return true;
  608. });
  609. if (summary) {
  610. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  611. }
  612. if (filteredParents.length === 0) {
  613. emptyState?.classList.remove('hidden');
  614. return;
  615. }
  616. emptyState?.classList.add('hidden');
  617. filteredParents.forEach(parent => {
  618. const isUp = parent.state === 'UP';
  619. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  620. const hasVlans = childVlans.length > 0;
  621. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  622. const canHaveVlan = supportsVLAN(parent);
  623. const parentRow = document.createElement('tr');
  624. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  625. parentRow.innerHTML = `
  626. <td class="py-3 px-3 text-center">
  627. ${hasVlans ? `
  628. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  629. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  630. <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">
  631. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  632. </svg>
  633. </button>
  634. ` : `
  635. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  636. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  637. </div>
  638. `}
  639. </td>
  640. <td class="py-3 px-4">
  641. <div class="flex items-center space-x-2.5">
  642. <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">
  643. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  644. </div>
  645. <div>
  646. <div class="flex items-center gap-2">
  647. ${hasVlans ? `
  648. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  649. <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>
  650. ` : `
  651. <span class="font-bold text-white text-sm">${parent.name}</span>
  652. <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>
  653. `}
  654. </div>
  655. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  656. </div>
  657. </div>
  658. </td>
  659. <td class="py-3 px-4 font-sans">
  660. <div class="flex items-center gap-1.5">
  661. <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>
  662. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  663. </div>
  664. </td>
  665. <td class="py-3 px-4">
  666. ${parent.ipv4 && parent.ipv4.length > 0
  667. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  668. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  669. }
  670. ${(() => {
  671. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  672. if (!c) return '';
  673. 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');
  674. 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>`;
  675. })()}
  676. </td>
  677. <td class="py-3 px-4 text-slate-400 text-[11px]">
  678. <div>${parent.mac || 'N/A'}</div>
  679. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  680. </td>
  681. <td class="py-3 px-4 text-[11px]">
  682. <div class="flex items-center space-x-2">
  683. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  684. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  685. </div>
  686. </td>
  687. <td class="py-3 px-4 font-sans">
  688. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  689. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  690. 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'
  691. }" title="Click to toggle link status">
  692. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  693. <span>${parent.state}</span>
  694. </button>
  695. </td>
  696. <td class="py-3 px-4 text-right space-x-2 font-sans">
  697. ${(() => {
  698. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  699. if (c) {
  700. 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>`;
  701. }
  702. 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>`;
  703. })()}
  704. ${canHaveVlan ? `
  705. <button onclick="openVlanModal('${parent.name}')"
  706. 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">
  707. + Add VLAN
  708. </button>
  709. ` : ''}
  710. <button onclick="openIfaceModal('${parent.name}')"
  711. 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">
  712. Configure
  713. </button>
  714. </td>
  715. `;
  716. tbody.appendChild(parentRow);
  717. if (isExpanded) {
  718. const drawerRow = document.createElement('tr');
  719. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  720. const drawerCell = document.createElement('td');
  721. drawerCell.colSpan = 8;
  722. drawerCell.className = 'p-0';
  723. drawerCell.innerHTML = `
  724. <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">
  725. <div class="flex items-center justify-between mb-3">
  726. <div class="flex items-center space-x-3">
  727. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  728. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  729. </span>
  730. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  731. ${childVlans.length} Attached
  732. </span>
  733. </div>
  734. <button onclick="openVlanModal('${parent.name}')"
  735. 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">
  736. <span>+ Create VLAN on ${parent.name}</span>
  737. </button>
  738. </div>
  739. ${childVlans.length === 0 ? `
  740. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  741. <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>
  742. <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">
  743. <span>+ Create Your First VLAN on ${parent.name}</span>
  744. </button>
  745. </div>
  746. ` : `
  747. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  748. <table class="w-full text-left text-xs font-mono">
  749. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  750. <tr>
  751. <th class="py-2.5 px-4">VLAN ID</th>
  752. <th class="py-2.5 px-4">Interface Device</th>
  753. <th class="py-2.5 px-4">Subnet Gateway</th>
  754. <th class="py-2.5 px-4">Role / Alias</th>
  755. <th class="py-2.5 px-4">MTU</th>
  756. <th class="py-2.5 px-4">Throughput</th>
  757. <th class="py-2.5 px-4">Status</th>
  758. <th class="py-2.5 px-4 text-right">Actions</th>
  759. </tr>
  760. </thead>
  761. <tbody class="divide-y divide-slate-800/70">
  762. ${childVlans.map(v => {
  763. const isVlanUp = v.state === 'UP';
  764. return `
  765. <tr class="hover:bg-slate-800/40 transition">
  766. <td class="py-2.5 px-4">
  767. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  768. VLAN ${v.vlan_id}
  769. </span>
  770. </td>
  771. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  772. <span class="text-cyan-500">└─</span>
  773. <span>${v.name}</span>
  774. </td>
  775. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  776. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (!c) return '';
  780. 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';
  781. 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>`;
  782. })()}
  783. </td>
  784. <td class="py-2.5 px-4 font-sans text-slate-300">
  785. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  786. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  787. </td>
  788. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  789. <td class="py-2.5 px-4 text-[11px]">
  790. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  791. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  792. </td>
  793. <td class="py-2.5 px-4 font-sans">
  794. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  795. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  796. 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'
  797. }">
  798. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  799. <span>${v.state}</span>
  800. </button>
  801. </td>
  802. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  803. ${(() => {
  804. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  805. if (c) {
  806. 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>`;
  807. }
  808. 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>`;
  809. })()}
  810. <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>
  811. <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>
  812. </td>
  813. </tr>
  814. `;
  815. }).join('')}
  816. </tbody>
  817. </table>
  818. </div>
  819. `}
  820. </div>
  821. `;
  822. drawerRow.appendChild(drawerCell);
  823. tbody.appendChild(drawerRow);
  824. }
  825. });
  826. }
  827. // Render VLANs Dedicated View
  828. function renderVlansList() {
  829. const tbody = document.getElementById('vlans-table-body');
  830. if (!tbody) return;
  831. const emptyState = document.getElementById('vlans-empty-state');
  832. const countBadge = document.getElementById('vlans-table-count');
  833. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  834. tbody.innerHTML = '';
  835. const allVlans = state.vlans || [];
  836. if (countBadge) countBadge.innerText = allVlans.length;
  837. const filtered = allVlans.filter(v => {
  838. if (!query) return true;
  839. return v.name.toLowerCase().includes(query) ||
  840. String(v.vlan_id).includes(query) ||
  841. (v.description || '').toLowerCase().includes(query) ||
  842. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  843. });
  844. if (allVlans.length === 0) {
  845. emptyState.classList.remove('hidden');
  846. return;
  847. }
  848. emptyState.classList.add('hidden');
  849. filtered.forEach(v => {
  850. const isUp = v.state === 'UP';
  851. const tr = document.createElement('tr');
  852. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  853. tr.innerHTML = `
  854. <td class="py-3 px-4">
  855. <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">
  856. VLAN ${v.vlan_id}
  857. </span>
  858. </td>
  859. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  860. <td class="py-3 px-4 text-slate-300">
  861. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  862. </td>
  863. <td class="py-3 px-4 text-emerald-400 font-medium">
  864. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  865. </td>
  866. <td class="py-3 px-4 text-slate-300 font-sans">
  867. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  868. </td>
  869. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  870. <td class="py-3 px-4 font-sans">
  871. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  872. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  873. 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'
  874. }">
  875. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  876. <span>${v.state}</span>
  877. </button>
  878. </td>
  879. <td class="py-3 px-4 text-right space-x-2 font-sans">
  880. <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>
  881. <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>
  882. </td>
  883. `;
  884. tbody.appendChild(tr);
  885. });
  886. }
  887. // Toggle interface UP / DOWN
  888. async function toggleInterfaceState(name, newState) {
  889. try {
  890. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  891. method: 'POST',
  892. headers: { 'Content-Type': 'application/json' },
  893. body: JSON.stringify({ state: newState })
  894. });
  895. const data = await res.json();
  896. if (res.ok) {
  897. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  898. fetchData(false);
  899. } else {
  900. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  901. }
  902. } catch (err) {
  903. showToast('Error', err.message, 'error');
  904. }
  905. }
  906. // ---------------- MikroTik Flag & Utilities ----------------
  907. function renderMikroTikFlag(running, disabled) {
  908. if (running) {
  909. 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>`;
  910. }
  911. if (disabled) {
  912. 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>`;
  913. }
  914. 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>`;
  915. }
  916. function copyToClipboard(text, label = 'Text') {
  917. navigator.clipboard.writeText(text).then(() => {
  918. showToast('Copied', `${label} copied to clipboard`, 'success');
  919. }).catch(() => {
  920. prompt('Copy value:', text);
  921. });
  922. }
  923. // ======================== PPP Profiles Shared Helper ========================
  924. async function fetchPPPProfilesList() {
  925. try {
  926. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  927. if (res.ok) {
  928. state.pppProfiles = await res.json();
  929. }
  930. } catch (err) {
  931. console.error('Failed to load PPP profiles:', err);
  932. }
  933. }
  934. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  935. const sel = document.getElementById(selectId);
  936. if (!sel) return;
  937. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  938. { name: 'default', use_encryption: 'no' },
  939. { name: 'default-encryption', use_encryption: 'required' }
  940. ];
  941. sel.innerHTML = '';
  942. profiles.forEach(p => {
  943. const opt = document.createElement('option');
  944. opt.value = p.name;
  945. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  946. opt.innerText = `${p.name}${encBadge}`;
  947. sel.appendChild(opt);
  948. });
  949. if (selectedVal) {
  950. sel.value = selectedVal;
  951. } else {
  952. sel.value = defaultVal;
  953. }
  954. if (!sel.value && sel.options.length > 0) {
  955. sel.selectedIndex = 0;
  956. }
  957. }
  958. // ======================== PPPoE Multi-Instance ========================
  959. async function loadPPPoE(populateInputs = true) {
  960. try {
  961. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  962. await fetchPPPProfilesList();
  963. }
  964. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  965. const list = await res.json();
  966. state.pppoeList = Array.isArray(list) ? list : [];
  967. const badge = document.getElementById('pppoe-count-badge');
  968. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  969. const tbody = document.getElementById('pppoe-table-body');
  970. const empty = document.getElementById('pppoe-empty');
  971. if (!tbody) return;
  972. tbody.innerHTML = '';
  973. if (state.pppoeList.length === 0) {
  974. if (empty) empty.classList.remove('hidden');
  975. } else {
  976. if (empty) empty.classList.add('hidden');
  977. state.pppoeList.forEach(inst => {
  978. const tr = document.createElement('tr');
  979. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  980. tr.innerHTML = `
  981. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  982. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  983. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  984. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  985. <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>
  986. <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>
  987. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  988. <td class="py-2.5 px-3 text-center">
  989. <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'}">
  990. ${inst.default_route ? 'Yes' : 'No'}
  991. </span>
  992. </td>
  993. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  994. ${inst.running ? `
  995. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  996. ` : `
  997. <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>
  998. `}
  999. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1000. ${inst.disabled ? 'Enable' : 'Disable'}
  1001. </button>
  1002. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1003. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1004. </td>
  1005. `;
  1006. tbody.appendChild(tr);
  1007. });
  1008. }
  1009. } catch (err) {
  1010. console.error('Failed to load PPPoE:', err);
  1011. }
  1012. }
  1013. function openAddPPPoEModal() {
  1014. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1015. document.getElementById('pppoe-modal-edit-orig').value = '';
  1016. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1017. document.getElementById('pppoe-modal-name').readOnly = false;
  1018. document.getElementById('pppoe-modal-user').value = '';
  1019. document.getElementById('pppoe-modal-pass').value = '';
  1020. document.getElementById('pppoe-modal-service').value = '';
  1021. document.getElementById('pppoe-modal-mtu').value = '1492';
  1022. document.getElementById('pppoe-modal-defroute').checked = true;
  1023. document.getElementById('pppoe-modal-reconnect').checked = true;
  1024. document.getElementById('pppoe-modal-disabled').checked = false;
  1025. // Populate profiles
  1026. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1027. // Populate interfaces
  1028. const sel = document.getElementById('pppoe-modal-iface');
  1029. sel.innerHTML = '';
  1030. (state.interfaces || []).forEach(i => {
  1031. if (i.name === 'lo') return;
  1032. const opt = document.createElement('option');
  1033. opt.value = i.name;
  1034. opt.innerText = `${i.name} (${i.role || i.type})`;
  1035. sel.appendChild(opt);
  1036. });
  1037. document.getElementById('pppoe-modal').classList.remove('hidden');
  1038. }
  1039. function openEditPPPoEModal(name) {
  1040. const inst = (state.pppoeList || []).find(i => i.name === name);
  1041. if (!inst) return;
  1042. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1043. document.getElementById('pppoe-modal-edit-orig').value = name;
  1044. document.getElementById('pppoe-modal-name').value = inst.name;
  1045. document.getElementById('pppoe-modal-name').readOnly = true;
  1046. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1047. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1048. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1049. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1050. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1051. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1052. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1053. // Populate profiles
  1054. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1055. const sel = document.getElementById('pppoe-modal-iface');
  1056. sel.innerHTML = '';
  1057. (state.interfaces || []).forEach(i => {
  1058. if (i.name === 'lo') return;
  1059. const opt = document.createElement('option');
  1060. opt.value = i.name;
  1061. opt.innerText = `${i.name} (${i.role || i.type})`;
  1062. if (i.name === inst.interface) opt.selected = true;
  1063. sel.appendChild(opt);
  1064. });
  1065. document.getElementById('pppoe-modal').classList.remove('hidden');
  1066. }
  1067. function closePPPoEModal() {
  1068. document.getElementById('pppoe-modal').classList.add('hidden');
  1069. }
  1070. async function submitSavePPPoE(e) {
  1071. e.preventDefault();
  1072. const name = document.getElementById('pppoe-modal-name').value.trim();
  1073. const iface = document.getElementById('pppoe-modal-iface').value;
  1074. const user = document.getElementById('pppoe-modal-user').value.trim();
  1075. const pass = document.getElementById('pppoe-modal-pass').value;
  1076. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1077. const service = document.getElementById('pppoe-modal-service').value.trim();
  1078. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1079. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1080. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1081. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1082. try {
  1083. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1084. method: 'POST',
  1085. headers: { 'Content-Type': 'application/json' },
  1086. body: JSON.stringify({
  1087. name,
  1088. interface: iface,
  1089. username: user,
  1090. password: pass,
  1091. profile: profile,
  1092. service_name: service,
  1093. mtu,
  1094. default_route: defRoute,
  1095. auto_reconnect: reconnect,
  1096. disabled
  1097. })
  1098. });
  1099. if (res.ok) {
  1100. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1101. closePPPoEModal();
  1102. loadPPPoE(false);
  1103. fetchData(false);
  1104. } else {
  1105. const err = await res.json();
  1106. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1107. }
  1108. } catch (err) {
  1109. showToast('Error', err.message, 'error');
  1110. }
  1111. }
  1112. async function connectPPPoEInstance(name) {
  1113. try {
  1114. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1115. if (res.ok) {
  1116. showToast('Connecting', `Dialing ${name}...`, 'info');
  1117. setTimeout(() => loadPPPoE(false), 2000);
  1118. }
  1119. } catch (err) {
  1120. showToast('Error', err.message, 'error');
  1121. }
  1122. }
  1123. async function disconnectPPPoEInstance(name) {
  1124. try {
  1125. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1126. if (res.ok) {
  1127. showToast('Disconnected', `${name} session terminated`, 'info');
  1128. setTimeout(() => loadPPPoE(false), 1000);
  1129. }
  1130. } catch (err) {
  1131. showToast('Error', err.message, 'error');
  1132. }
  1133. }
  1134. async function togglePPPoEState(name, enable) {
  1135. try {
  1136. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1137. method: 'POST',
  1138. headers: { 'Content-Type': 'application/json' },
  1139. body: JSON.stringify({ enabled: enable })
  1140. });
  1141. if (res.ok) {
  1142. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1143. loadPPPoE(false);
  1144. }
  1145. } catch (err) {
  1146. showToast('Error', err.message, 'error');
  1147. }
  1148. }
  1149. async function deletePPPoEInstance(name) {
  1150. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1151. try {
  1152. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1153. if (res.ok) {
  1154. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1155. loadPPPoE(false);
  1156. fetchData(false);
  1157. }
  1158. } catch (err) {
  1159. showToast('Error', err.message, 'error');
  1160. }
  1161. }
  1162. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1163. state.wgSubTab = 'ifaces';
  1164. function switchWGSubTab(tab) {
  1165. state.wgSubTab = tab;
  1166. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1167. const peersPanel = document.getElementById('wg-subtab-peers');
  1168. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1169. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1170. if (tab === 'ifaces') {
  1171. ifacesPanel?.classList.remove('hidden');
  1172. peersPanel?.classList.add('hidden');
  1173. 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';
  1174. 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';
  1175. } else {
  1176. ifacesPanel?.classList.add('hidden');
  1177. peersPanel?.classList.remove('hidden');
  1178. 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';
  1179. 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';
  1180. renderWGPeers();
  1181. }
  1182. }
  1183. async function loadWireGuard(populateInputs = true) {
  1184. try {
  1185. const [ifacesRes, peersRes] = await Promise.all([
  1186. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1187. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1188. ]);
  1189. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1190. const peers = peersRes.ok ? await peersRes.json() : [];
  1191. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1192. state.wgPeers = Array.isArray(peers) ? peers : [];
  1193. // Badges
  1194. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1195. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1196. const peersCountBadge = document.getElementById('wg-peers-count');
  1197. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1198. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1199. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1200. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1201. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1202. // Render Interfaces
  1203. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1204. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1205. if (ifacesTbody) {
  1206. ifacesTbody.innerHTML = '';
  1207. if (state.wgInterfaces.length === 0) {
  1208. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1209. } else {
  1210. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1211. state.wgInterfaces.forEach(iface => {
  1212. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1213. const tr = document.createElement('tr');
  1214. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1215. tr.innerHTML = `
  1216. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1217. <td class="py-2.5 px-3">
  1218. <div class="flex items-center gap-1.5">
  1219. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1220. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1221. </div>
  1222. </td>
  1223. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1224. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1225. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1226. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1227. ${(iface.public_key || '').substring(0, 10)}... 📋
  1228. </span>
  1229. </td>
  1230. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1231. <td class="py-2.5 px-3 text-center">
  1232. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1233. </td>
  1234. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1235. ${iface.running ? `
  1236. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1237. ` : `
  1238. <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>
  1239. `}
  1240. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1241. ${iface.disabled ? 'Enable' : 'Disable'}
  1242. </button>
  1243. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1244. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1245. </td>
  1246. `;
  1247. ifacesTbody.appendChild(tr);
  1248. });
  1249. }
  1250. }
  1251. // Populate filter dropdown in peers tab
  1252. const filterSel = document.getElementById('wg-peers-filter-iface');
  1253. if (filterSel) {
  1254. const currentVal = filterSel.value;
  1255. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1256. state.wgInterfaces.forEach(i => {
  1257. const opt = document.createElement('option');
  1258. opt.value = i.name;
  1259. opt.innerText = i.name;
  1260. if (i.name === currentVal) opt.selected = true;
  1261. filterSel.appendChild(opt);
  1262. });
  1263. }
  1264. renderWGPeers();
  1265. } catch (err) {
  1266. console.error('Failed to load WireGuard:', err);
  1267. }
  1268. }
  1269. function renderWGPeers() {
  1270. const filterSel = document.getElementById('wg-peers-filter-iface');
  1271. const selectedIface = filterSel ? filterSel.value : '';
  1272. const tbody = document.getElementById('wg-peers-table-body');
  1273. const empty = document.getElementById('wg-peers-empty');
  1274. if (!tbody) return;
  1275. tbody.innerHTML = '';
  1276. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1277. if (filtered.length === 0) {
  1278. if (empty) empty.classList.remove('hidden');
  1279. } else {
  1280. if (empty) empty.classList.add('hidden');
  1281. filtered.forEach(p => {
  1282. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1283. const tr = document.createElement('tr');
  1284. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1285. tr.innerHTML = `
  1286. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1287. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1288. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1289. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1290. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1291. ${(p.public_key || '').substring(0, 10)}... 📋
  1292. </span>
  1293. </td>
  1294. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1295. <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>
  1296. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1297. <td class="py-2.5 px-3 font-mono text-[11px]">
  1298. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1299. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1300. </td>
  1301. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1302. <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">
  1303. ${p.disabled ? 'Enable' : 'Disable'}
  1304. </button>
  1305. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1306. <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>
  1307. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1308. </td>
  1309. `;
  1310. tbody.appendChild(tr);
  1311. });
  1312. }
  1313. }
  1314. function openAddWGInterfaceModal() {
  1315. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1316. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1317. const nameEl = document.getElementById('wg-iface-modal-name');
  1318. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1319. nameEl.readOnly = false;
  1320. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1321. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1322. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1323. document.getElementById('wg-iface-modal-comment').value = '';
  1324. document.getElementById('wg-iface-modal-pubkey').value = '';
  1325. document.getElementById('wg-iface-modal-privkey').value = '';
  1326. document.getElementById('wg-iface-modal-disabled').checked = false;
  1327. generateWGInterfaceKeys();
  1328. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1329. }
  1330. function openEditWGInterfaceModal(name) {
  1331. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1332. if (!iface) return;
  1333. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1334. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1335. const nameEl = document.getElementById('wg-iface-modal-name');
  1336. nameEl.value = iface.name;
  1337. nameEl.readOnly = false; // ALLOW RENAMING
  1338. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1339. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1340. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1341. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1342. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1343. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1344. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1345. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1346. }
  1347. function closeAddWGInterfaceModal() {
  1348. document.getElementById('wg-iface-modal').classList.add('hidden');
  1349. }
  1350. async function generateWGInterfaceKeys() {
  1351. try {
  1352. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1353. const keys = await res.json();
  1354. if (res.ok) {
  1355. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1356. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1357. }
  1358. } catch (err) {
  1359. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1360. }
  1361. }
  1362. async function onWGInterfacePrivKeyInput() {
  1363. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1364. if (!privKey) return;
  1365. try {
  1366. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1367. method: 'POST',
  1368. headers: { 'Content-Type': 'application/json' },
  1369. body: JSON.stringify({ private_key: privKey })
  1370. });
  1371. if (res.ok) {
  1372. const data = await res.json();
  1373. if (data.public_key) {
  1374. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1375. }
  1376. }
  1377. } catch (err) {
  1378. // Ignore while typing
  1379. }
  1380. }
  1381. function toggleWGPrivKeyVisibility() {
  1382. const el = document.getElementById('wg-iface-modal-privkey');
  1383. const btn = document.getElementById('btn-toggle-wg-privkey');
  1384. if (el.type === 'password') {
  1385. el.type = 'text';
  1386. btn.innerText = '🙈 Hide';
  1387. } else {
  1388. el.type = 'password';
  1389. btn.innerText = '👁️ Show';
  1390. }
  1391. }
  1392. function copyWGInterfacePubKey() {
  1393. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1394. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1395. }
  1396. async function submitSaveWGInterface(e) {
  1397. e.preventDefault();
  1398. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1399. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1400. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1401. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1402. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1403. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1404. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1405. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1406. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1409. method: 'POST',
  1410. headers: { 'Content-Type': 'application/json' },
  1411. body: JSON.stringify({
  1412. orig_name: origName,
  1413. name,
  1414. listen_port: port,
  1415. address: addr,
  1416. mtu,
  1417. comment,
  1418. public_key: pub,
  1419. private_key: priv,
  1420. disabled
  1421. })
  1422. });
  1423. const data = await res.json();
  1424. if (res.ok) {
  1425. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1426. closeAddWGInterfaceModal();
  1427. loadWireGuard(false);
  1428. fetchData(false);
  1429. } else {
  1430. showToast('Error', data.error || 'Failed to save interface', 'error');
  1431. }
  1432. } catch (err) {
  1433. showToast('Error', err.message, 'error');
  1434. }
  1435. }
  1436. async function startWGInterface(name) {
  1437. try {
  1438. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1439. if (res.ok) {
  1440. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1441. loadWireGuard(false);
  1442. fetchData(false);
  1443. }
  1444. } catch (err) {
  1445. showToast('Error', err.message, 'error');
  1446. }
  1447. }
  1448. async function stopWGInterface(name) {
  1449. try {
  1450. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1451. if (res.ok) {
  1452. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1453. loadWireGuard(false);
  1454. fetchData(false);
  1455. }
  1456. } catch (err) {
  1457. showToast('Error', err.message, 'error');
  1458. }
  1459. }
  1460. async function toggleWGInterfaceState(name, enable) {
  1461. try {
  1462. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1463. method: 'POST',
  1464. headers: { 'Content-Type': 'application/json' },
  1465. body: JSON.stringify({ enabled: enable })
  1466. });
  1467. if (res.ok) {
  1468. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1469. loadWireGuard(false);
  1470. fetchData(false);
  1471. }
  1472. } catch (err) {
  1473. showToast('Error', err.message, 'error');
  1474. }
  1475. }
  1476. async function deleteWGInterface(name) {
  1477. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1478. try {
  1479. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1480. if (res.ok) {
  1481. showToast('Deleted', `Interface ${name} removed`, 'success');
  1482. loadWireGuard(false);
  1483. fetchData(false);
  1484. }
  1485. } catch (err) {
  1486. showToast('Error', err.message, 'error');
  1487. }
  1488. }
  1489. function populateWGPeerIfaceSelect(selectedIface = '') {
  1490. const sel = document.getElementById('wg-peer-modal-iface');
  1491. if (!sel) return;
  1492. sel.innerHTML = '';
  1493. (state.wgInterfaces || []).forEach(i => {
  1494. const opt = document.createElement('option');
  1495. opt.value = i.name;
  1496. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1497. if (i.name === selectedIface) opt.selected = true;
  1498. sel.appendChild(opt);
  1499. });
  1500. }
  1501. function openAddWGPeerModal() {
  1502. if ((state.wgInterfaces || []).length === 0) {
  1503. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1504. openAddWGInterfaceModal();
  1505. return;
  1506. }
  1507. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1508. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1509. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1510. populateWGPeerIfaceSelect();
  1511. document.getElementById('wg-peer-modal-name').value = '';
  1512. document.getElementById('wg-peer-modal-pubkey').value = '';
  1513. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1514. document.getElementById('wg-peer-modal-endpoint').value = '';
  1515. document.getElementById('wg-peer-modal-port').value = '';
  1516. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1517. document.getElementById('wg-peer-modal-preshared').value = '';
  1518. document.getElementById('wg-peer-modal-disabled').checked = false;
  1519. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1520. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1521. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1522. }
  1523. function openEditWGPeerModal(ifaceName, pubKey) {
  1524. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1525. if (!peer) {
  1526. showToast('Not Found', 'Peer not found', 'warning');
  1527. return;
  1528. }
  1529. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1530. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1531. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1532. populateWGPeerIfaceSelect(peer.interface);
  1533. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1534. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1535. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1536. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1537. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1538. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1539. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1540. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1541. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1542. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1543. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1544. }
  1545. function closeAddWGPeerModal() {
  1546. document.getElementById('wg-peer-modal').classList.add('hidden');
  1547. }
  1548. async function generatePeerKeypairHelper() {
  1549. try {
  1550. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1551. const keys = await res.json();
  1552. if (res.ok) {
  1553. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1554. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1555. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1556. checkWGPeerKeyValidity();
  1557. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1558. }
  1559. } catch (err) {
  1560. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1561. }
  1562. }
  1563. function copyGeneratedPeerPrivKey() {
  1564. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1565. if (priv) copyToClipboard(priv, 'Client Private Key');
  1566. }
  1567. async function generatePeerPSK() {
  1568. try {
  1569. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1570. const keys = await res.json();
  1571. if (res.ok && keys.private_key) {
  1572. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1573. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1574. }
  1575. } catch (err) {
  1576. showToast('Error', err.message, 'error');
  1577. }
  1578. }
  1579. function checkWGPeerKeyValidity() {
  1580. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1581. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1582. const warningEl = document.getElementById('wg-peer-key-warning');
  1583. if (!warningEl) return;
  1584. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1585. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1586. warningEl.classList.remove('hidden');
  1587. } else {
  1588. warningEl.classList.add('hidden');
  1589. }
  1590. }
  1591. async function submitSaveWGPeer(e) {
  1592. e.preventDefault();
  1593. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1594. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1595. const iface = document.getElementById('wg-peer-modal-iface').value;
  1596. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1597. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1598. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1599. .split(',')
  1600. .map(s => s.trim())
  1601. .filter(s => s.length > 0);
  1602. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1603. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1604. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1605. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1606. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1607. // Validation
  1608. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1609. if (targetIface && targetIface.public_key === pub) {
  1610. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1611. return;
  1612. }
  1613. try {
  1614. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1615. method: 'POST',
  1616. headers: { 'Content-Type': 'application/json' },
  1617. body: JSON.stringify({
  1618. orig_interface: origIface,
  1619. orig_public_key: origPubKey,
  1620. interface: iface,
  1621. name,
  1622. public_key: pub,
  1623. allowed_ips: allowed,
  1624. endpoint_address: epHost,
  1625. endpoint_port: epPort,
  1626. persistent_keepalive: keepalive,
  1627. preshared_key: psk,
  1628. disabled
  1629. })
  1630. });
  1631. const data = await res.json();
  1632. if (res.ok) {
  1633. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1634. closeAddWGPeerModal();
  1635. loadWireGuard(false);
  1636. } else {
  1637. showToast('Error', data.error || 'Failed to save peer', 'error');
  1638. }
  1639. } catch (err) {
  1640. showToast('Error', err.message, 'error');
  1641. }
  1642. }
  1643. async function toggleWGPeerState(iface, pubkey, enable) {
  1644. try {
  1645. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1646. method: 'POST',
  1647. headers: { 'Content-Type': 'application/json' },
  1648. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1649. });
  1650. const data = await res.json();
  1651. if (res.ok) {
  1652. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1653. loadWireGuard(false);
  1654. } else {
  1655. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1656. }
  1657. } catch (err) {
  1658. showToast('Error', err.message, 'error');
  1659. }
  1660. }
  1661. async function deleteWGPeer(iface, pubkey) {
  1662. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1663. try {
  1664. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1665. method: 'POST',
  1666. headers: { 'Content-Type': 'application/json' },
  1667. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1668. });
  1669. const data = await res.json();
  1670. if (res.ok) {
  1671. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1672. loadWireGuard(false);
  1673. } else {
  1674. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1675. }
  1676. } catch (err) {
  1677. showToast('Error', err.message, 'error');
  1678. }
  1679. }
  1680. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1681. function switchIpsecModalTab(tab) {
  1682. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1683. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1684. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1685. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1686. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1687. if (tab === 'p1') {
  1688. if (p1Tab) {
  1689. 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';
  1690. }
  1691. if (p2Tab) {
  1692. 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';
  1693. }
  1694. if (p1Content) p1Content.classList.remove('hidden');
  1695. if (p2Content) p2Content.classList.add('hidden');
  1696. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1697. } else {
  1698. if (p1Tab) {
  1699. 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';
  1700. }
  1701. if (p2Tab) {
  1702. 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';
  1703. }
  1704. if (p1Content) p1Content.classList.add('hidden');
  1705. if (p2Content) p2Content.classList.remove('hidden');
  1706. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1707. }
  1708. }
  1709. function toggleIpsecPhaseStep() {
  1710. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1711. if (p1Content && !p1Content.classList.contains('hidden')) {
  1712. switchIpsecModalTab('p2');
  1713. } else {
  1714. switchIpsecModalTab('p1');
  1715. }
  1716. }
  1717. function toggleIpsecPskVisibility() {
  1718. const pskInput = document.getElementById('ipsec-modal-psk');
  1719. if (!pskInput) return;
  1720. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1721. }
  1722. function addIpsecLocalSubnet(val = '') {
  1723. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1724. if (!container) return;
  1725. const row = document.createElement('div');
  1726. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1727. row.innerHTML = `
  1728. <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">
  1729. <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>
  1730. `;
  1731. container.appendChild(row);
  1732. }
  1733. function addIpsecRemoteSubnet(val = '') {
  1734. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1735. if (!container) return;
  1736. const row = document.createElement('div');
  1737. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1738. row.innerHTML = `
  1739. <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">
  1740. <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>
  1741. `;
  1742. container.appendChild(row);
  1743. }
  1744. function updateIpsecEspProposalFromPFS(val) {
  1745. const prop = document.getElementById('ipsec-modal-espprop');
  1746. if (!prop) return;
  1747. if (val === 'none') {
  1748. prop.value = 'aes256-sha256,aes128-sha256,default';
  1749. } else {
  1750. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1751. }
  1752. }
  1753. function updateIpsecIkeProposalFromDH(dh) {
  1754. const el = document.getElementById('ipsec-modal-ikeprop');
  1755. if (el) {
  1756. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1757. }
  1758. }
  1759. function safeSetVal(id, val) {
  1760. const el = document.getElementById(id);
  1761. if (el) el.value = val;
  1762. }
  1763. function safeSetChecked(id, val) {
  1764. const el = document.getElementById(id);
  1765. if (el) el.checked = !!val;
  1766. }
  1767. function safeGetVal(id, def = '') {
  1768. const el = document.getElementById(id);
  1769. return el ? el.value : def;
  1770. }
  1771. async function loadIPSec(populateInputs = true) {
  1772. try {
  1773. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1774. const list = await res.json();
  1775. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1776. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1777. const badge = document.getElementById('ipsec-sas-badge');
  1778. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1779. const tbody = document.getElementById('ipsec-table-body');
  1780. const empty = document.getElementById('ipsec-empty');
  1781. if (!tbody) return;
  1782. tbody.innerHTML = '';
  1783. if (state.ipsecTunnels.length === 0) {
  1784. if (empty) empty.classList.remove('hidden');
  1785. } else {
  1786. if (empty) empty.classList.add('hidden');
  1787. state.ipsecTunnels.forEach(c => {
  1788. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1789. const tr = document.createElement('tr');
  1790. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1791. // Local subnets tags
  1792. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1793. 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('');
  1794. // Remote subnets tags
  1795. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1796. 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('');
  1797. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1798. const p2Name = c.phase2_name || `${c.name}_p2`;
  1799. tr.innerHTML = `
  1800. <td class="py-2.5 px-3 text-center">
  1801. ${isEstablished ? `
  1802. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1803. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1804. <span>UP</span>
  1805. </span>
  1806. ` : (c.disabled ? `
  1807. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1808. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1809. <span>DOWN</span>
  1810. </span>
  1811. ` : `
  1812. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1813. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1814. <span>IDLE</span>
  1815. </span>
  1816. `)}
  1817. </td>
  1818. <td class="py-2.5 px-4 font-bold text-white">
  1819. <div class="flex items-center gap-2">
  1820. <span class="text-amber-400">🛡</span>
  1821. <div>
  1822. <div>${escapeHtml(c.name)}</div>
  1823. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1824. </div>
  1825. </div>
  1826. </td>
  1827. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1828. <td class="py-2.5 px-4 font-sans">
  1829. <div class="flex items-center gap-1.5">
  1830. <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>
  1831. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1832. </div>
  1833. </td>
  1834. <td class="py-2.5 px-4">
  1835. <div class="space-y-1">
  1836. <div class="flex items-center flex-wrap gap-1">
  1837. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1838. ${localBadges}
  1839. </div>
  1840. <div class="flex items-center flex-wrap gap-1">
  1841. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1842. ${remoteBadges}
  1843. </div>
  1844. </div>
  1845. </td>
  1846. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1847. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1848. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1849. </div>
  1850. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1851. </td>
  1852. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1853. ${isEstablished ? `
  1854. <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>
  1855. ` : `
  1856. <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>
  1857. `}
  1858. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1859. ${c.disabled ? 'Enable' : 'Disable'}
  1860. </button>
  1861. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1862. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1863. </td>
  1864. `;
  1865. tbody.appendChild(tr);
  1866. });
  1867. }
  1868. } catch (err) {
  1869. console.error('Failed to load IPSec:', err);
  1870. }
  1871. }
  1872. function openAddIPSecModal() {
  1873. const modal = document.getElementById('ipsec-modal');
  1874. if (!modal) return;
  1875. const title = document.getElementById('ipsec-modal-title');
  1876. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1877. // Phase 1 Fields
  1878. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1879. const nameEl = document.getElementById('ipsec-modal-name');
  1880. if (nameEl) nameEl.readOnly = false;
  1881. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1882. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1883. safeSetVal('ipsec-modal-remotegw', '');
  1884. safeSetVal('ipsec-modal-localaddrs', '');
  1885. safeSetVal('ipsec-modal-comments', '');
  1886. safeSetVal('ipsec-modal-psk', '');
  1887. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1888. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1889. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1890. safeSetVal('ipsec-modal-localid', '');
  1891. safeSetVal('ipsec-modal-remoteid', '');
  1892. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1893. // Phase 2 Fields
  1894. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1895. safeSetVal('ipsec-modal-espkeylife', '28800');
  1896. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1897. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1898. safeSetChecked('ipsec-modal-autostart', true);
  1899. safeSetChecked('ipsec-modal-disabled', false);
  1900. // Clear & Populate default dynamic subnets
  1901. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1902. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1903. if (localContainer) {
  1904. localContainer.innerHTML = '';
  1905. addIpsecLocalSubnet('192.168.10.0/24');
  1906. }
  1907. if (remoteContainer) {
  1908. remoteContainer.innerHTML = '';
  1909. addIpsecRemoteSubnet('192.168.20.0/24');
  1910. }
  1911. switchIpsecModalTab('p1');
  1912. modal.classList.remove('hidden');
  1913. }
  1914. function openEditIPSecModal(name) {
  1915. const modal = document.getElementById('ipsec-modal');
  1916. if (!modal) return;
  1917. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1918. if (!conn) return;
  1919. const title = document.getElementById('ipsec-modal-title');
  1920. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1921. // Phase 1 Fields
  1922. safeSetVal('ipsec-modal-name', conn.name);
  1923. const nameEl = document.getElementById('ipsec-modal-name');
  1924. if (nameEl) nameEl.readOnly = true;
  1925. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1926. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1927. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1928. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1929. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1930. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1931. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1932. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1933. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1934. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1935. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1936. // Phase 2 Fields
  1937. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1938. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1939. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1940. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1941. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1942. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1943. // Populate dynamic subnets
  1944. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1945. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1946. if (localContainer) {
  1947. localContainer.innerHTML = '';
  1948. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1949. locals.forEach(s => addIpsecLocalSubnet(s));
  1950. }
  1951. if (remoteContainer) {
  1952. remoteContainer.innerHTML = '';
  1953. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1954. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1955. }
  1956. switchIpsecModalTab('p1');
  1957. modal.classList.remove('hidden');
  1958. }
  1959. function closeAddIPSecModal() {
  1960. const modal = document.getElementById('ipsec-modal');
  1961. if (modal) modal.classList.add('hidden');
  1962. }
  1963. async function submitSaveIPSec(e) {
  1964. if (e) e.preventDefault();
  1965. const name = safeGetVal('ipsec-modal-name').trim();
  1966. if (!name) {
  1967. showToast('Error', 'Tunnel name is required', 'error');
  1968. return;
  1969. }
  1970. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1971. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1972. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1973. const comments = safeGetVal('ipsec-modal-comments').trim();
  1974. const psk = safeGetVal('ipsec-modal-psk');
  1975. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1976. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1977. const localId = safeGetVal('ipsec-modal-localid').trim();
  1978. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1979. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1980. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1981. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1982. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1983. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1984. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1985. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1986. // Scrape dynamic local and remote subnets
  1987. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1988. const localSubnets = [];
  1989. localInputs.forEach(inp => {
  1990. const v = inp.value.trim();
  1991. if (v) localSubnets.push(v);
  1992. });
  1993. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1994. const remoteSubnets = [];
  1995. remoteInputs.forEach(inp => {
  1996. const v = inp.value.trim();
  1997. if (v) remoteSubnets.push(v);
  1998. });
  1999. try {
  2000. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2001. method: 'POST',
  2002. headers: { 'Content-Type': 'application/json' },
  2003. body: JSON.stringify({
  2004. name,
  2005. comment: comments,
  2006. ike_version: ikeVersion,
  2007. local_addrs: localAddrs,
  2008. remote_addrs: remotegw,
  2009. preshared_key: psk,
  2010. ike_proposals: ikeProposals,
  2011. ike_keylife: ikeKeylife,
  2012. local_id: localId,
  2013. remote_id: remoteId,
  2014. dpd: dpd,
  2015. phase2_name: phase2Name,
  2016. esp_proposals: espProposals,
  2017. esp_keylife: espKeylife,
  2018. pfs_group: pfsGroup,
  2019. pfs: pfsGroup !== 'none',
  2020. local_subnets: localSubnets,
  2021. remote_subnets: remoteSubnets,
  2022. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2023. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2024. auto_start: autostart,
  2025. disabled
  2026. })
  2027. });
  2028. if (res.ok) {
  2029. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2030. closeAddIPSecModal();
  2031. loadIPSec(false);
  2032. } else {
  2033. const err = await res.json();
  2034. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2035. }
  2036. } catch (err) {
  2037. showToast('Error', err.message, 'error');
  2038. }
  2039. }
  2040. async function startIPSecTunnel(name) {
  2041. try {
  2042. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2043. if (res.ok) {
  2044. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2045. setTimeout(() => loadIPSec(false), 2000);
  2046. }
  2047. } catch (err) {
  2048. showToast('Error', err.message, 'error');
  2049. }
  2050. }
  2051. async function stopIPSecTunnel(name) {
  2052. try {
  2053. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2054. if (res.ok) {
  2055. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2056. loadIPSec(false);
  2057. }
  2058. } catch (err) {
  2059. showToast('Error', err.message, 'error');
  2060. }
  2061. }
  2062. async function toggleIPSecState(name, enable) {
  2063. try {
  2064. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2065. method: 'POST',
  2066. headers: { 'Content-Type': 'application/json' },
  2067. body: JSON.stringify({ enabled: enable })
  2068. });
  2069. if (res.ok) {
  2070. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2071. loadIPSec(false);
  2072. }
  2073. } catch (err) {
  2074. showToast('Error', err.message, 'error');
  2075. }
  2076. }
  2077. async function deleteIPSecConn(name) {
  2078. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2079. try {
  2080. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2081. if (res.ok) {
  2082. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2083. loadIPSec(false);
  2084. fetchData(false);
  2085. }
  2086. } catch (err) {
  2087. showToast('Error', err.message, 'error');
  2088. }
  2089. }
  2090. // ======================== L2TP Multi-Instance ========================
  2091. async function loadL2TP(populateInputs = true) {
  2092. try {
  2093. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2094. await fetchPPPProfilesList();
  2095. }
  2096. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2097. const list = await res.json();
  2098. state.l2tpList = Array.isArray(list) ? list : [];
  2099. const badge = document.getElementById('l2tp-count-badge');
  2100. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2101. const tbody = document.getElementById('l2tp-table-body');
  2102. const empty = document.getElementById('l2tp-empty');
  2103. if (!tbody) return;
  2104. tbody.innerHTML = '';
  2105. if (state.l2tpList.length === 0) {
  2106. if (empty) empty.classList.remove('hidden');
  2107. } else {
  2108. if (empty) empty.classList.add('hidden');
  2109. state.l2tpList.forEach(inst => {
  2110. const tr = document.createElement('tr');
  2111. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2112. tr.innerHTML = `
  2113. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2114. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2115. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2116. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2117. <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>
  2118. <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>
  2119. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2120. <td class="py-2.5 px-3 text-center">
  2121. <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'}">
  2122. ${inst.default_route ? 'Yes' : 'No'}
  2123. </span>
  2124. </td>
  2125. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2126. ${inst.running ? `
  2127. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2128. ` : `
  2129. <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>
  2130. `}
  2131. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2132. ${inst.disabled ? 'Enable' : 'Disable'}
  2133. </button>
  2134. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2135. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2136. </td>
  2137. `;
  2138. tbody.appendChild(tr);
  2139. });
  2140. }
  2141. } catch (err) {
  2142. console.error('Failed to load L2TP:', err);
  2143. }
  2144. }
  2145. async function openAddL2TPModal() {
  2146. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2147. await fetchPPPProfilesList();
  2148. }
  2149. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2150. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2151. document.getElementById('l2tp-modal-name').readOnly = false;
  2152. document.getElementById('l2tp-modal-server').value = '';
  2153. document.getElementById('l2tp-modal-user').value = '';
  2154. document.getElementById('l2tp-modal-pass').value = '';
  2155. document.getElementById('l2tp-modal-ipsec').value = '';
  2156. document.getElementById('l2tp-modal-defroute').checked = true;
  2157. document.getElementById('l2tp-modal-disabled').checked = false;
  2158. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2159. document.getElementById('l2tp-modal').classList.remove('hidden');
  2160. }
  2161. async function openEditL2TPModal(name) {
  2162. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2163. await fetchPPPProfilesList();
  2164. }
  2165. const inst = (state.l2tpList || []).find(i => i.name === name);
  2166. if (!inst) return;
  2167. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2168. document.getElementById('l2tp-modal-name').value = inst.name;
  2169. document.getElementById('l2tp-modal-name').readOnly = true;
  2170. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2171. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2172. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2173. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2174. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2175. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2176. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2177. document.getElementById('l2tp-modal').classList.remove('hidden');
  2178. }
  2179. function closeL2TPModal() {
  2180. document.getElementById('l2tp-modal').classList.add('hidden');
  2181. }
  2182. async function submitSaveL2TP(e) {
  2183. e.preventDefault();
  2184. const name = document.getElementById('l2tp-modal-name').value.trim();
  2185. const server = document.getElementById('l2tp-modal-server').value.trim();
  2186. const user = document.getElementById('l2tp-modal-user').value.trim();
  2187. const pass = document.getElementById('l2tp-modal-pass').value;
  2188. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2189. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2190. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2191. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2192. try {
  2193. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2194. method: 'POST',
  2195. headers: { 'Content-Type': 'application/json' },
  2196. body: JSON.stringify({
  2197. name,
  2198. connect_to: server,
  2199. username: user,
  2200. password: pass,
  2201. profile: profile,
  2202. ipsec_secret: ipsec,
  2203. default_route: defRoute,
  2204. disabled
  2205. })
  2206. });
  2207. if (res.ok) {
  2208. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2209. closeL2TPModal();
  2210. loadL2TP(false);
  2211. fetchData(false);
  2212. }
  2213. } catch (err) {
  2214. showToast('Error', err.message, 'error');
  2215. }
  2216. }
  2217. async function connectL2TPInstance(name) {
  2218. try {
  2219. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2220. if (res.ok) {
  2221. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2222. setTimeout(() => loadL2TP(false), 2000);
  2223. }
  2224. } catch (err) {
  2225. showToast('Error', err.message, 'error');
  2226. }
  2227. }
  2228. async function disconnectL2TPInstance(name) {
  2229. try {
  2230. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2231. if (res.ok) {
  2232. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2233. loadL2TP(false);
  2234. }
  2235. } catch (err) {
  2236. showToast('Error', err.message, 'error');
  2237. }
  2238. }
  2239. async function toggleL2TPState(name, enable) {
  2240. try {
  2241. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2242. method: 'POST',
  2243. headers: { 'Content-Type': 'application/json' },
  2244. body: JSON.stringify({ enabled: enable })
  2245. });
  2246. if (res.ok) {
  2247. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2248. loadL2TP(false);
  2249. }
  2250. } catch (err) {
  2251. showToast('Error', err.message, 'error');
  2252. }
  2253. }
  2254. async function deleteL2TPInstance(name) {
  2255. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2256. try {
  2257. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2258. if (res.ok) {
  2259. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2260. loadL2TP(false);
  2261. fetchData(false);
  2262. }
  2263. } catch (err) {
  2264. showToast('Error', err.message, 'error');
  2265. }
  2266. }
  2267. // ======================== PPTP Multi-Instance ========================
  2268. async function loadPPTP(populateInputs = true) {
  2269. try {
  2270. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2271. await fetchPPPProfilesList();
  2272. }
  2273. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2274. const list = await res.json();
  2275. state.pptpList = Array.isArray(list) ? list : [];
  2276. const badge = document.getElementById('pptp-count-badge');
  2277. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2278. const tbody = document.getElementById('pptp-table-body');
  2279. const empty = document.getElementById('pptp-empty');
  2280. if (!tbody) return;
  2281. tbody.innerHTML = '';
  2282. if (state.pptpList.length === 0) {
  2283. if (empty) empty.classList.remove('hidden');
  2284. } else {
  2285. if (empty) empty.classList.add('hidden');
  2286. state.pptpList.forEach(inst => {
  2287. const tr = document.createElement('tr');
  2288. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2289. tr.innerHTML = `
  2290. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2291. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2292. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2293. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2294. <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>
  2295. <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>
  2296. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2297. <td class="py-2.5 px-3 text-center">
  2298. <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'}">
  2299. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2300. </span>
  2301. </td>
  2302. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2303. ${inst.running ? `
  2304. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2305. ` : `
  2306. <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>
  2307. `}
  2308. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2309. ${inst.disabled ? 'Enable' : 'Disable'}
  2310. </button>
  2311. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2312. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2313. </td>
  2314. `;
  2315. tbody.appendChild(tr);
  2316. });
  2317. }
  2318. } catch (err) {
  2319. console.error('Failed to load PPTP:', err);
  2320. }
  2321. }
  2322. async function openAddPPTPModal() {
  2323. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2324. await fetchPPPProfilesList();
  2325. }
  2326. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2327. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2328. document.getElementById('pptp-modal-name').readOnly = false;
  2329. document.getElementById('pptp-modal-server').value = '';
  2330. document.getElementById('pptp-modal-user').value = '';
  2331. document.getElementById('pptp-modal-pass').value = '';
  2332. document.getElementById('pptp-modal-mppe').checked = true;
  2333. document.getElementById('pptp-modal-defroute').checked = true;
  2334. document.getElementById('pptp-modal-disabled').checked = false;
  2335. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2336. document.getElementById('pptp-modal').classList.remove('hidden');
  2337. }
  2338. async function openEditPPTPModal(name) {
  2339. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2340. await fetchPPPProfilesList();
  2341. }
  2342. const inst = (state.pptpList || []).find(i => i.name === name);
  2343. if (!inst) return;
  2344. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2345. document.getElementById('pptp-modal-name').value = inst.name;
  2346. document.getElementById('pptp-modal-name').readOnly = true;
  2347. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2348. document.getElementById('pptp-modal-user').value = inst.username || '';
  2349. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2350. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2351. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2352. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2353. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2354. document.getElementById('pptp-modal').classList.remove('hidden');
  2355. }
  2356. function closePPTPModal() {
  2357. document.getElementById('pptp-modal').classList.add('hidden');
  2358. }
  2359. async function submitSavePPTP(e) {
  2360. e.preventDefault();
  2361. const name = document.getElementById('pptp-modal-name').value.trim();
  2362. const server = document.getElementById('pptp-modal-server').value.trim();
  2363. const user = document.getElementById('pptp-modal-user').value.trim();
  2364. const pass = document.getElementById('pptp-modal-pass').value;
  2365. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2366. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2367. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2368. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2369. try {
  2370. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2371. method: 'POST',
  2372. headers: { 'Content-Type': 'application/json' },
  2373. body: JSON.stringify({
  2374. name,
  2375. connect_to: server,
  2376. username: user,
  2377. password: pass,
  2378. profile: profile,
  2379. require_mppe: mppe,
  2380. default_route: defRoute,
  2381. auto_reconnect: true,
  2382. disabled
  2383. })
  2384. });
  2385. if (res.ok) {
  2386. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2387. closePPTPModal();
  2388. loadPPTP(false);
  2389. fetchData(false);
  2390. }
  2391. } catch (err) {
  2392. showToast('Error', err.message, 'error');
  2393. }
  2394. }
  2395. async function connectPPTPInstance(name) {
  2396. try {
  2397. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2398. if (res.ok) {
  2399. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2400. setTimeout(() => loadPPTP(false), 2000);
  2401. }
  2402. } catch (err) {
  2403. showToast('Error', err.message, 'error');
  2404. }
  2405. }
  2406. async function disconnectPPTPInstance(name) {
  2407. try {
  2408. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2409. if (res.ok) {
  2410. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2411. loadPPTP(false);
  2412. }
  2413. } catch (err) {
  2414. showToast('Error', err.message, 'error');
  2415. }
  2416. }
  2417. async function togglePPTPState(name, enable) {
  2418. try {
  2419. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2420. method: 'POST',
  2421. headers: { 'Content-Type': 'application/json' },
  2422. body: JSON.stringify({ enabled: enable })
  2423. });
  2424. if (res.ok) {
  2425. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2426. loadPPTP(false);
  2427. }
  2428. } catch (err) {
  2429. showToast('Error', err.message, 'error');
  2430. }
  2431. }
  2432. async function deletePPTPInstance(name) {
  2433. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2434. try {
  2435. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2436. if (res.ok) {
  2437. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2438. loadPPTP(false);
  2439. fetchData(false);
  2440. }
  2441. } catch (err) {
  2442. showToast('Error', err.message, 'error');
  2443. }
  2444. }
  2445. // ---------------- Modal & Helper Functions ----------------
  2446. function openVlanModal(defaultParent = '') {
  2447. const select = document.getElementById('vlan-parent');
  2448. select.innerHTML = '';
  2449. const allIfaces = state.interfaces || [];
  2450. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2451. if (eligible.length === 0) {
  2452. const opt = document.createElement('option');
  2453. opt.value = '';
  2454. opt.innerText = 'No VLAN-capable interfaces available';
  2455. select.appendChild(opt);
  2456. } else {
  2457. eligible.forEach(i => {
  2458. const opt = document.createElement('option');
  2459. opt.value = i.name;
  2460. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2461. if (i.name === defaultParent) opt.selected = true;
  2462. select.appendChild(opt);
  2463. });
  2464. }
  2465. document.getElementById('vlan-id').value = '';
  2466. document.getElementById('vlan-name').value = '';
  2467. document.getElementById('vlan-ip').value = '';
  2468. document.getElementById('vlan-desc').value = '';
  2469. autoSuggestVlanName();
  2470. document.getElementById('vlan-modal').classList.remove('hidden');
  2471. }
  2472. function closeVlanModal() {
  2473. document.getElementById('vlan-modal').classList.add('hidden');
  2474. }
  2475. function autoSuggestVlanName() {
  2476. const parent = document.getElementById('vlan-parent').value;
  2477. if (!parent) return;
  2478. const id = document.getElementById('vlan-id').value;
  2479. const nameInput = document.getElementById('vlan-name');
  2480. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2481. }
  2482. function setSubnetPreset(cidr) {
  2483. const ipInput = document.getElementById('vlan-ip');
  2484. const id = document.getElementById('vlan-id').value || '10';
  2485. ipInput.value = `192.168.${id}.1${cidr}`;
  2486. }
  2487. async function submitCreateVlan(e) {
  2488. e.preventDefault();
  2489. const btn = document.getElementById('vlan-submit-btn');
  2490. btn.disabled = true;
  2491. btn.innerText = 'Creating...';
  2492. const parent = document.getElementById('vlan-parent').value;
  2493. if (!parent) {
  2494. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2495. btn.disabled = false;
  2496. btn.innerText = 'Create VLAN';
  2497. return;
  2498. }
  2499. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2500. const name = document.getElementById('vlan-name').value.trim();
  2501. const ip = document.getElementById('vlan-ip').value.trim();
  2502. const role = document.getElementById('vlan-role').value;
  2503. const desc = document.getElementById('vlan-desc').value.trim();
  2504. try {
  2505. const res = await fetch(`${API_BASE}/vlans`, {
  2506. method: 'POST',
  2507. headers: { 'Content-Type': 'application/json' },
  2508. body: JSON.stringify({
  2509. parent_name: parent,
  2510. vlan_id: id,
  2511. name: name,
  2512. ip_address: ip,
  2513. role: role,
  2514. description: desc,
  2515. mtu: 1500,
  2516. auto_up: true
  2517. })
  2518. });
  2519. const data = await res.json();
  2520. if (res.ok) {
  2521. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2522. state.expandedParents.add(parent);
  2523. closeVlanModal();
  2524. await fetchData(true);
  2525. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2526. } else {
  2527. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2528. }
  2529. } catch (err) {
  2530. showToast('Error', err.message, 'error');
  2531. } finally {
  2532. btn.disabled = false;
  2533. btn.innerText = 'Create VLAN';
  2534. }
  2535. }
  2536. async function confirmDeleteVlan(name) {
  2537. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2538. try {
  2539. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2540. if (res.ok) {
  2541. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2542. closeIfaceModal();
  2543. fetchData(true);
  2544. }
  2545. } catch (err) {
  2546. showToast('Error', err.message, 'error');
  2547. }
  2548. }
  2549. function openIfaceModal(name) {
  2550. const iface = (state.interfaces || []).find(i => i.name === name);
  2551. if (!iface) return;
  2552. state.currentModalIface = iface.name;
  2553. document.getElementById('modal-iface-name').innerText = iface.name;
  2554. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2555. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2556. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2557. document.getElementById('modal-iface-desc').value = iface.description || '';
  2558. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2559. if (iface.is_vlan) {
  2560. delBtn.classList.remove('hidden');
  2561. } else {
  2562. delBtn.classList.add('hidden');
  2563. }
  2564. renderModalIPs(iface);
  2565. document.getElementById('iface-modal').classList.remove('hidden');
  2566. }
  2567. function renderModalIPs(iface) {
  2568. const container = document.getElementById('modal-ip-list');
  2569. container.innerHTML = '';
  2570. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2571. if (addrs.length === 0) {
  2572. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2573. return;
  2574. }
  2575. addrs.forEach(addr => {
  2576. const row = document.createElement('div');
  2577. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2578. row.innerHTML = `
  2579. <span class="text-white">${addr}</span>
  2580. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2581. `;
  2582. container.appendChild(row);
  2583. });
  2584. }
  2585. function closeIfaceModal() {
  2586. document.getElementById('iface-modal').classList.add('hidden');
  2587. state.currentModalIface = null;
  2588. }
  2589. async function setIfaceState(name, newState) {
  2590. await toggleInterfaceState(name, newState);
  2591. const updated = (state.interfaces || []).find(i => i.name === name);
  2592. if (updated) openIfaceModal(name);
  2593. }
  2594. async function applyMTU() {
  2595. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2596. try {
  2597. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2598. method: 'POST',
  2599. headers: { 'Content-Type': 'application/json' },
  2600. body: JSON.stringify({ mtu })
  2601. });
  2602. if (res.ok) {
  2603. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2604. fetchData(false);
  2605. }
  2606. } catch (err) {
  2607. showToast('Error', err.message, 'error');
  2608. }
  2609. }
  2610. async function addInterfaceIP() {
  2611. const ip = document.getElementById('modal-new-ip').value.trim();
  2612. if (!ip) return;
  2613. try {
  2614. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2615. method: 'POST',
  2616. headers: { 'Content-Type': 'application/json' },
  2617. body: JSON.stringify({ ip })
  2618. });
  2619. if (res.ok) {
  2620. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2621. document.getElementById('modal-new-ip').value = '';
  2622. await fetchData(false);
  2623. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2624. if (iface) renderModalIPs(iface);
  2625. } else {
  2626. const err = await res.json();
  2627. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2628. }
  2629. } catch (err) {
  2630. showToast('Error', err.message, 'error');
  2631. }
  2632. }
  2633. async function removeInterfaceIP(ip) {
  2634. if (!confirm(`Remove IP ${ip}?`)) return;
  2635. try {
  2636. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2637. method: 'DELETE',
  2638. headers: { 'Content-Type': 'application/json' },
  2639. body: JSON.stringify({ ip })
  2640. });
  2641. if (res.ok) {
  2642. showToast('IP Removed', `Removed ${ip}`, 'success');
  2643. await fetchData(false);
  2644. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2645. if (iface) renderModalIPs(iface);
  2646. }
  2647. } catch (err) {
  2648. showToast('Error', err.message, 'error');
  2649. }
  2650. }
  2651. async function saveInterfaceMetadata() {
  2652. const role = document.getElementById('modal-iface-role').value;
  2653. const desc = document.getElementById('modal-iface-desc').value.trim();
  2654. try {
  2655. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2656. method: 'POST',
  2657. headers: { 'Content-Type': 'application/json' },
  2658. body: JSON.stringify({ role, description: desc })
  2659. });
  2660. if (res.ok) {
  2661. showToast('Saved', 'Metadata updated', 'success');
  2662. closeIfaceModal();
  2663. fetchData(false);
  2664. }
  2665. } catch (err) {
  2666. showToast('Error', err.message, 'error');
  2667. }
  2668. }
  2669. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2670. state.fwSubTab = 'filter';
  2671. state.routesSubTab = 'routes';
  2672. function renderRuleFlag(disabled, hasComment) {
  2673. let flags = '';
  2674. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2675. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2676. return flags || '<span class="text-slate-600">-</span>';
  2677. }
  2678. function renderActionBadge(action) {
  2679. const act = (action || '').toLowerCase();
  2680. let color = 'bg-slate-800 text-slate-300';
  2681. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2682. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2683. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2684. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2685. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2686. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2687. }
  2688. function switchFWSubTab(tab) {
  2689. state.fwSubTab = tab;
  2690. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2691. tabs.forEach(t => {
  2692. const panel = document.getElementById(`fw-subtab-${t}`);
  2693. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2694. if (panel) {
  2695. if (t === tab) panel.classList.remove('hidden');
  2696. else panel.classList.add('hidden');
  2697. }
  2698. if (btn) {
  2699. if (t === tab) {
  2700. 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';
  2701. } else {
  2702. 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';
  2703. }
  2704. }
  2705. });
  2706. const addBtn = document.getElementById('fw-primary-add-btn');
  2707. if (addBtn) {
  2708. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2709. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2710. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2711. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2712. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2713. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2714. }
  2715. if (tab === 'geo') loadGeoIP();
  2716. if (tab === 'connections') loadConnections();
  2717. setTimeout(initTableSorting, 50);
  2718. }
  2719. function openCurrentFWModal() {
  2720. if (state.fwSubTab === 'filter') openAddFilterModal();
  2721. else if (state.fwSubTab === 'nat') openAddNATModal();
  2722. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2723. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2724. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2725. else if (state.fwSubTab === 'connections') loadConnections();
  2726. }
  2727. async function loadFirewall(populateDropdowns = true) {
  2728. try {
  2729. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2730. fetch(`${API_BASE}/firewall/summary`),
  2731. fetch(`${API_BASE}/firewall/filter`),
  2732. fetch(`${API_BASE}/firewall/nat`),
  2733. fetch(`${API_BASE}/firewall/mangle`),
  2734. fetch(`${API_BASE}/firewall/address-lists`),
  2735. fetch(`${API_BASE}/firewall/geoip/status`),
  2736. fetch(`${API_BASE}/firewall/geoip/countries`)
  2737. ]);
  2738. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2739. if (filterRes.ok) state.filterRules = await filterRes.json();
  2740. if (natRes.ok) state.natRules = await natRes.json();
  2741. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2742. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2743. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2744. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2745. // Badges
  2746. const bFilter = document.getElementById('fw-badge-filter');
  2747. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2748. const bNat = document.getElementById('fw-badge-nat');
  2749. if (bNat) bNat.innerText = (state.natRules || []).length;
  2750. const bMangle = document.getElementById('fw-badge-mangle');
  2751. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2752. const bAddr = document.getElementById('fw-badge-addrlist');
  2753. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2754. const bGeo = document.getElementById('fw-badge-geo');
  2755. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2756. renderFilterRules();
  2757. renderNATRules();
  2758. renderMangleRules();
  2759. renderAddressLists();
  2760. renderGeoCountries();
  2761. if (state.fwSubTab === 'connections') {
  2762. loadConnections();
  2763. }
  2764. } catch (err) {
  2765. console.error('Failed to load firewall:', err);
  2766. }
  2767. }
  2768. // ----------------- Filter Rules -----------------
  2769. function renderFilterRules() {
  2770. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2771. const tbody = document.getElementById('filter-table-body');
  2772. const empty = document.getElementById('filter-empty');
  2773. if (!tbody) return;
  2774. tbody.innerHTML = '';
  2775. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2776. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2777. if (rules.length === 0) {
  2778. empty?.classList.remove('hidden');
  2779. return;
  2780. }
  2781. empty?.classList.add('hidden');
  2782. rules.forEach((r, idx) => {
  2783. const tr = document.createElement('tr');
  2784. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2785. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2786. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2787. let actionExtra = '';
  2788. if (r.action === 'reject') {
  2789. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2790. } else if (r.action === 'jump') {
  2791. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2792. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2793. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2794. } else if (r.action === 'log' && r.log_prefix) {
  2795. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2796. }
  2797. tr.innerHTML = `
  2798. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2799. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2800. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2801. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2802. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2803. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2804. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2805. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2806. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2807. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2808. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2809. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2810. </td>
  2811. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2812. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2813. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2814. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2815. <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>
  2816. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2817. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2818. </td>
  2819. `;
  2820. tbody.appendChild(tr);
  2821. });
  2822. }
  2823. function formatTarget(addr, list, geo) {
  2824. const parts = [];
  2825. if (addr) parts.push(`<span>${addr}</span>`);
  2826. if (list) {
  2827. const inv = list.startsWith('!') ? '!' : '';
  2828. const clean = list.replace(/^!/, '');
  2829. 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>`);
  2830. }
  2831. if (geo) {
  2832. const inv = geo.startsWith('!') ? '!' : '';
  2833. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2834. 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>`);
  2835. }
  2836. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2837. return parts.join(' ');
  2838. }
  2839. function populateInterfaceSelect(selectId, currentVal = '') {
  2840. const sel = document.getElementById(selectId);
  2841. if (!sel) return;
  2842. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2843. (state.interfaces || []).forEach(i => {
  2844. const opt = document.createElement('option');
  2845. opt.value = i.name;
  2846. opt.innerText = `${i.name} (${i.role || i.type})`;
  2847. if (i.name === currentVal) opt.selected = true;
  2848. sel.appendChild(opt);
  2849. });
  2850. }
  2851. function populateAddressListSelect(selectId, currentVal = '') {
  2852. const sel = document.getElementById(selectId);
  2853. if (!sel) return;
  2854. sel.innerHTML = '<option value="">(None)</option>';
  2855. const cleanVal = (currentVal || '').replace(/^!/, '');
  2856. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2857. customNames.forEach(name => {
  2858. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2859. const opt = document.createElement('option');
  2860. opt.value = name;
  2861. opt.innerText = `${name} (${count} entries)`;
  2862. if (name === cleanVal) opt.selected = true;
  2863. sel.appendChild(opt);
  2864. });
  2865. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2866. const opt = document.createElement('option');
  2867. opt.value = cleanVal;
  2868. opt.innerText = cleanVal;
  2869. opt.selected = true;
  2870. sel.appendChild(opt);
  2871. }
  2872. populateCommonAddrListDatalist();
  2873. }
  2874. function populateCommonAddrListDatalist() {
  2875. const dl = document.getElementById('fw-addrlist-datalist');
  2876. if (!dl) return;
  2877. dl.innerHTML = '';
  2878. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2879. names.forEach(name => {
  2880. const opt = document.createElement('option');
  2881. opt.value = name;
  2882. dl.appendChild(opt);
  2883. });
  2884. }
  2885. function populateGeoIPSelect(selectId, currentVal = '') {
  2886. const sel = document.getElementById(selectId);
  2887. if (!sel) return;
  2888. sel.innerHTML = '<option value="">(None)</option>';
  2889. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2890. // Presets optgroup
  2891. const grpPresets = document.createElement('optgroup');
  2892. grpPresets.label = '⚡ Regional Presets';
  2893. const presets = [
  2894. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2895. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2896. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2897. ];
  2898. presets.forEach(p => {
  2899. const opt = document.createElement('option');
  2900. opt.value = p.code;
  2901. opt.innerText = p.label;
  2902. if (p.code === cleanVal) opt.selected = true;
  2903. grpPresets.appendChild(opt);
  2904. });
  2905. sel.appendChild(grpPresets);
  2906. // All Countries optgroup
  2907. const grpCountries = document.createElement('optgroup');
  2908. grpCountries.label = '🌍 All Countries';
  2909. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2910. countries.forEach(c => {
  2911. const opt = document.createElement('option');
  2912. opt.value = c.code;
  2913. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2914. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2915. if (c.code === cleanVal) opt.selected = true;
  2916. grpCountries.appendChild(opt);
  2917. });
  2918. sel.appendChild(grpCountries);
  2919. }
  2920. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2921. function switchFwRuleTab(tab) {
  2922. state.activeFwRuleTab = tab;
  2923. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2924. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2925. btn.classList.add('text-slate-400', 'border-transparent');
  2926. });
  2927. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2928. if (activeBtn) {
  2929. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2930. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2931. }
  2932. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2933. const activePane = document.getElementById(`fw-pane-${tab}`);
  2934. if (activePane) activePane.classList.remove('hidden');
  2935. if (tab === 'statistics') {
  2936. startFwStatPolling();
  2937. } else {
  2938. stopFwStatPolling();
  2939. }
  2940. }
  2941. function toggleFwField(fieldKey, expand) {
  2942. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2943. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2944. if (!plusBtn || !fieldBox) return;
  2945. if (expand) {
  2946. plusBtn.classList.add('hidden');
  2947. fieldBox.classList.remove('hidden');
  2948. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2949. if (valInput) valInput.focus();
  2950. } else {
  2951. fieldBox.classList.add('hidden');
  2952. plusBtn.classList.remove('hidden');
  2953. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2954. if (valInput) {
  2955. if (valInput.tagName === 'SELECT') {
  2956. valInput.selectedIndex = 0;
  2957. } else {
  2958. valInput.value = '';
  2959. }
  2960. }
  2961. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2962. if (invInput) invInput.checked = false;
  2963. if (fieldKey === 'cs') {
  2964. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2965. const el = document.getElementById(id);
  2966. if (el) el.checked = false;
  2967. });
  2968. }
  2969. if (fieldKey === 'natstate') {
  2970. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2971. const el = document.getElementById(id);
  2972. if (el) el.checked = false;
  2973. });
  2974. }
  2975. if (fieldKey === 'days') {
  2976. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2977. const el = document.getElementById(`fw-day-${d}`);
  2978. if (el) el.checked = true;
  2979. });
  2980. }
  2981. }
  2982. }
  2983. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2984. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2985. toggleFwField(fieldKey, true);
  2986. let strVal = String(value);
  2987. if (hasInvert) {
  2988. const inv = strVal.startsWith('!');
  2989. if (inv) strVal = strVal.slice(1);
  2990. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2991. if (invEl) invEl.checked = inv;
  2992. }
  2993. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2994. if (valEl) valEl.value = strVal;
  2995. } else {
  2996. toggleFwField(fieldKey, false);
  2997. }
  2998. }
  2999. function getFwFieldVal(fieldKey, hasInvert = false) {
  3000. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3001. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3002. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3003. let v = valEl ? valEl.value.trim() : '';
  3004. if (!v) return '';
  3005. if (hasInvert) {
  3006. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3007. if (invEl && invEl.checked) {
  3008. v = '!' + v.replace(/^!/, '');
  3009. }
  3010. }
  3011. return v;
  3012. }
  3013. function toggleMaximizeFilterModal() {
  3014. const win = document.getElementById('filter-modal-window');
  3015. if (!win) return;
  3016. if (win.classList.contains('max-w-[720px]')) {
  3017. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3018. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3019. } else {
  3020. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3021. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3022. }
  3023. }
  3024. function openAddFilterModal() {
  3025. switchFwRuleTab('general');
  3026. const badge = document.getElementById('fw-modal-badge');
  3027. if (badge) badge.innerText = 'New...';
  3028. document.getElementById('filter-modal-id').value = '';
  3029. document.getElementById('filter-modal-enabled').checked = true;
  3030. document.getElementById('filter-modal-comment').value = '';
  3031. document.getElementById('filter-modal-chain').value = 'forward';
  3032. document.getElementById('filter-modal-action').value = 'accept';
  3033. document.getElementById('filter-modal-log').checked = false;
  3034. populateInterfaceSelect('fw-val-iniface');
  3035. populateInterfaceSelect('fw-val-outiface');
  3036. populateAddressListSelect('fw-val-srclist');
  3037. populateAddressListSelect('fw-val-dstlist');
  3038. populateGeoIPSelect('fw-val-srcgeo');
  3039. populateGeoIPSelect('fw-val-dstgeo');
  3040. const allFieldKeys = [
  3041. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3042. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3043. 'routingmark', 'conntype', 'cs', 'natstate',
  3044. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3045. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3046. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3047. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3048. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3049. ];
  3050. allFieldKeys.forEach(k => toggleFwField(k, false));
  3051. resetCurrentRuleCounters();
  3052. toggleFilterActionFields();
  3053. document.getElementById('filter-modal').classList.remove('hidden');
  3054. }
  3055. function openEditFilterModal(id) {
  3056. const r = (state.filterRules || []).find(rule => rule.id === id);
  3057. if (!r) return;
  3058. switchFwRuleTab('general');
  3059. const badge = document.getElementById('fw-modal-badge');
  3060. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3061. document.getElementById('filter-modal-id').value = r.id;
  3062. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3063. document.getElementById('filter-modal-comment').value = r.comment || '';
  3064. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3065. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3066. document.getElementById('filter-modal-log').checked = !!r.log;
  3067. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3068. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3069. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3070. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3071. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3072. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3073. setFwFieldVal('src', r.src_address, true);
  3074. setFwFieldVal('dst', r.dst_address, true);
  3075. setFwFieldVal('srclist', r.src_address_list, true);
  3076. setFwFieldVal('dstlist', r.dst_address_list, true);
  3077. setFwFieldVal('srcgeo', r.src_geoip, true);
  3078. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3079. if (r.protocol && r.protocol !== 'all') {
  3080. setFwFieldVal('proto', r.protocol, true);
  3081. } else {
  3082. toggleFwField('proto', false);
  3083. }
  3084. setFwFieldVal('sport', r.src_port, true);
  3085. setFwFieldVal('dport', r.dst_port, true);
  3086. setFwFieldVal('anyport', r.any_port, true);
  3087. setFwFieldVal('iniface', r.in_interface, true);
  3088. setFwFieldVal('outiface', r.out_interface, true);
  3089. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3090. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3091. setFwFieldVal('pktmark', r.packet_mark, true);
  3092. setFwFieldVal('connmark', r.connection_mark, true);
  3093. setFwFieldVal('routingmark', r.routing_mark, true);
  3094. setFwFieldVal('conntype', r.connection_type, false);
  3095. const states = r.connection_state || [];
  3096. if (states.length > 0) {
  3097. toggleFwField('cs', true);
  3098. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3099. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3100. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3101. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3102. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3103. } else {
  3104. toggleFwField('cs', false);
  3105. }
  3106. const natStates = r.connection_nat_state || [];
  3107. if (natStates.length > 0) {
  3108. toggleFwField('natstate', true);
  3109. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3110. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3111. } else {
  3112. toggleFwField('natstate', false);
  3113. }
  3114. // Advanced tab fields
  3115. setFwFieldVal('layer7', r.layer7_protocol, false);
  3116. setFwFieldVal('content', r.content, false);
  3117. setFwFieldVal('connbytes', r.connection_bytes, false);
  3118. setFwFieldVal('connrate', r.connection_rate, false);
  3119. setFwFieldVal('pcc', r.pcc, false);
  3120. setFwFieldVal('srcmac', r.src_mac_address, true);
  3121. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3122. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3123. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3124. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3125. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3126. setFwFieldVal('tlshost', r.tls_host, false);
  3127. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3128. setFwFieldVal('priority', r.priority, false);
  3129. setFwFieldVal('dscp', r.dscp, false);
  3130. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3131. if (r.tos) {
  3132. const tosEl = document.getElementById('fw-val-tos');
  3133. if (tosEl) tosEl.value = r.tos;
  3134. }
  3135. setFwFieldVal('pktsize', r.packet_size, false);
  3136. setFwFieldVal('random', r.random, false);
  3137. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3138. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3139. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3140. setFwFieldVal('ttl', r.ttl, false);
  3141. // Extra tab fields
  3142. setFwFieldVal('time', r.time, false);
  3143. if (r.days) {
  3144. toggleFwField('days', true);
  3145. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3146. const chk = document.getElementById(`fw-day-${d}`);
  3147. if (chk) chk.checked = r.days.includes(d);
  3148. });
  3149. } else {
  3150. toggleFwField('days', false);
  3151. }
  3152. setFwFieldVal('limit', r.limit, false);
  3153. setFwFieldVal('dstlimit', r.dst_limit, false);
  3154. setFwFieldVal('psd', r.psd, false);
  3155. // Action fields
  3156. if (r.reject_with) {
  3157. const rwEl = document.getElementById('filter-modal-rejectwith');
  3158. if (rwEl) rwEl.value = r.reject_with;
  3159. }
  3160. if (r.jump_target) {
  3161. const jtEl = document.getElementById('filter-modal-jumptarget');
  3162. if (jtEl) jtEl.value = r.jump_target;
  3163. }
  3164. if (r.address_list) {
  3165. const alEl = document.getElementById('filter-modal-action-addrlist');
  3166. if (alEl) alEl.value = r.address_list;
  3167. }
  3168. if (r.address_list_timeout) {
  3169. const toEl = document.getElementById('filter-modal-action-timeout');
  3170. if (toEl) toEl.value = r.address_list_timeout;
  3171. }
  3172. setFwFieldVal('logprefix', r.log_prefix, false);
  3173. // Statistics
  3174. const bEl = document.getElementById('fw-stat-bytes');
  3175. const pEl = document.getElementById('fw-stat-packets');
  3176. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3177. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3178. state.fwLastBytes = r.bytes || 0;
  3179. state.fwLastPackets = r.packets || 0;
  3180. state.fwLastTimestamp = Date.now();
  3181. state.fwStatRateHistory = new Array(30).fill(0);
  3182. state.fwStatPktHistory = new Array(30).fill(0);
  3183. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3184. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3185. toggleFilterActionFields();
  3186. document.getElementById('filter-modal').classList.remove('hidden');
  3187. }
  3188. function closeFilterModal() {
  3189. stopFwStatPolling();
  3190. document.getElementById('filter-modal').classList.add('hidden');
  3191. }
  3192. function toggleFilterActionFields() {
  3193. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3194. const rejectBox = document.getElementById('filter-action-reject-box');
  3195. const jumpBox = document.getElementById('filter-action-jump-box');
  3196. const addrBox = document.getElementById('filter-action-addrlist-box');
  3197. if (rejectBox) {
  3198. if (act === 'reject') rejectBox.classList.remove('hidden');
  3199. else rejectBox.classList.add('hidden');
  3200. }
  3201. if (jumpBox) {
  3202. if (act === 'jump') jumpBox.classList.remove('hidden');
  3203. else jumpBox.classList.add('hidden');
  3204. }
  3205. if (addrBox) {
  3206. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3207. addrBox.classList.remove('hidden');
  3208. } else {
  3209. addrBox.classList.add('hidden');
  3210. }
  3211. }
  3212. if (act === 'log') {
  3213. const logEl = document.getElementById('filter-modal-log');
  3214. if (logEl) logEl.checked = true;
  3215. toggleFwField('logprefix', true);
  3216. }
  3217. }
  3218. function toggleFwLogPrefix() {
  3219. const isLog = document.getElementById('filter-modal-log')?.checked;
  3220. toggleFwField('logprefix', !!isLog);
  3221. }
  3222. function copyFilterRule() {
  3223. document.getElementById('filter-modal-id').value = '';
  3224. const badge = document.getElementById('fw-modal-badge');
  3225. if (badge) badge.innerText = 'New...';
  3226. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3227. }
  3228. function resetCurrentRuleCounters() {
  3229. state.fwStatRateHistory = new Array(30).fill(0);
  3230. state.fwStatPktHistory = new Array(30).fill(0);
  3231. state.fwLastBytes = 0;
  3232. state.fwLastPackets = 0;
  3233. state.fwLastTimestamp = Date.now();
  3234. const bEl = document.getElementById('fw-stat-bytes');
  3235. const pEl = document.getElementById('fw-stat-packets');
  3236. const rEl = document.getElementById('fw-stat-rate');
  3237. const prEl = document.getElementById('fw-stat-pktrate');
  3238. if (bEl) bEl.value = '0 B';
  3239. if (pEl) pEl.value = '0';
  3240. if (rEl) rEl.value = '0 bps';
  3241. if (prEl) prEl.value = '0 p/s';
  3242. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3243. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3244. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3245. }
  3246. async function resetAllFwCounters() {
  3247. try {
  3248. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3249. if (res.ok) {
  3250. resetCurrentRuleCounters();
  3251. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3252. loadFirewall(false);
  3253. }
  3254. } catch (err) {
  3255. showToast('Error', err.message, 'error');
  3256. }
  3257. }
  3258. async function applyFilterRule(closeAfter = false) {
  3259. const id = document.getElementById('filter-modal-id').value;
  3260. const chain = document.getElementById('filter-modal-chain').value;
  3261. const action = document.getElementById('filter-modal-action').value;
  3262. const comment = document.getElementById('filter-modal-comment').value.trim();
  3263. const enabled = document.getElementById('filter-modal-enabled').checked;
  3264. const src = getFwFieldVal('src', true);
  3265. const dst = getFwFieldVal('dst', true);
  3266. const srclist = getFwFieldVal('srclist', true);
  3267. const dstlist = getFwFieldVal('dstlist', true);
  3268. const srcgeo = getFwFieldVal('srcgeo', true);
  3269. const dstgeo = getFwFieldVal('dstgeo', true);
  3270. const proto = getFwFieldVal('proto', true);
  3271. const sport = getFwFieldVal('sport', true);
  3272. const dport = getFwFieldVal('dport', true);
  3273. const anyport = getFwFieldVal('anyport', true);
  3274. const iniface = getFwFieldVal('iniface', true);
  3275. const outiface = getFwFieldVal('outiface', true);
  3276. const inifacelist = getFwFieldVal('inifacelist', true);
  3277. const outifacelist = getFwFieldVal('outifacelist', true);
  3278. const pktmark = getFwFieldVal('pktmark', true);
  3279. const connmark = getFwFieldVal('connmark', true);
  3280. const routingmark = getFwFieldVal('routingmark', true);
  3281. const conntype = getFwFieldVal('conntype', false);
  3282. const states = [];
  3283. const csBox = document.getElementById('fw-field-cs');
  3284. if (csBox && !csBox.classList.contains('hidden')) {
  3285. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3286. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3287. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3288. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3289. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3290. }
  3291. const natStates = [];
  3292. const natBox = document.getElementById('fw-field-natstate');
  3293. if (natBox && !natBox.classList.contains('hidden')) {
  3294. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3295. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3296. }
  3297. const payload = {
  3298. id,
  3299. chain,
  3300. action,
  3301. protocol: proto || 'all',
  3302. src_address: src,
  3303. dst_address: dst,
  3304. src_port: sport,
  3305. dst_port: dport,
  3306. any_port: anyport,
  3307. in_interface: iniface,
  3308. out_interface: outiface,
  3309. in_interface_list: inifacelist,
  3310. out_interface_list: outifacelist,
  3311. packet_mark: pktmark,
  3312. connection_mark: connmark,
  3313. routing_mark: routingmark,
  3314. connection_type: conntype,
  3315. connection_state: states,
  3316. connection_nat_state: natStates,
  3317. src_address_list: srclist,
  3318. dst_address_list: dstlist,
  3319. src_geoip: srcgeo,
  3320. dst_geoip: dstgeo,
  3321. comment,
  3322. disabled: !enabled,
  3323. // Advanced tab
  3324. layer7_protocol: getFwFieldVal('layer7', false),
  3325. content: getFwFieldVal('content', false),
  3326. connection_bytes: getFwFieldVal('connbytes', false),
  3327. connection_rate: getFwFieldVal('connrate', false),
  3328. pcc: getFwFieldVal('pcc', false),
  3329. src_mac_address: getFwFieldVal('srcmac', true),
  3330. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3331. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3332. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3333. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3334. ipsec_policy: getFwFieldVal('ipsec', false),
  3335. tls_host: getFwFieldVal('tlshost', false),
  3336. ingress_priority: getFwFieldVal('ingresspriority', false),
  3337. priority: getFwFieldVal('priority', false),
  3338. dscp: getFwFieldVal('dscp', false),
  3339. tcp_mss: getFwFieldVal('tcpmss', false),
  3340. tos: document.getElementById('fw-val-tos')?.value || '',
  3341. packet_size: getFwFieldVal('pktsize', false),
  3342. random: getFwFieldVal('random', false),
  3343. tcp_flags: getFwFieldVal('tcpflags', false),
  3344. icmp_options: getFwFieldVal('icmpoptions', false),
  3345. ipv4_options: getFwFieldVal('ipv4options', false),
  3346. ttl: getFwFieldVal('ttl', false),
  3347. // Extra tab
  3348. time: getFwFieldVal('time', false),
  3349. limit: getFwFieldVal('limit', false),
  3350. dst_limit: getFwFieldVal('dstlimit', false),
  3351. psd: getFwFieldVal('psd', false),
  3352. // Action tab
  3353. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3354. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3355. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3356. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3357. log: document.getElementById('filter-modal-log')?.checked || false,
  3358. log_prefix: getFwFieldVal('logprefix', false)
  3359. };
  3360. try {
  3361. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3362. method: 'POST',
  3363. headers: { 'Content-Type': 'application/json' },
  3364. body: JSON.stringify(payload)
  3365. });
  3366. if (res.ok) {
  3367. const data = await res.json();
  3368. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3369. loadFirewall(false);
  3370. if (closeAfter) {
  3371. closeFilterModal();
  3372. } else {
  3373. if (data.id) {
  3374. document.getElementById('filter-modal-id').value = data.id;
  3375. const badge = document.getElementById('fw-modal-badge');
  3376. if (badge) badge.innerText = `#${data.id}`;
  3377. }
  3378. }
  3379. } else {
  3380. const err = await res.json();
  3381. showToast('Error', err.message || 'Failed to save rule', 'error');
  3382. }
  3383. } catch (err) {
  3384. showToast('Error', err.message, 'error');
  3385. }
  3386. }
  3387. function submitSaveFilterRule(e) {
  3388. if (e && e.preventDefault) e.preventDefault();
  3389. return applyFilterRule(true);
  3390. }
  3391. function startFwStatPolling() {
  3392. stopFwStatPolling();
  3393. pollRuleStats();
  3394. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3395. }
  3396. function stopFwStatPolling() {
  3397. if (state.fwStatInterval) {
  3398. clearInterval(state.fwStatInterval);
  3399. state.fwStatInterval = null;
  3400. }
  3401. }
  3402. async function pollRuleStats() {
  3403. const id = document.getElementById('filter-modal-id')?.value;
  3404. if (!id) {
  3405. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3406. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3407. return;
  3408. }
  3409. try {
  3410. const res = await fetch(`${API_BASE}/firewall/filter`);
  3411. if (!res.ok) return;
  3412. const rules = await res.json();
  3413. const r = rules.find(x => x.id === id);
  3414. if (!r) return;
  3415. const now = Date.now();
  3416. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3417. state.fwLastTimestamp = now;
  3418. const curBytes = r.bytes || 0;
  3419. const curPackets = r.packets || 0;
  3420. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3421. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3422. state.fwLastBytes = curBytes;
  3423. state.fwLastPackets = curPackets;
  3424. const rateBps = Math.round((deltaBytes * 8) / dt);
  3425. const ratePkt = Math.round(deltaPkts / dt);
  3426. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3427. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3428. state.fwStatRateHistory.push(rateBps);
  3429. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3430. state.fwStatPktHistory.push(ratePkt);
  3431. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3432. const bEl = document.getElementById('fw-stat-bytes');
  3433. const pEl = document.getElementById('fw-stat-packets');
  3434. const rEl = document.getElementById('fw-stat-rate');
  3435. const prEl = document.getElementById('fw-stat-pktrate');
  3436. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3437. if (pEl) pEl.value = curPackets.toLocaleString();
  3438. if (rEl) rEl.value = formatBps(rateBps);
  3439. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3440. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3441. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3442. } catch (e) {
  3443. console.error('Error polling rule stats', e);
  3444. }
  3445. }
  3446. function formatBps(bps) {
  3447. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3448. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3449. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3450. return bps + ' bps';
  3451. }
  3452. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3453. const svg = document.getElementById(svgId);
  3454. if (!svg) return;
  3455. const w = 500;
  3456. const h = 100;
  3457. const paddingRight = 45;
  3458. const graphWidth = w - paddingRight;
  3459. const maxVal = Math.max(5, ...dataArray);
  3460. const currentVal = dataArray[dataArray.length - 1] || 0;
  3461. const leg = document.getElementById(legendId);
  3462. if (leg) {
  3463. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3464. }
  3465. let gridLines = '';
  3466. for (let i = 0; i <= 5; i++) {
  3467. const y = 8 + (i * (h - 18) / 5);
  3468. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3469. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3470. gridLines += `
  3471. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3472. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3473. `;
  3474. }
  3475. const step = graphWidth / (dataArray.length - 1);
  3476. const points = dataArray.map((val, idx) => {
  3477. const x = idx * step;
  3478. const y = (h - 10) - (val / maxVal) * (h - 20);
  3479. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3480. });
  3481. const polylineStr = points.join(' ');
  3482. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3483. svg.innerHTML = `
  3484. ${gridLines}
  3485. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3486. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3487. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3488. `;
  3489. }
  3490. async function moveFilterRule(id, dir) {
  3491. try {
  3492. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3493. method: 'POST',
  3494. headers: { 'Content-Type': 'application/json' },
  3495. body: JSON.stringify({ direction: dir })
  3496. });
  3497. if (res.ok) loadFirewall(false);
  3498. } catch (err) {
  3499. showToast('Error', err.message, 'error');
  3500. }
  3501. }
  3502. async function toggleFilterRuleState(id, disabled) {
  3503. try {
  3504. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3505. method: 'POST',
  3506. headers: { 'Content-Type': 'application/json' },
  3507. body: JSON.stringify({ disabled })
  3508. });
  3509. if (res.ok) loadFirewall(false);
  3510. } catch (err) {
  3511. showToast('Error', err.message, 'error');
  3512. }
  3513. }
  3514. async function deleteFilterRule(id) {
  3515. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3516. try {
  3517. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3518. if (res.ok) {
  3519. showToast('Deleted', 'Filter rule removed', 'success');
  3520. loadFirewall(false);
  3521. }
  3522. } catch (err) {
  3523. showToast('Error', err.message, 'error');
  3524. }
  3525. }
  3526. // ----------------- NAT Rules -----------------
  3527. function renderNATRules() {
  3528. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3529. const tbody = document.getElementById('nat-table-body');
  3530. const empty = document.getElementById('nat-empty');
  3531. if (!tbody) return;
  3532. tbody.innerHTML = '';
  3533. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3534. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3535. if (rules.length === 0) {
  3536. empty?.classList.remove('hidden');
  3537. return;
  3538. }
  3539. empty?.classList.add('hidden');
  3540. rules.forEach((r, idx) => {
  3541. const tr = document.createElement('tr');
  3542. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3543. let toTarget = '-';
  3544. if (r.action === 'jump') {
  3545. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3546. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3547. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3548. } else if (r.action === 'redirect') {
  3549. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3550. } else if (r.action === 'masquerade') {
  3551. 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>`;
  3552. } else if (r.action === 'log') {
  3553. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3554. } else {
  3555. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3556. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3557. }
  3558. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3559. tr.innerHTML = `
  3560. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3561. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3562. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3563. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3564. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3565. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3566. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3567. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3568. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3569. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3570. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3571. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3572. </td>
  3573. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3574. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3575. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3576. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3577. <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>
  3578. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3579. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3580. </td>
  3581. `;
  3582. tbody.appendChild(tr);
  3583. });
  3584. }
  3585. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3586. function switchNATRuleTab(tab) {
  3587. state.activeNATRuleTab = tab;
  3588. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3589. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3590. btn.classList.add('text-slate-400', 'border-transparent');
  3591. });
  3592. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3593. if (activeBtn) {
  3594. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3595. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3596. }
  3597. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3598. const activePane = document.getElementById(`nat-pane-${tab}`);
  3599. if (activePane) activePane.classList.remove('hidden');
  3600. if (tab === 'statistics') {
  3601. startNATStatPolling();
  3602. } else {
  3603. stopNATStatPolling();
  3604. }
  3605. }
  3606. function toggleNATField(fieldKey, expand) {
  3607. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3608. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3609. if (!plusBtn || !fieldBox) return;
  3610. if (expand) {
  3611. plusBtn.classList.add('hidden');
  3612. fieldBox.classList.remove('hidden');
  3613. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3614. if (valInput) valInput.focus();
  3615. } else {
  3616. fieldBox.classList.add('hidden');
  3617. plusBtn.classList.remove('hidden');
  3618. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3619. if (valInput) {
  3620. if (valInput.tagName === 'SELECT') {
  3621. valInput.selectedIndex = 0;
  3622. } else {
  3623. valInput.value = '';
  3624. }
  3625. }
  3626. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3627. if (invInput) invInput.checked = false;
  3628. if (fieldKey === 'days') {
  3629. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3630. const el = document.getElementById(`nat-day-${d}`);
  3631. if (el) el.checked = true;
  3632. });
  3633. }
  3634. }
  3635. }
  3636. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3637. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3638. toggleNATField(fieldKey, true);
  3639. let strVal = String(value);
  3640. if (hasInvert) {
  3641. const inv = strVal.startsWith('!');
  3642. if (inv) strVal = strVal.slice(1);
  3643. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3644. if (invEl) invEl.checked = inv;
  3645. }
  3646. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3647. if (valEl) valEl.value = strVal;
  3648. } else {
  3649. toggleNATField(fieldKey, false);
  3650. }
  3651. }
  3652. function getNATFieldVal(fieldKey, hasInvert = false) {
  3653. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3654. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3655. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3656. let v = valEl ? valEl.value.trim() : '';
  3657. if (!v) return '';
  3658. if (hasInvert) {
  3659. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3660. if (invEl && invEl.checked) {
  3661. v = '!' + v.replace(/^!/, '');
  3662. }
  3663. }
  3664. return v;
  3665. }
  3666. function toggleMaximizeNATModal() {
  3667. const win = document.getElementById('nat-modal-window');
  3668. if (!win) return;
  3669. if (win.classList.contains('max-w-[720px]')) {
  3670. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3671. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3672. } else {
  3673. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3674. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3675. }
  3676. }
  3677. function handleNATChainChange() {
  3678. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3679. const actSel = document.getElementById('nat-modal-action');
  3680. if (actSel) {
  3681. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3682. actSel.value = 'masquerade';
  3683. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3684. actSel.value = 'dst-nat';
  3685. }
  3686. }
  3687. toggleNATActionFields();
  3688. }
  3689. function toggleNATActionFields() {
  3690. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3691. const rowAddr = document.getElementById('nat-row-toaddr');
  3692. const rowPort = document.getElementById('nat-row-toport');
  3693. const jumpBox = document.getElementById('nat-action-jump-box');
  3694. const addrBox = document.getElementById('nat-action-addrlist-box');
  3695. // Hide all dynamic rows first
  3696. if (rowAddr) rowAddr.classList.add('hidden');
  3697. if (rowPort) rowPort.classList.add('hidden');
  3698. if (jumpBox) jumpBox.classList.add('hidden');
  3699. if (addrBox) addrBox.classList.add('hidden');
  3700. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3701. if (rowAddr) rowAddr.classList.remove('hidden');
  3702. if (rowPort) rowPort.classList.remove('hidden');
  3703. } else if (act === 'redirect' || act === 'masquerade') {
  3704. if (rowPort) rowPort.classList.remove('hidden');
  3705. } else if (act === 'jump') {
  3706. if (jumpBox) jumpBox.classList.remove('hidden');
  3707. } else if (act.includes('address-list') || act.includes('address list')) {
  3708. if (addrBox) addrBox.classList.remove('hidden');
  3709. }
  3710. if (act === 'log') {
  3711. const logEl = document.getElementById('nat-modal-log');
  3712. if (logEl) logEl.checked = true;
  3713. toggleNATField('logprefix', true);
  3714. }
  3715. }
  3716. function toggleNATLogPrefix() {
  3717. const isLog = document.getElementById('nat-modal-log')?.checked;
  3718. toggleNATField('logprefix', !!isLog);
  3719. }
  3720. function openAddNATModal() {
  3721. switchNATRuleTab('general');
  3722. const badge = document.getElementById('nat-modal-badge');
  3723. if (badge) badge.innerText = 'New...';
  3724. document.getElementById('nat-modal-id').value = '';
  3725. document.getElementById('nat-modal-enabled').checked = true;
  3726. document.getElementById('nat-modal-comment').value = '';
  3727. document.getElementById('nat-modal-chain').value = 'srcnat';
  3728. document.getElementById('nat-modal-action').value = 'masquerade';
  3729. document.getElementById('nat-modal-toaddr').value = '';
  3730. document.getElementById('nat-modal-toport').value = '';
  3731. document.getElementById('nat-modal-log').checked = false;
  3732. populateInterfaceSelect('nat-val-iniface');
  3733. populateInterfaceSelect('nat-val-outiface');
  3734. populateAddressListSelect('nat-val-srclist');
  3735. populateAddressListSelect('nat-val-dstlist');
  3736. populateGeoIPSelect('nat-val-srcgeo');
  3737. populateGeoIPSelect('nat-val-dstgeo');
  3738. const allFieldKeys = [
  3739. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3740. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3741. 'routingmark', 'conntype',
  3742. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3743. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3744. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3745. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3746. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3747. ];
  3748. allFieldKeys.forEach(k => toggleNATField(k, false));
  3749. resetCurrentNATRuleCounters();
  3750. toggleNATActionFields();
  3751. document.getElementById('nat-modal').classList.remove('hidden');
  3752. }
  3753. function openEditNATModal(id) {
  3754. const r = (state.natRules || []).find(rule => rule.id === id);
  3755. if (!r) return;
  3756. switchNATRuleTab('general');
  3757. const badge = document.getElementById('nat-modal-badge');
  3758. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3759. document.getElementById('nat-modal-id').value = r.id;
  3760. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3761. document.getElementById('nat-modal-comment').value = r.comment || '';
  3762. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3763. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3764. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3765. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3766. document.getElementById('nat-modal-log').checked = !!r.log;
  3767. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3768. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3769. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3770. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3771. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3772. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3773. setNATFieldVal('src', r.src_address, true);
  3774. setNATFieldVal('dst', r.dst_address, true);
  3775. setNATFieldVal('srclist', r.src_address_list, true);
  3776. setNATFieldVal('dstlist', r.dst_address_list, true);
  3777. setNATFieldVal('srcgeo', r.src_geoip, true);
  3778. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3779. if (r.protocol && r.protocol !== 'all') {
  3780. setNATFieldVal('proto', r.protocol, true);
  3781. } else {
  3782. toggleNATField('proto', false);
  3783. }
  3784. setNATFieldVal('sport', r.src_port, true);
  3785. setNATFieldVal('dport', r.dst_port, true);
  3786. setNATFieldVal('anyport', r.any_port, true);
  3787. setNATFieldVal('iniface', r.in_interface, true);
  3788. setNATFieldVal('outiface', r.out_interface, true);
  3789. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3790. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3791. setNATFieldVal('pktmark', r.packet_mark, true);
  3792. setNATFieldVal('connmark', r.connection_mark, true);
  3793. setNATFieldVal('routingmark', r.routing_mark, true);
  3794. setNATFieldVal('conntype', r.connection_type, false);
  3795. // Advanced tab fields
  3796. setNATFieldVal('layer7', r.layer7_protocol, false);
  3797. setNATFieldVal('content', r.content, false);
  3798. setNATFieldVal('connbytes', r.connection_bytes, false);
  3799. setNATFieldVal('connrate', r.connection_rate, false);
  3800. setNATFieldVal('pcc', r.pcc, false);
  3801. setNATFieldVal('srcmac', r.src_mac_address, true);
  3802. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3803. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3804. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3805. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3806. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3807. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3808. setNATFieldVal('priority', r.priority, false);
  3809. setNATFieldVal('dscp', r.dscp, false);
  3810. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3811. if (r.tos) {
  3812. const tosEl = document.getElementById('nat-val-tos');
  3813. if (tosEl) tosEl.value = r.tos;
  3814. }
  3815. setNATFieldVal('pktsize', r.packet_size, false);
  3816. setNATFieldVal('random', r.random, false);
  3817. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3818. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3819. setNATFieldVal('ttl', r.ttl, false);
  3820. // Extra tab fields
  3821. setNATFieldVal('time', r.time, false);
  3822. if (r.days) {
  3823. toggleNATField('days', true);
  3824. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3825. const chk = document.getElementById(`nat-day-${d}`);
  3826. if (chk) chk.checked = r.days.includes(d);
  3827. });
  3828. } else {
  3829. toggleNATField('days', false);
  3830. }
  3831. setNATFieldVal('limit', r.limit, false);
  3832. setNATFieldVal('dstlimit', r.dst_limit, false);
  3833. setNATFieldVal('psd', r.psd, false);
  3834. // Action fields
  3835. if (r.jump_target) {
  3836. const jtEl = document.getElementById('nat-modal-jumptarget');
  3837. if (jtEl) jtEl.value = r.jump_target;
  3838. }
  3839. if (r.address_list) {
  3840. const alEl = document.getElementById('nat-modal-action-addrlist');
  3841. if (alEl) alEl.value = r.address_list;
  3842. }
  3843. if (r.address_list_timeout) {
  3844. const toEl = document.getElementById('nat-modal-action-timeout');
  3845. if (toEl) toEl.value = r.address_list_timeout;
  3846. }
  3847. setNATFieldVal('logprefix', r.log_prefix, false);
  3848. // Statistics
  3849. const bEl = document.getElementById('nat-stat-bytes');
  3850. const pEl = document.getElementById('nat-stat-packets');
  3851. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3852. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3853. state.natLastBytes = r.bytes || 0;
  3854. state.natLastPackets = r.packets || 0;
  3855. state.natLastTimestamp = Date.now();
  3856. state.natStatRateHistory = new Array(30).fill(0);
  3857. state.natStatPktHistory = new Array(30).fill(0);
  3858. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3859. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3860. toggleNATActionFields();
  3861. document.getElementById('nat-modal').classList.remove('hidden');
  3862. }
  3863. function closeNATModal() {
  3864. stopNATStatPolling();
  3865. document.getElementById('nat-modal').classList.add('hidden');
  3866. }
  3867. function copyNATRule() {
  3868. document.getElementById('nat-modal-id').value = '';
  3869. const badge = document.getElementById('nat-modal-badge');
  3870. if (badge) badge.innerText = 'New...';
  3871. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3872. }
  3873. function resetCurrentNATRuleCounters() {
  3874. state.natStatRateHistory = new Array(30).fill(0);
  3875. state.natStatPktHistory = new Array(30).fill(0);
  3876. state.natLastBytes = 0;
  3877. state.natLastPackets = 0;
  3878. state.natLastTimestamp = Date.now();
  3879. const bEl = document.getElementById('nat-stat-bytes');
  3880. const pEl = document.getElementById('nat-stat-packets');
  3881. const rEl = document.getElementById('nat-stat-rate');
  3882. const prEl = document.getElementById('nat-stat-pktrate');
  3883. if (bEl) bEl.value = '0 B';
  3884. if (pEl) pEl.value = '0';
  3885. if (rEl) rEl.value = '0 bps';
  3886. if (prEl) prEl.value = '0 p/s';
  3887. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3888. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3889. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3890. }
  3891. async function applyNATRule(closeAfter = false) {
  3892. const id = document.getElementById('nat-modal-id').value;
  3893. const chain = document.getElementById('nat-modal-chain').value;
  3894. const action = document.getElementById('nat-modal-action').value;
  3895. const comment = document.getElementById('nat-modal-comment').value.trim();
  3896. const enabled = document.getElementById('nat-modal-enabled').checked;
  3897. const src = getNATFieldVal('src', true);
  3898. const dst = getNATFieldVal('dst', true);
  3899. const srclist = getNATFieldVal('srclist', true);
  3900. const dstlist = getNATFieldVal('dstlist', true);
  3901. const srcgeo = getNATFieldVal('srcgeo', true);
  3902. const dstgeo = getNATFieldVal('dstgeo', true);
  3903. const proto = getNATFieldVal('proto', true);
  3904. const sport = getNATFieldVal('sport', true);
  3905. const dport = getNATFieldVal('dport', true);
  3906. const anyport = getNATFieldVal('anyport', true);
  3907. const iniface = getNATFieldVal('iniface', true);
  3908. const outiface = getNATFieldVal('outiface', true);
  3909. const inifacelist = getNATFieldVal('inifacelist', true);
  3910. const outifacelist = getNATFieldVal('outifacelist', true);
  3911. const pktmark = getNATFieldVal('pktmark', true);
  3912. const connmark = getNATFieldVal('connmark', true);
  3913. const routingmark = getNATFieldVal('routingmark', true);
  3914. const conntype = getNATFieldVal('conntype', false);
  3915. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3916. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3917. const payload = {
  3918. id,
  3919. chain,
  3920. action,
  3921. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3922. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3923. protocol: proto || 'all',
  3924. src_address: src,
  3925. dst_address: dst,
  3926. src_port: sport,
  3927. dst_port: dport,
  3928. any_port: anyport,
  3929. in_interface: iniface,
  3930. out_interface: outiface,
  3931. in_interface_list: inifacelist,
  3932. out_interface_list: outifacelist,
  3933. packet_mark: pktmark,
  3934. connection_mark: connmark,
  3935. routing_mark: routingmark,
  3936. connection_type: conntype,
  3937. src_address_list: srclist,
  3938. dst_address_list: dstlist,
  3939. src_geoip: srcgeo,
  3940. dst_geoip: dstgeo,
  3941. comment,
  3942. disabled: !enabled,
  3943. // Advanced tab
  3944. layer7_protocol: getNATFieldVal('layer7', false),
  3945. content: getNATFieldVal('content', false),
  3946. connection_bytes: getNATFieldVal('connbytes', false),
  3947. connection_rate: getNATFieldVal('connrate', false),
  3948. pcc: getNATFieldVal('pcc', false),
  3949. src_mac_address: getNATFieldVal('srcmac', true),
  3950. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3951. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3952. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3953. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3954. ipsec_policy: getNATFieldVal('ipsec', false),
  3955. ingress_priority: getNATFieldVal('ingresspriority', false),
  3956. priority: getNATFieldVal('priority', false),
  3957. dscp: getNATFieldVal('dscp', false),
  3958. tcp_mss: getNATFieldVal('tcpmss', false),
  3959. tos: document.getElementById('nat-val-tos')?.value || '',
  3960. packet_size: getNATFieldVal('pktsize', false),
  3961. random: getNATFieldVal('random', false),
  3962. icmp_options: getNATFieldVal('icmpoptions', false),
  3963. ipv4_options: getNATFieldVal('ipv4options', false),
  3964. ttl: getNATFieldVal('ttl', false),
  3965. // Extra tab
  3966. time: getNATFieldVal('time', false),
  3967. limit: getNATFieldVal('limit', false),
  3968. dst_limit: getNATFieldVal('dstlimit', false),
  3969. psd: getNATFieldVal('psd', false),
  3970. // Action tab
  3971. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3972. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3973. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3974. log: document.getElementById('nat-modal-log')?.checked || false,
  3975. log_prefix: getNATFieldVal('logprefix', false)
  3976. };
  3977. try {
  3978. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3979. method: 'POST',
  3980. headers: { 'Content-Type': 'application/json' },
  3981. body: JSON.stringify(payload)
  3982. });
  3983. if (res.ok) {
  3984. const data = await res.json();
  3985. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3986. loadFirewall(false);
  3987. if (closeAfter) {
  3988. closeNATModal();
  3989. } else {
  3990. if (data.id) {
  3991. document.getElementById('nat-modal-id').value = data.id;
  3992. const badge = document.getElementById('nat-modal-badge');
  3993. if (badge) badge.innerText = `#${data.id}`;
  3994. }
  3995. }
  3996. } else {
  3997. const err = await res.json();
  3998. showToast('Error', err.message || 'Failed to save rule', 'error');
  3999. }
  4000. } catch (err) {
  4001. showToast('Error', err.message, 'error');
  4002. }
  4003. }
  4004. function submitSaveNATRule(e) {
  4005. if (e && e.preventDefault) e.preventDefault();
  4006. return applyNATRule(true);
  4007. }
  4008. function startNATStatPolling() {
  4009. stopNATStatPolling();
  4010. pollNATRuleStats();
  4011. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4012. }
  4013. function stopNATStatPolling() {
  4014. if (state.natStatInterval) {
  4015. clearInterval(state.natStatInterval);
  4016. state.natStatInterval = null;
  4017. }
  4018. }
  4019. async function pollNATRuleStats() {
  4020. const id = document.getElementById('nat-modal-id')?.value;
  4021. if (!id) {
  4022. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4023. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4024. return;
  4025. }
  4026. try {
  4027. const res = await fetch(`${API_BASE}/firewall/nat`);
  4028. if (!res.ok) return;
  4029. const rules = await res.json();
  4030. const r = rules.find(x => x.id === id);
  4031. if (!r) return;
  4032. const now = Date.now();
  4033. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4034. state.natLastTimestamp = now;
  4035. const curBytes = r.bytes || 0;
  4036. const curPackets = r.packets || 0;
  4037. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4038. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4039. state.natLastBytes = curBytes;
  4040. state.natLastPackets = curPackets;
  4041. const rateBps = Math.round((deltaBytes * 8) / dt);
  4042. const ratePkt = Math.round(deltaPkts / dt);
  4043. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4044. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4045. state.natStatRateHistory.push(rateBps);
  4046. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4047. state.natStatPktHistory.push(ratePkt);
  4048. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4049. const bEl = document.getElementById('nat-stat-bytes');
  4050. const pEl = document.getElementById('nat-stat-packets');
  4051. const rEl = document.getElementById('nat-stat-rate');
  4052. const prEl = document.getElementById('nat-stat-pktrate');
  4053. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4054. if (pEl) pEl.value = curPackets.toLocaleString();
  4055. if (rEl) rEl.value = formatBps(rateBps);
  4056. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4057. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4058. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4059. } catch (e) {
  4060. console.error('Error polling NAT rule stats', e);
  4061. }
  4062. }
  4063. async function moveNATRule(id, dir) {
  4064. try {
  4065. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4066. method: 'POST',
  4067. headers: { 'Content-Type': 'application/json' },
  4068. body: JSON.stringify({ direction: dir })
  4069. });
  4070. if (res.ok) loadFirewall(false);
  4071. } catch (err) {
  4072. showToast('Error', err.message, 'error');
  4073. }
  4074. }
  4075. async function toggleNATRuleState(id, disabled) {
  4076. try {
  4077. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4078. method: 'POST',
  4079. headers: { 'Content-Type': 'application/json' },
  4080. body: JSON.stringify({ disabled })
  4081. });
  4082. if (res.ok) loadFirewall(false);
  4083. } catch (err) {
  4084. showToast('Error', err.message, 'error');
  4085. }
  4086. }
  4087. async function deleteNATRule(id) {
  4088. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4089. try {
  4090. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4091. if (res.ok) {
  4092. showToast('Deleted', 'NAT rule removed', 'success');
  4093. loadFirewall(false);
  4094. }
  4095. } catch (err) {
  4096. showToast('Error', err.message, 'error');
  4097. }
  4098. }
  4099. // ----------------- Mangle Rules -----------------
  4100. function renderMangleRules() {
  4101. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4102. const tbody = document.getElementById('mangle-table-body');
  4103. const empty = document.getElementById('mangle-empty');
  4104. if (!tbody) return;
  4105. tbody.innerHTML = '';
  4106. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4107. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4108. if (rules.length === 0) {
  4109. empty?.classList.remove('hidden');
  4110. return;
  4111. }
  4112. empty?.classList.add('hidden');
  4113. rules.forEach((r, idx) => {
  4114. const tr = document.createElement('tr');
  4115. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4116. let markVal = '<span class="text-slate-500">-</span>';
  4117. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4118. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4119. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4120. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4121. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4122. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4123. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4124. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4125. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4126. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4127. 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>`;
  4128. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4129. tr.innerHTML = `
  4130. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4131. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4132. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4133. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4134. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4135. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4136. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4137. <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>
  4138. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4139. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4140. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4141. </td>
  4142. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4143. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4144. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4145. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4146. <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>
  4147. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4148. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4149. </td>
  4150. `;
  4151. tbody.appendChild(tr);
  4152. });
  4153. }
  4154. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4155. function switchMangleRuleTab(tab) {
  4156. state.activeMangleRuleTab = tab;
  4157. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4158. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4159. btn.classList.add('text-slate-400', 'border-transparent');
  4160. });
  4161. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4162. if (activeBtn) {
  4163. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4164. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4165. }
  4166. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4167. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4168. if (activePane) activePane.classList.remove('hidden');
  4169. if (tab === 'statistics') {
  4170. startMangleStatPolling();
  4171. } else {
  4172. stopMangleStatPolling();
  4173. }
  4174. }
  4175. function toggleMangleField(fieldKey, expand) {
  4176. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4177. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4178. if (!plusBtn || !fieldBox) return;
  4179. if (expand) {
  4180. plusBtn.classList.add('hidden');
  4181. fieldBox.classList.remove('hidden');
  4182. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4183. if (valInput) valInput.focus();
  4184. } else {
  4185. fieldBox.classList.add('hidden');
  4186. plusBtn.classList.remove('hidden');
  4187. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4188. if (valInput) {
  4189. if (valInput.tagName === 'SELECT') {
  4190. valInput.selectedIndex = 0;
  4191. } else {
  4192. valInput.value = '';
  4193. }
  4194. }
  4195. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4196. if (invInput) invInput.checked = false;
  4197. if (fieldKey === 'cs') {
  4198. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4199. const el = document.getElementById(id);
  4200. if (el) el.checked = false;
  4201. });
  4202. }
  4203. if (fieldKey === 'natstate') {
  4204. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4205. const el = document.getElementById(id);
  4206. if (el) el.checked = false;
  4207. });
  4208. }
  4209. }
  4210. }
  4211. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4212. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4213. toggleMangleField(fieldKey, true);
  4214. let strVal = String(value);
  4215. if (hasInvert) {
  4216. const inv = strVal.startsWith('!');
  4217. if (inv) strVal = strVal.slice(1);
  4218. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4219. if (invEl) invEl.checked = inv;
  4220. }
  4221. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4222. if (valEl) valEl.value = strVal;
  4223. } else {
  4224. toggleMangleField(fieldKey, false);
  4225. }
  4226. }
  4227. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4228. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4229. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4230. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4231. let v = valEl ? valEl.value.trim() : '';
  4232. if (!v) return '';
  4233. if (hasInvert) {
  4234. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4235. if (invEl && invEl.checked) {
  4236. v = '!' + v.replace(/^!/, '');
  4237. }
  4238. }
  4239. return v;
  4240. }
  4241. function toggleMaximizeMangleModal() {
  4242. const win = document.getElementById('mangle-modal-window');
  4243. if (!win) return;
  4244. if (win.classList.contains('max-w-[720px]')) {
  4245. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4246. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4247. } else {
  4248. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4249. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4250. }
  4251. }
  4252. function toggleMangleActionFields() {
  4253. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4254. // Hide all dynamic rows first
  4255. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4256. const el = document.getElementById(`mangle-row-${id}`);
  4257. if (el) el.classList.add('hidden');
  4258. });
  4259. const jumpBox = document.getElementById('mangle-action-jump-box');
  4260. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4261. if (jumpBox) jumpBox.classList.add('hidden');
  4262. if (addrBox) addrBox.classList.add('hidden');
  4263. // Activate matching rows
  4264. if (act === 'mark-connection') {
  4265. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4266. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4267. } else if (act === 'mark-routing') {
  4268. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4269. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4270. } else if (act === 'mark-packet') {
  4271. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4272. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4273. } else if (act === 'change-mss') {
  4274. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4275. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4276. } else if (act === 'change-dscp') {
  4277. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4278. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4279. } else if (act === 'change-ttl') {
  4280. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4281. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4282. } else if (act === 'set-priority') {
  4283. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4284. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4285. } else if (act === 'route') {
  4286. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4287. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4288. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4289. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4290. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4291. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4292. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4293. } else if (act === 'jump') {
  4294. if (jumpBox) jumpBox.classList.remove('hidden');
  4295. } else if (act.includes('address-list') || act.includes('address list')) {
  4296. if (addrBox) addrBox.classList.remove('hidden');
  4297. }
  4298. if (act === 'log') {
  4299. const logEl = document.getElementById('mangle-modal-log');
  4300. if (logEl) logEl.checked = true;
  4301. toggleMangleField('logprefix', true);
  4302. }
  4303. }
  4304. function toggleMangleLogPrefix() {
  4305. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4306. toggleMangleField('logprefix', !!isLog);
  4307. }
  4308. const allMangleFieldKeys = [
  4309. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4310. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4311. 'routingmark', 'conntype', 'cs', 'natstate',
  4312. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4313. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4314. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4315. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4316. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4317. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4318. ];
  4319. function openAddMangleModal() {
  4320. switchMangleRuleTab('general');
  4321. const badge = document.getElementById('mangle-modal-badge');
  4322. if (badge) badge.innerText = 'New...';
  4323. document.getElementById('mangle-modal-id').value = '';
  4324. document.getElementById('mangle-modal-enabled').checked = true;
  4325. document.getElementById('mangle-modal-comment').value = '';
  4326. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4327. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4328. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4329. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4330. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4331. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4332. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4333. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4334. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4335. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4336. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4337. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4338. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4339. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4340. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4341. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4342. populateInterfaceSelect('mangle-val-iniface');
  4343. populateInterfaceSelect('mangle-val-outiface');
  4344. populateAddressListSelect('mangle-val-srclist');
  4345. populateAddressListSelect('mangle-val-dstlist');
  4346. populateGeoIPSelect('mangle-val-srcgeo');
  4347. populateGeoIPSelect('mangle-val-dstgeo');
  4348. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4349. resetCurrentMangleRuleCounters();
  4350. toggleMangleActionFields();
  4351. document.getElementById('mangle-modal').classList.remove('hidden');
  4352. }
  4353. function openEditMangleModal(id) {
  4354. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4355. if (!r) return;
  4356. switchMangleRuleTab('general');
  4357. const badge = document.getElementById('mangle-modal-badge');
  4358. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4359. document.getElementById('mangle-modal-id').value = r.id;
  4360. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4361. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4362. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4363. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4364. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4365. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4366. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4367. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4368. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4369. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4370. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4371. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4372. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4373. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4374. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4375. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4376. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4377. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4378. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4379. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4380. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4381. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4382. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4383. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4384. setMangleFieldVal('src', r.src_address, true);
  4385. setMangleFieldVal('dst', r.dst_address, true);
  4386. setMangleFieldVal('srclist', r.src_address_list, true);
  4387. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4388. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4389. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4390. if (r.protocol && r.protocol !== 'all') {
  4391. setMangleFieldVal('proto', r.protocol, true);
  4392. } else {
  4393. toggleMangleField('proto', false);
  4394. }
  4395. setMangleFieldVal('sport', r.src_port, true);
  4396. setMangleFieldVal('dport', r.dst_port, true);
  4397. setMangleFieldVal('anyport', r.any_port, true);
  4398. setMangleFieldVal('iniface', r.in_interface, true);
  4399. setMangleFieldVal('outiface', r.out_interface, true);
  4400. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4401. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4402. setMangleFieldVal('pktmark', r.packet_mark, true);
  4403. setMangleFieldVal('connmark', r.connection_mark, true);
  4404. setMangleFieldVal('routingmark', r.routing_mark, true);
  4405. setMangleFieldVal('conntype', r.connection_type, false);
  4406. // Connection State
  4407. const states = r.connection_state || [];
  4408. if (states.length > 0) {
  4409. toggleMangleField('cs', true);
  4410. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4411. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4412. if (el) el.checked = states.includes(s);
  4413. });
  4414. } else {
  4415. toggleMangleField('cs', false);
  4416. }
  4417. // Connection NAT State
  4418. const natStates = r.connection_nat_state || [];
  4419. if (natStates.length > 0) {
  4420. toggleMangleField('natstate', true);
  4421. ['srcnat', 'dstnat'].forEach(s => {
  4422. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4423. if (el) el.checked = natStates.includes(s);
  4424. });
  4425. } else {
  4426. toggleMangleField('natstate', false);
  4427. }
  4428. // Advanced tab fields
  4429. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4430. setMangleFieldVal('content', r.content, false);
  4431. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4432. setMangleFieldVal('connrate', r.connection_rate, false);
  4433. setMangleFieldVal('pcc', r.pcc, false);
  4434. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4435. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4436. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4437. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4438. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4439. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4440. setMangleFieldVal('tlshost', r.tls_host, false);
  4441. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4442. setMangleFieldVal('priority', r.priority, false);
  4443. setMangleFieldVal('dscp', r.dscp, false);
  4444. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4445. if (r.tos) {
  4446. const tosEl = document.getElementById('mangle-val-tos');
  4447. if (tosEl) tosEl.value = r.tos;
  4448. }
  4449. setMangleFieldVal('pktsize', r.packet_size, false);
  4450. setMangleFieldVal('random', r.random, false);
  4451. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4452. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4453. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4454. setMangleFieldVal('ttl', r.ttl, false);
  4455. // Extra tab fields
  4456. setMangleFieldVal('nth', r.nth, false);
  4457. setMangleFieldVal('connlimit', r.connection_limit, false);
  4458. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4459. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4460. setMangleFieldVal('hotspot', r.hotspot, false);
  4461. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4462. setMangleFieldVal('limit', r.limit, false);
  4463. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4464. setMangleFieldVal('time', r.time, false);
  4465. setMangleFieldVal('psd', r.psd, false);
  4466. // Action fields
  4467. if (r.jump_target) {
  4468. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4469. if (jtEl) jtEl.value = r.jump_target;
  4470. }
  4471. if (r.address_list) {
  4472. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4473. if (alEl) alEl.value = r.address_list;
  4474. }
  4475. if (r.address_list_timeout) {
  4476. const toEl = document.getElementById('mangle-modal-action-timeout');
  4477. if (toEl) toEl.value = r.address_list_timeout;
  4478. }
  4479. setMangleFieldVal('logprefix', r.log_prefix, false);
  4480. // Statistics
  4481. const bEl = document.getElementById('mangle-stat-bytes');
  4482. const pEl = document.getElementById('mangle-stat-packets');
  4483. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4484. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4485. state.mangleLastBytes = r.bytes || 0;
  4486. state.mangleLastPackets = r.packets || 0;
  4487. state.mangleLastTimestamp = Date.now();
  4488. state.mangleStatRateHistory = new Array(30).fill(0);
  4489. state.mangleStatPktHistory = new Array(30).fill(0);
  4490. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4491. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4492. toggleMangleActionFields();
  4493. document.getElementById('mangle-modal').classList.remove('hidden');
  4494. }
  4495. function closeMangleModal() {
  4496. stopMangleStatPolling();
  4497. document.getElementById('mangle-modal').classList.add('hidden');
  4498. }
  4499. function copyMangleRule() {
  4500. document.getElementById('mangle-modal-id').value = '';
  4501. const badge = document.getElementById('mangle-modal-badge');
  4502. if (badge) badge.innerText = 'New...';
  4503. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4504. }
  4505. function resetCurrentMangleRuleCounters() {
  4506. state.mangleStatRateHistory = new Array(30).fill(0);
  4507. state.mangleStatPktHistory = new Array(30).fill(0);
  4508. state.mangleLastBytes = 0;
  4509. state.mangleLastPackets = 0;
  4510. state.mangleLastTimestamp = Date.now();
  4511. const bEl = document.getElementById('mangle-stat-bytes');
  4512. const pEl = document.getElementById('mangle-stat-packets');
  4513. const rEl = document.getElementById('mangle-stat-rate');
  4514. const prEl = document.getElementById('mangle-stat-pktrate');
  4515. if (bEl) bEl.value = '0 B';
  4516. if (pEl) pEl.value = '0';
  4517. if (rEl) rEl.value = '0 bps';
  4518. if (prEl) prEl.value = '0 p/s';
  4519. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4520. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4521. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4522. }
  4523. async function applyMangleRule(closeAfter = false) {
  4524. const id = document.getElementById('mangle-modal-id').value;
  4525. const chain = document.getElementById('mangle-modal-chain').value;
  4526. const action = document.getElementById('mangle-modal-action').value;
  4527. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4528. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4529. const src = getMangleFieldVal('src', true);
  4530. const dst = getMangleFieldVal('dst', true);
  4531. const srclist = getMangleFieldVal('srclist', true);
  4532. const dstlist = getMangleFieldVal('dstlist', true);
  4533. const srcgeo = getMangleFieldVal('srcgeo', true);
  4534. const dstgeo = getMangleFieldVal('dstgeo', true);
  4535. const proto = getMangleFieldVal('proto', true);
  4536. const sport = getMangleFieldVal('sport', true);
  4537. const dport = getMangleFieldVal('dport', true);
  4538. const anyport = getMangleFieldVal('anyport', true);
  4539. const iniface = getMangleFieldVal('iniface', true);
  4540. const outiface = getMangleFieldVal('outiface', true);
  4541. const inifacelist = getMangleFieldVal('inifacelist', true);
  4542. const outifacelist = getMangleFieldVal('outifacelist', true);
  4543. const pktmark = getMangleFieldVal('pktmark', true);
  4544. const connmark = getMangleFieldVal('connmark', true);
  4545. const routingmark = getMangleFieldVal('routingmark', true);
  4546. const conntype = getMangleFieldVal('conntype', false);
  4547. const states = [];
  4548. const csBox = document.getElementById('mangle-field-cs');
  4549. if (csBox && !csBox.classList.contains('hidden')) {
  4550. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4551. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4552. });
  4553. }
  4554. const natStates = [];
  4555. const natBox = document.getElementById('mangle-field-natstate');
  4556. if (natBox && !natBox.classList.contains('hidden')) {
  4557. ['srcnat', 'dstnat'].forEach(s => {
  4558. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4559. });
  4560. }
  4561. const payload = {
  4562. id,
  4563. chain,
  4564. action,
  4565. protocol: proto || 'all',
  4566. src_address: src,
  4567. dst_address: dst,
  4568. src_port: sport,
  4569. dst_port: dport,
  4570. any_port: anyport,
  4571. in_interface: iniface,
  4572. out_interface: outiface,
  4573. in_interface_list: inifacelist,
  4574. out_interface_list: outifacelist,
  4575. packet_mark: pktmark,
  4576. connection_mark: connmark,
  4577. routing_mark: routingmark,
  4578. connection_type: conntype,
  4579. connection_state: states,
  4580. connection_nat_state: natStates,
  4581. src_address_list: srclist,
  4582. dst_address_list: dstlist,
  4583. src_geoip: srcgeo,
  4584. dst_geoip: dstgeo,
  4585. comment,
  4586. disabled: !enabled,
  4587. // Advanced tab
  4588. layer7_protocol: getMangleFieldVal('layer7', false),
  4589. content: getMangleFieldVal('content', false),
  4590. connection_bytes: getMangleFieldVal('connbytes', false),
  4591. connection_rate: getMangleFieldVal('connrate', false),
  4592. pcc: getMangleFieldVal('pcc', false),
  4593. src_mac_address: getMangleFieldVal('srcmac', true),
  4594. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4595. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4596. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4597. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4598. ipsec_policy: getMangleFieldVal('ipsec', false),
  4599. tls_host: getMangleFieldVal('tlshost', false),
  4600. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4601. priority: getMangleFieldVal('priority', false),
  4602. dscp: getMangleFieldVal('dscp', false),
  4603. tcp_mss: getMangleFieldVal('tcpmss', false),
  4604. tos: document.getElementById('mangle-val-tos')?.value || '',
  4605. packet_size: getMangleFieldVal('pktsize', false),
  4606. random: getMangleFieldVal('random', false),
  4607. tcp_flags: getMangleFieldVal('tcpflags', false),
  4608. icmp_options: getMangleFieldVal('icmpoptions', false),
  4609. ipv4_options: getMangleFieldVal('ipv4options', false),
  4610. ttl: getMangleFieldVal('ttl', false),
  4611. // Extra tab
  4612. nth: getMangleFieldVal('nth', false),
  4613. connection_limit: getMangleFieldVal('connlimit', false),
  4614. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4615. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4616. hotspot: getMangleFieldVal('hotspot', false),
  4617. ip_fragment: getMangleFieldVal('ipfragment', false),
  4618. limit: getMangleFieldVal('limit', false),
  4619. dst_limit: getMangleFieldVal('dstlimit', false),
  4620. time: getMangleFieldVal('time', false),
  4621. psd: getMangleFieldVal('psd', false),
  4622. // Action tab
  4623. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4624. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4625. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4626. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4627. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4628. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4629. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4630. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4631. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4632. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4633. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4634. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4635. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4636. log: document.getElementById('mangle-modal-log')?.checked || false,
  4637. log_prefix: getMangleFieldVal('logprefix', false)
  4638. };
  4639. try {
  4640. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4641. method: 'POST',
  4642. headers: { 'Content-Type': 'application/json' },
  4643. body: JSON.stringify(payload)
  4644. });
  4645. if (res.ok) {
  4646. const data = await res.json();
  4647. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4648. loadFirewall(false);
  4649. if (closeAfter) {
  4650. closeMangleModal();
  4651. } else {
  4652. if (data.id) {
  4653. document.getElementById('mangle-modal-id').value = data.id;
  4654. const badge = document.getElementById('mangle-modal-badge');
  4655. if (badge) badge.innerText = `#${data.id}`;
  4656. }
  4657. }
  4658. } else {
  4659. const err = await res.json();
  4660. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4661. }
  4662. } catch (err) {
  4663. showToast('Error', err.message, 'error');
  4664. }
  4665. }
  4666. function submitSaveMangleRule(e) {
  4667. if (e && e.preventDefault) e.preventDefault();
  4668. return applyMangleRule(true);
  4669. }
  4670. function startMangleStatPolling() {
  4671. stopMangleStatPolling();
  4672. pollMangleRuleStats();
  4673. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4674. }
  4675. function stopMangleStatPolling() {
  4676. if (state.mangleStatInterval) {
  4677. clearInterval(state.mangleStatInterval);
  4678. state.mangleStatInterval = null;
  4679. }
  4680. }
  4681. async function pollMangleRuleStats() {
  4682. const id = document.getElementById('mangle-modal-id')?.value;
  4683. if (!id) {
  4684. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4685. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4686. return;
  4687. }
  4688. try {
  4689. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4690. if (!res.ok) return;
  4691. const rules = await res.json();
  4692. const r = rules.find(x => x.id === id);
  4693. if (!r) return;
  4694. const now = Date.now();
  4695. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4696. state.mangleLastTimestamp = now;
  4697. const curBytes = r.bytes || 0;
  4698. const curPackets = r.packets || 0;
  4699. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4700. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4701. state.mangleLastBytes = curBytes;
  4702. state.mangleLastPackets = curPackets;
  4703. const rateBps = Math.round((deltaBytes * 8) / dt);
  4704. const ratePkt = Math.round(deltaPkts / dt);
  4705. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4706. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4707. state.mangleStatRateHistory.push(rateBps);
  4708. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4709. state.mangleStatPktHistory.push(ratePkt);
  4710. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4711. const bEl = document.getElementById('mangle-stat-bytes');
  4712. const pEl = document.getElementById('mangle-stat-packets');
  4713. const rEl = document.getElementById('mangle-stat-rate');
  4714. const prEl = document.getElementById('mangle-stat-pktrate');
  4715. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4716. if (pEl) pEl.value = curPackets.toLocaleString();
  4717. if (rEl) rEl.value = formatBps(rateBps);
  4718. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4719. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4720. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4721. } catch (e) {
  4722. console.error('Error polling Mangle rule stats', e);
  4723. }
  4724. }
  4725. async function moveMangleRule(id, dir) {
  4726. try {
  4727. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4728. method: 'POST',
  4729. headers: { 'Content-Type': 'application/json' },
  4730. body: JSON.stringify({ direction: dir })
  4731. });
  4732. if (res.ok) loadFirewall(false);
  4733. } catch (err) {
  4734. showToast('Error', err.message, 'error');
  4735. }
  4736. }
  4737. async function toggleMangleRuleState(id, disabled) {
  4738. try {
  4739. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4740. method: 'POST',
  4741. headers: { 'Content-Type': 'application/json' },
  4742. body: JSON.stringify({ disabled })
  4743. });
  4744. if (res.ok) loadFirewall(false);
  4745. } catch (err) {
  4746. showToast('Error', err.message, 'error');
  4747. }
  4748. }
  4749. async function deleteMangleRule(id) {
  4750. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4751. try {
  4752. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4753. if (res.ok) {
  4754. showToast('Deleted', 'Mangle rule removed', 'success');
  4755. loadFirewall(false);
  4756. }
  4757. } catch (err) {
  4758. showToast('Error', err.message, 'error');
  4759. }
  4760. }
  4761. // ----------------- Address Lists -----------------
  4762. function renderAddressLists() {
  4763. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4764. const tbody = document.getElementById('addrlist-table-body');
  4765. const empty = document.getElementById('addrlist-empty');
  4766. if (!tbody) return;
  4767. tbody.innerHTML = '';
  4768. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4769. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4770. // Update filter select
  4771. const sel = document.getElementById('addrlist-filter-name');
  4772. if (sel) {
  4773. const cur = sel.value;
  4774. sel.innerHTML = '<option value="">All Lists</option>';
  4775. const set = new Set((state.addressLists || []).map(a => a.name));
  4776. set.forEach(n => {
  4777. const opt = document.createElement('option');
  4778. opt.value = n;
  4779. opt.innerText = n;
  4780. if (n === cur) opt.selected = true;
  4781. sel.appendChild(opt);
  4782. });
  4783. }
  4784. if (entries.length === 0) {
  4785. empty?.classList.remove('hidden');
  4786. return;
  4787. }
  4788. empty?.classList.add('hidden');
  4789. entries.forEach((e, idx) => {
  4790. const tr = document.createElement('tr');
  4791. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4792. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4793. tr.innerHTML = `
  4794. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4795. <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>
  4796. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4797. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4798. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4799. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4800. <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>
  4801. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4802. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4803. </td>
  4804. `;
  4805. tbody.appendChild(tr);
  4806. });
  4807. populateCommonAddrListDatalist();
  4808. }
  4809. function openAddAddrListModal() {
  4810. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4811. document.getElementById('addrlist-modal-id').value = '';
  4812. document.getElementById('addrlist-modal-name').value = '';
  4813. document.getElementById('addrlist-modal-addr').value = '';
  4814. document.getElementById('addrlist-modal-comment').value = '';
  4815. document.getElementById('addrlist-modal-disabled').checked = false;
  4816. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4817. if (submitBtn) submitBtn.innerText = 'Add to List';
  4818. document.getElementById('addrlist-modal').classList.remove('hidden');
  4819. }
  4820. function openEditAddrListModal(id) {
  4821. const e = (state.addressLists || []).find(item => item.id === id);
  4822. if (!e) return;
  4823. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4824. document.getElementById('addrlist-modal-id').value = e.id;
  4825. document.getElementById('addrlist-modal-name').value = e.name;
  4826. document.getElementById('addrlist-modal-addr').value = e.address;
  4827. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4828. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4829. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4830. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4831. document.getElementById('addrlist-modal').classList.remove('hidden');
  4832. }
  4833. function closeAddrListModal() {
  4834. document.getElementById('addrlist-modal').classList.add('hidden');
  4835. }
  4836. async function submitSaveAddrList(e) {
  4837. e.preventDefault();
  4838. const id = document.getElementById('addrlist-modal-id').value;
  4839. const name = document.getElementById('addrlist-modal-name').value.trim();
  4840. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4841. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4842. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4843. try {
  4844. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4845. method: 'POST',
  4846. headers: { 'Content-Type': 'application/json' },
  4847. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4848. });
  4849. if (res.ok) {
  4850. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4851. closeAddrListModal();
  4852. loadFirewall(false);
  4853. } else {
  4854. const err = await res.json();
  4855. showToast('Error', err.message || 'Failed to save address list', 'error');
  4856. }
  4857. } catch (err) {
  4858. showToast('Error', err.message, 'error');
  4859. }
  4860. }
  4861. async function toggleAddrListState(id, disabled) {
  4862. try {
  4863. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4864. method: 'POST',
  4865. headers: { 'Content-Type': 'application/json' },
  4866. body: JSON.stringify({ disabled })
  4867. });
  4868. if (res.ok) {
  4869. loadFirewall(false);
  4870. }
  4871. } catch (err) {
  4872. showToast('Error', err.message, 'error');
  4873. }
  4874. }
  4875. async function deleteAddrList(id) {
  4876. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4877. try {
  4878. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4879. if (res.ok) {
  4880. showToast('Deleted', 'Address list item removed', 'info');
  4881. loadFirewall(false);
  4882. }
  4883. } catch (err) {
  4884. showToast('Error', err.message, 'error');
  4885. }
  4886. }
  4887. // ----------------- Geo-Location IP Management -----------------
  4888. async function loadGeoIP() {
  4889. try {
  4890. const [statusRes, countriesRes] = await Promise.all([
  4891. fetch(`${API_BASE}/firewall/geoip/status`),
  4892. fetch(`${API_BASE}/firewall/geoip/countries`)
  4893. ]);
  4894. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4895. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4896. updateGeoHeader();
  4897. renderGeoCountries();
  4898. } catch (err) {
  4899. console.error('Failed to load GeoIP:', err);
  4900. }
  4901. }
  4902. function getGeoUsageMap() {
  4903. const usage = {};
  4904. const checkRule = (r, type) => {
  4905. ['src_geoip', 'dst_geoip'].forEach(field => {
  4906. let val = (r && r[field]) || '';
  4907. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4908. if (code) {
  4909. if (!usage[code]) usage[code] = [];
  4910. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4911. if (!usage[code].includes(label)) usage[code].push(label);
  4912. }
  4913. });
  4914. };
  4915. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4916. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4917. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4918. return usage;
  4919. }
  4920. function updateGeoHeader() {
  4921. const s = state.geoStatus || {};
  4922. const statusBadge = document.getElementById('geo-status-badge');
  4923. if (statusBadge) {
  4924. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4925. statusBadge.className = s.auto_update
  4926. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4927. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4928. }
  4929. const intervalLabel = document.getElementById('geo-interval-label');
  4930. if (intervalLabel) {
  4931. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4932. }
  4933. const usageMap = getGeoUsageMap();
  4934. const inUseCount = Object.keys(usageMap).length;
  4935. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4936. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4937. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4938. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4939. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4940. if (lastSyncEl) {
  4941. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4942. const d = new Date(s.last_updated);
  4943. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4944. } else {
  4945. lastSyncEl.innerText = 'Never (Sync Pending)';
  4946. }
  4947. }
  4948. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4949. if (nextSyncEl) {
  4950. if (s.next_update && !s.next_update.startsWith('0001')) {
  4951. const d = new Date(s.next_update);
  4952. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4953. } else {
  4954. nextSyncEl.innerText = '-';
  4955. }
  4956. }
  4957. const badge = document.getElementById('fw-badge-geo');
  4958. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4959. }
  4960. function renderGeoCountries() {
  4961. const tbody = document.getElementById('geo-table-body');
  4962. const empty = document.getElementById('geo-empty');
  4963. if (!tbody) return;
  4964. tbody.innerHTML = '';
  4965. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4966. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4967. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4968. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4969. const usageMap = getGeoUsageMap();
  4970. const countries = (state.geoCountries || []).filter(c => {
  4971. const isUsed = !!usageMap[c.code];
  4972. if (inUseOnly && !isUsed) return false;
  4973. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4974. if (continent && c.continent !== continent) return false;
  4975. if (q) {
  4976. const matchCode = c.code.toLowerCase().includes(q);
  4977. const matchName = c.name.toLowerCase().includes(q);
  4978. if (!matchCode && !matchName) return false;
  4979. }
  4980. return true;
  4981. });
  4982. if (countries.length === 0) {
  4983. empty?.classList.remove('hidden');
  4984. return;
  4985. }
  4986. empty?.classList.add('hidden');
  4987. countries.forEach(c => {
  4988. const tr = document.createElement('tr');
  4989. const isUsed = !!usageMap[c.code];
  4990. const rulesUsing = usageMap[c.code] || [];
  4991. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4992. let statusHtml = '';
  4993. if (isUsed) {
  4994. 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>`;
  4995. } else if (c.subnet_count > 0) {
  4996. 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>';
  4997. } else {
  4998. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4999. }
  5000. tr.innerHTML = `
  5001. <td class="py-2.5 px-3 text-center">
  5002. <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'}">
  5003. ${c.code}
  5004. </span>
  5005. </td>
  5006. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5007. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5008. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5009. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5010. </td>
  5011. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5012. <td class="py-2.5 px-3">
  5013. ${statusHtml}
  5014. </td>
  5015. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5016. <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>
  5017. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5018. </td>
  5019. `;
  5020. tbody.appendChild(tr);
  5021. });
  5022. }
  5023. function quickFilterGeo(preset) {
  5024. const searchInput = document.getElementById('geo-search-input');
  5025. const continentSel = document.getElementById('geo-continent-filter');
  5026. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5027. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5028. if (searchInput) searchInput.value = '';
  5029. if (continentSel) continentSel.value = '';
  5030. if (inUseCheck) inUseCheck.checked = false;
  5031. if (cachedCheck) cachedCheck.checked = false;
  5032. if (preset === 'GR') {
  5033. if (searchInput) searchInput.value = 'Greece';
  5034. } else if (preset === 'Europe') {
  5035. if (continentSel) continentSel.value = 'Europe';
  5036. } else if (preset === 'HIGHRISK') {
  5037. if (searchInput) searchInput.value = 'China';
  5038. }
  5039. renderGeoCountries();
  5040. }
  5041. async function toggleGeoCountry(code, enabled) {
  5042. try {
  5043. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5044. method: 'POST',
  5045. headers: { 'Content-Type': 'application/json' },
  5046. body: JSON.stringify({ enabled })
  5047. });
  5048. if (res.ok) {
  5049. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5050. loadGeoIP();
  5051. } else {
  5052. const err = await res.json();
  5053. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5054. }
  5055. } catch (err) {
  5056. showToast('Error', err.message, 'error');
  5057. }
  5058. }
  5059. async function updateGeoCountry(code) {
  5060. try {
  5061. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5062. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5063. if (res.ok) {
  5064. const data = await res.json();
  5065. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5066. loadGeoIP();
  5067. } else {
  5068. const err = await res.json();
  5069. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5070. }
  5071. } catch (err) {
  5072. showToast('Error', err.message, 'error');
  5073. }
  5074. }
  5075. async function triggerGeoUpdateNow() {
  5076. const spinner = document.getElementById('geo-update-spinner');
  5077. if (spinner) spinner.classList.remove('hidden');
  5078. try {
  5079. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5080. if (res.ok) {
  5081. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5082. setTimeout(() => {
  5083. loadGeoIP();
  5084. if (spinner) spinner.classList.add('hidden');
  5085. }, 2500);
  5086. } else {
  5087. const err = await res.json();
  5088. showToast('Notice', err.message || 'Update in progress', 'info');
  5089. if (spinner) spinner.classList.add('hidden');
  5090. }
  5091. } catch (err) {
  5092. showToast('Error', err.message, 'error');
  5093. if (spinner) spinner.classList.add('hidden');
  5094. }
  5095. }
  5096. async function applyGeoPreset(preset) {
  5097. try {
  5098. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5099. method: 'POST',
  5100. headers: { 'Content-Type': 'application/json' },
  5101. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5102. });
  5103. if (res.ok) {
  5104. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5105. loadGeoIP();
  5106. }
  5107. } catch (err) {
  5108. showToast('Error', err.message, 'error');
  5109. }
  5110. }
  5111. function openGeoIntervalModal() {
  5112. const s = state.geoStatus || {};
  5113. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5114. const sel = document.getElementById('geo-cfg-interval');
  5115. const customBox = document.getElementById('geo-cfg-custom-box');
  5116. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5117. const curHours = s.interval_hours || 24;
  5118. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5119. if (matchOption) {
  5120. sel.value = String(curHours);
  5121. customBox.classList.add('hidden');
  5122. } else {
  5123. sel.value = 'custom';
  5124. customHoursInput.value = curHours;
  5125. customBox.classList.remove('hidden');
  5126. }
  5127. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5128. }
  5129. function closeGeoIntervalModal() {
  5130. document.getElementById('geo-interval-modal').classList.add('hidden');
  5131. }
  5132. function toggleCustomGeoInterval() {
  5133. const val = document.getElementById('geo-cfg-interval').value;
  5134. const customBox = document.getElementById('geo-cfg-custom-box');
  5135. if (val === 'custom') {
  5136. customBox.classList.remove('hidden');
  5137. } else {
  5138. customBox.classList.add('hidden');
  5139. }
  5140. }
  5141. async function submitGeoIntervalSettings(e) {
  5142. e.preventDefault();
  5143. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5144. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5145. let hours = 24;
  5146. if (intervalVal === 'custom') {
  5147. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5148. } else {
  5149. hours = parseInt(intervalVal, 10) || 24;
  5150. }
  5151. try {
  5152. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5153. method: 'POST',
  5154. headers: { 'Content-Type': 'application/json' },
  5155. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5156. });
  5157. if (res.ok) {
  5158. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5159. closeGeoIntervalModal();
  5160. loadGeoIP();
  5161. } else {
  5162. const err = await res.json();
  5163. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5164. }
  5165. } catch (err) {
  5166. showToast('Error', err.message, 'error');
  5167. }
  5168. }
  5169. async function viewGeoSubnets(code, name) {
  5170. if (!name) {
  5171. const found = (state.geoCountries || []).find(x => x.code === code);
  5172. name = found ? found.name : code;
  5173. }
  5174. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5175. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5176. const listEl = document.getElementById('geo-subnets-list');
  5177. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5178. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5179. try {
  5180. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5181. if (res.ok) {
  5182. const data = await res.json();
  5183. const subnets = data.subnets || [];
  5184. if (subnets.length === 0) {
  5185. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5186. } else {
  5187. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5188. }
  5189. } else {
  5190. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5191. }
  5192. } catch (err) {
  5193. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5194. }
  5195. }
  5196. function closeGeoSubnetsModal() {
  5197. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5198. }
  5199. // ----------------- Active Connections Tracking -----------------
  5200. async function loadConnections() {
  5201. try {
  5202. const res = await fetch(`${API_BASE}/firewall/connections`);
  5203. const data = await res.json();
  5204. state.connections = Array.isArray(data) ? data : [];
  5205. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5206. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5207. renderConnections();
  5208. } catch (err) {
  5209. console.error('Failed to load connections:', err);
  5210. }
  5211. }
  5212. function renderConnections() {
  5213. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5214. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5215. const tbody = document.getElementById('conns-table-body');
  5216. const empty = document.getElementById('conns-empty');
  5217. if (!tbody) return;
  5218. tbody.innerHTML = '';
  5219. const conns = (state.connections || []).filter(c => {
  5220. if (protoFilter && c.protocol !== protoFilter) return false;
  5221. if (search) {
  5222. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5223. if (!line.includes(search)) return false;
  5224. }
  5225. return true;
  5226. });
  5227. if (conns.length === 0) {
  5228. empty?.classList.remove('hidden');
  5229. return;
  5230. }
  5231. empty?.classList.add('hidden');
  5232. conns.slice(0, 150).forEach(c => {
  5233. const tr = document.createElement('tr');
  5234. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5235. let stateColor = 'text-slate-400';
  5236. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5237. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5238. tr.innerHTML = `
  5239. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5240. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5241. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5242. <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>
  5243. <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>
  5244. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5245. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5246. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5247. <td class="py-2.5 px-3 text-right font-sans">
  5248. <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>
  5249. </td>
  5250. `;
  5251. tbody.appendChild(tr);
  5252. });
  5253. }
  5254. async function killConnection(protocol, src, sport, dst, dport) {
  5255. try {
  5256. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5257. method: 'POST',
  5258. headers: { 'Content-Type': 'application/json' },
  5259. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5260. });
  5261. if (res.ok) {
  5262. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5263. loadConnections();
  5264. }
  5265. } catch (err) {
  5266. showToast('Error', err.message, 'error');
  5267. }
  5268. }
  5269. async function resetFirewallCounters() {
  5270. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5271. try {
  5272. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5273. if (res.ok) {
  5274. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5275. loadFirewall(false);
  5276. }
  5277. } catch (err) {
  5278. showToast('Error', err.message, 'error');
  5279. }
  5280. }
  5281. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5282. function switchRoutesSubTab(tab) {
  5283. state.routesSubTab = tab;
  5284. const tabs = ['routes', 'rules', 'tables'];
  5285. tabs.forEach(t => {
  5286. const panel = document.getElementById(`routes-subtab-${t}`);
  5287. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5288. if (panel) {
  5289. if (t === tab) panel.classList.remove('hidden');
  5290. else panel.classList.add('hidden');
  5291. }
  5292. if (btn) {
  5293. if (t === tab) {
  5294. 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';
  5295. } else {
  5296. 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';
  5297. }
  5298. }
  5299. });
  5300. setTimeout(initTableSorting, 50);
  5301. }
  5302. async function loadRoutes() {
  5303. try {
  5304. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5305. fetch(`${API_BASE}/routes`),
  5306. fetch(`${API_BASE}/routing/rules`),
  5307. fetch(`${API_BASE}/routing/tables`)
  5308. ]);
  5309. if (routesRes.ok) state.routes = await routesRes.json();
  5310. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5311. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5312. const bRoutes = document.getElementById('routes-badge-routes');
  5313. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5314. const showSystem = document.getElementById('prule-show-system')?.checked;
  5315. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5316. const bRules = document.getElementById('routes-badge-rules');
  5317. if (bRules) bRules.innerText = userRules.length;
  5318. const bTables = document.getElementById('routes-badge-tables');
  5319. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5320. const bRoutesCount = document.getElementById('badge-routes-count');
  5321. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5322. renderRoutesList();
  5323. renderPolicyRules();
  5324. renderRoutingTables();
  5325. } catch (err) {
  5326. console.error('Failed to load routing:', err);
  5327. }
  5328. }
  5329. function renderRoutesList() {
  5330. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5331. const tbody = document.getElementById('routes-table-body');
  5332. const empty = document.getElementById('routes-empty');
  5333. if (!tbody) return;
  5334. tbody.innerHTML = '';
  5335. // Update table filter select
  5336. const sel = document.getElementById('routes-filter-table');
  5337. if (sel) {
  5338. const cur = sel.value;
  5339. sel.innerHTML = '<option value="">All Tables</option>';
  5340. (state.routingTables || []).forEach(t => {
  5341. const opt = document.createElement('option');
  5342. opt.value = t.name;
  5343. opt.innerText = t.name;
  5344. if (t.name === cur) opt.selected = true;
  5345. sel.appendChild(opt);
  5346. });
  5347. }
  5348. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5349. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5350. if (routes.length === 0) {
  5351. empty?.classList.remove('hidden');
  5352. return;
  5353. }
  5354. empty?.classList.add('hidden');
  5355. routes.forEach(r => {
  5356. const tr = document.createElement('tr');
  5357. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5358. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5359. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5360. let flags = '';
  5361. if (r.dynamic) flags += 'D';
  5362. if (r.active) flags += 'A';
  5363. if (r.connect) flags += 'C';
  5364. if (r.static) flags += 'S';
  5365. if (r.disabled) flags += 'X';
  5366. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5367. tr.innerHTML = `
  5368. <td class="py-2.5 px-3 text-center">
  5369. <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'}">
  5370. ${flags || '-'}
  5371. </span>
  5372. </td>
  5373. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5374. <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>
  5375. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5376. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5377. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5378. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5379. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5380. ${r.static ? `
  5381. <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>
  5382. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5383. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5384. ` : `
  5385. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5386. `}
  5387. </td>
  5388. `;
  5389. tbody.appendChild(tr);
  5390. });
  5391. }
  5392. function openAddRouteModal() {
  5393. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5394. document.getElementById('route-modal-id').value = '';
  5395. document.getElementById('route-modal-old-dst').value = '';
  5396. document.getElementById('route-modal-old-gw').value = '';
  5397. document.getElementById('route-modal-old-distance').value = '';
  5398. document.getElementById('route-modal-old-table').value = '';
  5399. document.getElementById('route-modal-old-iface').value = '';
  5400. const dstInput = document.getElementById('route-modal-dst');
  5401. const gwInput = document.getElementById('route-modal-gw');
  5402. const distInput = document.getElementById('route-modal-distance');
  5403. const ifaceSelect = document.getElementById('route-modal-iface');
  5404. const tableSelect = document.getElementById('route-modal-table');
  5405. const commentInput = document.getElementById('route-modal-comment');
  5406. const disCheck = document.getElementById('route-modal-disabled');
  5407. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5408. dstInput.disabled = false;
  5409. dstInput.value = '0.0.0.0/0';
  5410. gwInput.disabled = false;
  5411. gwInput.value = '';
  5412. distInput.disabled = false;
  5413. distInput.value = '1';
  5414. ifaceSelect.disabled = false;
  5415. tableSelect.disabled = false;
  5416. commentInput.disabled = false;
  5417. commentInput.value = '';
  5418. disCheck.disabled = false;
  5419. disCheck.checked = false;
  5420. if (saveBtn) saveBtn.classList.remove('hidden');
  5421. populateInterfaceSelect('route-modal-iface');
  5422. // Populate tables
  5423. tableSelect.innerHTML = '';
  5424. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5425. const opt = document.createElement('option');
  5426. opt.value = t.name;
  5427. opt.innerText = t.name;
  5428. if (t.name === 'main') opt.selected = true;
  5429. tableSelect.appendChild(opt);
  5430. });
  5431. document.getElementById('route-modal').classList.remove('hidden');
  5432. }
  5433. function openEditRouteModal(id) {
  5434. const r = (state.routes || []).find(route => route.id === id);
  5435. if (!r) return;
  5436. const isStatic = !!r.static;
  5437. document.getElementById('route-modal-title').innerText = isStatic
  5438. ? `Edit Route: ${r.dst_address}`
  5439. : `Route Properties (Read Only): ${r.dst_address}`;
  5440. document.getElementById('route-modal-id').value = r.id;
  5441. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5442. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5443. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5444. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5445. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5446. const dstInput = document.getElementById('route-modal-dst');
  5447. const gwInput = document.getElementById('route-modal-gw');
  5448. const distInput = document.getElementById('route-modal-distance');
  5449. const ifaceSelect = document.getElementById('route-modal-iface');
  5450. const tableSelect = document.getElementById('route-modal-table');
  5451. const commentInput = document.getElementById('route-modal-comment');
  5452. const disCheck = document.getElementById('route-modal-disabled');
  5453. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5454. dstInput.value = r.dst_address;
  5455. gwInput.value = r.gateway || '';
  5456. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5457. commentInput.value = r.comment || '';
  5458. disCheck.checked = !!r.disabled;
  5459. dstInput.disabled = !isStatic;
  5460. gwInput.disabled = !isStatic;
  5461. distInput.disabled = !isStatic;
  5462. ifaceSelect.disabled = !isStatic;
  5463. tableSelect.disabled = !isStatic;
  5464. commentInput.disabled = !isStatic;
  5465. disCheck.disabled = !isStatic;
  5466. if (saveBtn) {
  5467. if (isStatic) {
  5468. saveBtn.classList.remove('hidden');
  5469. } else {
  5470. saveBtn.classList.add('hidden');
  5471. }
  5472. }
  5473. populateInterfaceSelect('route-modal-iface', r.interface);
  5474. tableSelect.innerHTML = '';
  5475. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5476. const opt = document.createElement('option');
  5477. opt.value = t.name;
  5478. opt.innerText = t.name;
  5479. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5480. tableSelect.appendChild(opt);
  5481. });
  5482. document.getElementById('route-modal').classList.remove('hidden');
  5483. }
  5484. function closeRouteModal() {
  5485. document.getElementById('route-modal').classList.add('hidden');
  5486. }
  5487. async function submitSaveRoute(e) {
  5488. e.preventDefault();
  5489. const id = document.getElementById('route-modal-id').value;
  5490. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5491. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5492. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5493. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5494. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5495. const dst = document.getElementById('route-modal-dst').value.trim();
  5496. const gw = document.getElementById('route-modal-gw').value.trim();
  5497. const table = document.getElementById('route-modal-table').value;
  5498. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5499. const iface = document.getElementById('route-modal-iface').value;
  5500. const comment = document.getElementById('route-modal-comment').value.trim();
  5501. const disabled = document.getElementById('route-modal-disabled').checked;
  5502. if (!dst) {
  5503. showToast('Error', 'Destination address is required', 'error');
  5504. return;
  5505. }
  5506. if (!gw && !iface) {
  5507. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5508. return;
  5509. }
  5510. const payload = {
  5511. id,
  5512. old_dst_address: oldDst,
  5513. old_gateway: oldGw,
  5514. old_routing_table: oldTable,
  5515. old_interface: oldIface,
  5516. dst_address: dst,
  5517. gateway: gw || iface,
  5518. routing_table: table,
  5519. distance,
  5520. interface: iface,
  5521. comment,
  5522. disabled
  5523. };
  5524. if (oldDistStr !== undefined && oldDistStr !== '') {
  5525. payload.old_distance = parseInt(oldDistStr, 10);
  5526. }
  5527. try {
  5528. const res = await fetch(`${API_BASE}/routes`, {
  5529. method: 'POST',
  5530. headers: { 'Content-Type': 'application/json' },
  5531. body: JSON.stringify(payload)
  5532. });
  5533. if (res.ok) {
  5534. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5535. closeRouteModal();
  5536. loadRoutes();
  5537. } else {
  5538. const err = await res.json();
  5539. showToast('Error', err.message || 'Failed to save route', 'error');
  5540. }
  5541. } catch (err) {
  5542. showToast('Error', err.message, 'error');
  5543. }
  5544. }
  5545. async function toggleRouteState(id, disabled) {
  5546. try {
  5547. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5548. method: 'POST',
  5549. headers: { 'Content-Type': 'application/json' },
  5550. body: JSON.stringify({ disabled })
  5551. });
  5552. if (res.ok) loadRoutes();
  5553. } catch (err) {
  5554. showToast('Error', err.message, 'error');
  5555. }
  5556. }
  5557. async function deleteRoute(id) {
  5558. if (!confirm('Are you sure you want to delete this route?')) return;
  5559. try {
  5560. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5561. if (res.ok) {
  5562. showToast('Deleted', 'Route removed', 'success');
  5563. loadRoutes();
  5564. }
  5565. } catch (err) {
  5566. showToast('Error', err.message, 'error');
  5567. }
  5568. }
  5569. // ----------------- Policy Rules (/ip route rule) -----------------
  5570. function renderPolicyRules() {
  5571. const tbody = document.getElementById('rules-table-body');
  5572. const empty = document.getElementById('rules-empty');
  5573. if (!tbody) return;
  5574. tbody.innerHTML = '';
  5575. const showSystem = document.getElementById('prule-show-system')?.checked;
  5576. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5577. const countBadge = document.getElementById('rules-count-badge');
  5578. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5579. const bRules = document.getElementById('routes-badge-rules');
  5580. if (bRules) bRules.innerText = filtered.length;
  5581. if (filtered.length === 0) {
  5582. empty?.classList.remove('hidden');
  5583. return;
  5584. }
  5585. empty?.classList.add('hidden');
  5586. filtered.forEach(pr => {
  5587. const isSys = pr.is_default || pr.is_system;
  5588. const tr = document.createElement('tr');
  5589. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5590. tr.innerHTML = `
  5591. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5592. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5593. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5594. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5595. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5596. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5597. <td class="py-2.5 px-3 text-right font-sans">
  5598. ${!pr.is_default ? `
  5599. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5600. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5601. </td>
  5602. `;
  5603. tbody.appendChild(tr);
  5604. });
  5605. }
  5606. function openAddPolicyRuleModal() {
  5607. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5608. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5609. document.getElementById('prule-modal-mark').value = '';
  5610. document.getElementById('prule-modal-src').value = '';
  5611. document.getElementById('prule-modal-dst').value = '';
  5612. const sel = document.getElementById('prule-modal-table');
  5613. sel.innerHTML = '';
  5614. (state.routingTables || []).forEach(t => {
  5615. const opt = document.createElement('option');
  5616. opt.value = t.name;
  5617. opt.innerText = t.name;
  5618. sel.appendChild(opt);
  5619. });
  5620. document.getElementById('prule-modal').classList.remove('hidden');
  5621. }
  5622. function closePolicyRuleModal() {
  5623. document.getElementById('prule-modal').classList.add('hidden');
  5624. }
  5625. async function submitSavePolicyRule(e) {
  5626. e.preventDefault();
  5627. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5628. const mark = document.getElementById('prule-modal-mark').value.trim();
  5629. const src = document.getElementById('prule-modal-src').value.trim();
  5630. const dst = document.getElementById('prule-modal-dst').value.trim();
  5631. const table = document.getElementById('prule-modal-table').value;
  5632. const action = document.getElementById('prule-modal-action').value;
  5633. try {
  5634. const res = await fetch(`${API_BASE}/routing/rules`, {
  5635. method: 'POST',
  5636. headers: { 'Content-Type': 'application/json' },
  5637. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5638. });
  5639. if (res.ok) {
  5640. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5641. closePolicyRuleModal();
  5642. loadRoutes();
  5643. } else {
  5644. const err = await res.json();
  5645. showToast('Error', err.message, 'error');
  5646. }
  5647. } catch (err) {
  5648. showToast('Error', err.message, 'error');
  5649. }
  5650. }
  5651. async function deletePolicyRule(id) {
  5652. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5653. try {
  5654. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5655. if (res.ok) {
  5656. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5657. loadRoutes();
  5658. }
  5659. } catch (err) {
  5660. showToast('Error', err.message, 'error');
  5661. }
  5662. }
  5663. // ----------------- Routing Tables -----------------
  5664. function renderRoutingTables() {
  5665. const tbody = document.getElementById('tables-table-body');
  5666. if (!tbody) return;
  5667. tbody.innerHTML = '';
  5668. (state.routingTables || []).forEach(t => {
  5669. const tr = document.createElement('tr');
  5670. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5671. tr.innerHTML = `
  5672. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5673. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5674. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5675. `;
  5676. tbody.appendChild(tr);
  5677. });
  5678. }
  5679. function openAddTableModal() {
  5680. document.getElementById('table-modal-name').value = '';
  5681. document.getElementById('table-modal-id').value = '';
  5682. document.getElementById('table-modal-comment').value = '';
  5683. document.getElementById('table-modal').classList.remove('hidden');
  5684. }
  5685. function closeTableModal() {
  5686. document.getElementById('table-modal').classList.add('hidden');
  5687. }
  5688. async function submitSaveTable(e) {
  5689. e.preventDefault();
  5690. const name = document.getElementById('table-modal-name').value.trim();
  5691. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5692. const comment = document.getElementById('table-modal-comment').value.trim();
  5693. try {
  5694. const res = await fetch(`${API_BASE}/routing/tables`, {
  5695. method: 'POST',
  5696. headers: { 'Content-Type': 'application/json' },
  5697. body: JSON.stringify({ name, table_id: id, comment })
  5698. });
  5699. if (res.ok) {
  5700. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5701. closeTableModal();
  5702. loadRoutes();
  5703. } else {
  5704. const err = await res.json();
  5705. showToast('Error', err.message, 'error');
  5706. }
  5707. } catch (err) {
  5708. showToast('Error', err.message, 'error');
  5709. }
  5710. }
  5711. async function loadDebianConfig() {
  5712. const view = document.getElementById('debian-config-view');
  5713. view.innerText = 'Generating live configuration...';
  5714. try {
  5715. const res = await fetch(`${API_BASE}/debian/config`);
  5716. const data = await res.json();
  5717. view.innerText = data.content || '# Empty config';
  5718. } catch (err) {
  5719. view.innerText = 'Failed to generate Debian network config.';
  5720. }
  5721. }
  5722. async function saveDebianConfig() {
  5723. try {
  5724. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5725. const data = await res.json();
  5726. if (res.ok) {
  5727. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5728. loadDebianConfig();
  5729. }
  5730. } catch (err) {
  5731. showToast('Error', err.message, 'error');
  5732. }
  5733. }
  5734. function showToast(title, message, type = 'info') {
  5735. const container = document.getElementById('toast-container');
  5736. const toast = document.createElement('div');
  5737. const borderColors = {
  5738. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5739. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5740. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5741. };
  5742. 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}`;
  5743. toast.innerHTML = `
  5744. <div class="flex-1">
  5745. <div class="font-bold text-xs text-white">${title}</div>
  5746. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5747. </div>
  5748. `;
  5749. container.appendChild(toast);
  5750. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5751. setTimeout(() => {
  5752. toast.classList.add('opacity-0', 'translate-y-2');
  5753. setTimeout(() => toast.remove(), 300);
  5754. }, 4000);
  5755. }
  5756. function formatTraffic(bytesPerSec) {
  5757. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5758. const kb = bytesPerSec / 1024;
  5759. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5760. const mb = kb / 1024;
  5761. return `${mb.toFixed(2)} MB/s`;
  5762. }
  5763. function toggleSidebar() {
  5764. const sb = document.getElementById('sidebar');
  5765. sb.classList.toggle('-translate-x-full');
  5766. }
  5767. // ======================== EoIP (Ethernet over IP) ========================
  5768. async function loadEoIP(populate = true) {
  5769. try {
  5770. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5771. const data = await res.json();
  5772. state.eoipTunnels = Array.isArray(data) ? data : [];
  5773. const badge = document.getElementById('eoip-count-badge');
  5774. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5775. const sideBadge = document.getElementById('badge-eoip-count');
  5776. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5777. renderEoIPTunnels();
  5778. } catch (err) {
  5779. console.error('Failed to load EoIP:', err);
  5780. }
  5781. }
  5782. function renderEoIPTunnels() {
  5783. const tbody = document.getElementById('eoip-table-body');
  5784. const empty = document.getElementById('eoip-empty');
  5785. if (!tbody) return;
  5786. tbody.innerHTML = '';
  5787. const tunnels = state.eoipTunnels || [];
  5788. if (tunnels.length === 0) {
  5789. empty?.classList.remove('hidden');
  5790. return;
  5791. }
  5792. empty?.classList.add('hidden');
  5793. tunnels.forEach(t => {
  5794. const tr = document.createElement('tr');
  5795. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5796. tr.innerHTML = `
  5797. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5798. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5799. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5800. <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>
  5801. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5802. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5803. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5804. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5805. <td class="py-2.5 px-3 font-mono text-[11px]">
  5806. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5807. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5808. </td>
  5809. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5810. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5811. <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>
  5812. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5813. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5814. </td>
  5815. `;
  5816. tbody.appendChild(tr);
  5817. });
  5818. }
  5819. function openAddEoIPModal() {
  5820. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5821. document.getElementById('eoip-modal-id').value = '';
  5822. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5823. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5824. document.getElementById('eoip-modal-remote').value = '';
  5825. document.getElementById('eoip-modal-ip').value = '';
  5826. document.getElementById('eoip-modal-local').value = '';
  5827. document.getElementById('eoip-modal-mac').value = '';
  5828. document.getElementById('eoip-modal-mtu').value = '1500';
  5829. document.getElementById('eoip-modal-comment').value = '';
  5830. document.getElementById('eoip-modal-clampmss').checked = true;
  5831. document.getElementById('eoip-modal-disabled').checked = false;
  5832. document.getElementById('eoip-modal').classList.remove('hidden');
  5833. }
  5834. function openEditEoIPModal(id) {
  5835. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5836. if (!t) return;
  5837. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5838. document.getElementById('eoip-modal-id').value = t.id;
  5839. document.getElementById('eoip-modal-name').value = t.name;
  5840. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5841. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5842. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5843. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5844. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5845. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5846. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5847. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5848. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5849. document.getElementById('eoip-modal').classList.remove('hidden');
  5850. }
  5851. function closeEoIPModal() {
  5852. document.getElementById('eoip-modal').classList.add('hidden');
  5853. }
  5854. async function submitSaveEoIP(e) {
  5855. e.preventDefault();
  5856. const id = document.getElementById('eoip-modal-id').value;
  5857. const name = document.getElementById('eoip-modal-name').value.trim();
  5858. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5859. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5860. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5861. const local = document.getElementById('eoip-modal-local').value.trim();
  5862. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5863. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5864. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5865. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5866. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5867. try {
  5868. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5869. method: 'POST',
  5870. headers: { 'Content-Type': 'application/json' },
  5871. body: JSON.stringify({
  5872. id,
  5873. name,
  5874. tunnel_id: tunnelId,
  5875. remote_address: remote,
  5876. ip_address: ipAddress,
  5877. local_address: local,
  5878. mac_address: mac,
  5879. mtu,
  5880. clamp_mss: clampMss,
  5881. comment,
  5882. disabled
  5883. })
  5884. });
  5885. if (res.ok) {
  5886. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5887. closeEoIPModal();
  5888. loadEoIP(false);
  5889. fetchData(false);
  5890. } else {
  5891. const err = await res.json();
  5892. showToast('Error', err.message, 'error');
  5893. }
  5894. } catch (err) {
  5895. showToast('Error', err.message, 'error');
  5896. }
  5897. }
  5898. async function toggleEoIPState(id, disabled) {
  5899. try {
  5900. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5901. method: 'POST',
  5902. headers: { 'Content-Type': 'application/json' },
  5903. body: JSON.stringify({ disabled })
  5904. });
  5905. if (res.ok) {
  5906. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5907. loadEoIP(false);
  5908. fetchData(false);
  5909. }
  5910. } catch (err) {
  5911. showToast('Error', err.message, 'error');
  5912. }
  5913. }
  5914. async function deleteEoIP(id) {
  5915. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5916. try {
  5917. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5918. if (res.ok) {
  5919. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5920. loadEoIP(false);
  5921. fetchData(false);
  5922. }
  5923. } catch (err) {
  5924. showToast('Error', err.message, 'error');
  5925. }
  5926. }
  5927. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  5928. async function loadAeroTUN(populate = true) {
  5929. try {
  5930. const [tunnelsRes, statsRes] = await Promise.all([
  5931. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  5932. fetch(`${API_BASE}/vpn/aerotun/stats`)
  5933. ]);
  5934. if (tunnelsRes.ok) {
  5935. const data = await tunnelsRes.json();
  5936. state.aerotunTunnels = Array.isArray(data) ? data : [];
  5937. }
  5938. if (statsRes.ok) {
  5939. state.aerotunStats = await statsRes.json();
  5940. }
  5941. const countBadge = document.getElementById('aerotun-count-badge');
  5942. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  5943. const sideBadge = document.getElementById('badge-aerotun-count');
  5944. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  5945. renderAeroTUN();
  5946. } catch (err) {
  5947. console.error('Failed to load AeroTUN:', err);
  5948. }
  5949. }
  5950. function renderAeroTUN() {
  5951. const tbody = document.getElementById('aerotun-table-body');
  5952. const empty = document.getElementById('aerotun-empty');
  5953. // Update summary cards
  5954. const stats = state.aerotunStats || {};
  5955. const tunnels = state.aerotunTunnels || [];
  5956. const statActive = document.getElementById('aerotun-stat-active');
  5957. if (statActive) {
  5958. const activeCount = tunnels.filter(t => t.running).length;
  5959. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  5960. }
  5961. const statSaved = document.getElementById('aerotun-stat-saved');
  5962. if (statSaved) {
  5963. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  5964. }
  5965. const statRatio = document.getElementById('aerotun-stat-ratio');
  5966. if (statRatio) {
  5967. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  5968. }
  5969. const statTraffic = document.getElementById('aerotun-stat-traffic');
  5970. if (statTraffic) {
  5971. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  5972. }
  5973. if (!tbody) return;
  5974. tbody.innerHTML = '';
  5975. if (tunnels.length === 0) {
  5976. empty?.classList.remove('hidden');
  5977. return;
  5978. }
  5979. empty?.classList.add('hidden');
  5980. tunnels.forEach(t => {
  5981. const tr = document.createElement('tr');
  5982. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5983. const modeBadge = t.mode === 'server'
  5984. ? `<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>`
  5985. : `<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>`;
  5986. const endpointInfo = t.mode === 'server'
  5987. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  5988. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  5989. const compBadge = t.compression
  5990. ? `<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>`
  5991. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  5992. const activePeer = t.active_peer_endpoint
  5993. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  5994. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  5995. const rawRx = formatBytes(t.rx_bytes || 0);
  5996. const rawTx = formatBytes(t.tx_bytes || 0);
  5997. const wireRx = formatBytes(t.wire_bytes_in || 0);
  5998. const wireTx = formatBytes(t.wire_bytes_out || 0);
  5999. tr.innerHTML = `
  6000. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6001. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6002. <span>${escapeHtml(t.name)}</span>
  6003. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6004. </td>
  6005. <td class="py-2.5 px-3">${modeBadge}</td>
  6006. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6007. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6008. <td class="py-2.5 px-3">${compBadge}</td>
  6009. <td class="py-2.5 px-3">${activePeer}</td>
  6010. <td class="py-2.5 px-3 font-mono text-[11px]">
  6011. <span class="text-emerald-400">↓ ${rawRx}</span>
  6012. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6013. </td>
  6014. <td class="py-2.5 px-3 font-mono text-[11px]">
  6015. <span class="text-slate-400">↓ ${wireRx}</span>
  6016. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6017. </td>
  6018. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6019. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6020. ${t.running
  6021. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6022. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6023. }
  6024. <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>
  6025. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6026. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6027. </td>
  6028. `;
  6029. tbody.appendChild(tr);
  6030. });
  6031. }
  6032. function onAeroTUNModeChange() {
  6033. const mode = document.getElementById('aerotun-modal-mode').value;
  6034. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6035. const portInput = document.getElementById('aerotun-modal-port');
  6036. if (mode === 'server') {
  6037. if (!portInput.value) portInput.value = '51830';
  6038. endpointInput.placeholder = 'Optional / learned roaming peer';
  6039. } else {
  6040. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6041. if (!portInput.value) portInput.value = '';
  6042. }
  6043. }
  6044. async function generateAeroTUNKey() {
  6045. try {
  6046. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6047. if (res.ok) {
  6048. const data = await res.json();
  6049. document.getElementById('aerotun-modal-psk').value = data.key;
  6050. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6051. }
  6052. } catch (err) {
  6053. const arr = new Uint8Array(32);
  6054. crypto.getRandomValues(arr);
  6055. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6056. document.getElementById('aerotun-modal-psk').value = hex;
  6057. }
  6058. }
  6059. function openAddAeroTUNModal() {
  6060. const tunnels = state.aerotunTunnels || [];
  6061. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6062. document.getElementById('aerotun-modal-id').value = '';
  6063. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6064. document.getElementById('aerotun-modal-mode').value = 'server';
  6065. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6066. document.getElementById('aerotun-modal-endpoint').value = '';
  6067. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6068. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6069. document.getElementById('aerotun-modal-psk').value = '';
  6070. document.getElementById('aerotun-modal-mtu').value = '1420';
  6071. document.getElementById('aerotun-modal-comment').value = '';
  6072. document.getElementById('aerotun-modal-compression').checked = true;
  6073. document.getElementById('aerotun-modal-defroute').checked = false;
  6074. document.getElementById('aerotun-modal-disabled').checked = false;
  6075. generateAeroTUNKey();
  6076. onAeroTUNModeChange();
  6077. document.getElementById('aerotun-modal').classList.remove('hidden');
  6078. }
  6079. function openEditAeroTUNModal(id) {
  6080. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6081. if (!t) return;
  6082. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6083. document.getElementById('aerotun-modal-id').value = t.id;
  6084. document.getElementById('aerotun-modal-name').value = t.name;
  6085. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6086. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6087. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6088. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6089. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6090. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6091. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6092. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6093. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6094. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6095. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6096. onAeroTUNModeChange();
  6097. document.getElementById('aerotun-modal').classList.remove('hidden');
  6098. }
  6099. function closeAeroTUNModal() {
  6100. document.getElementById('aerotun-modal').classList.add('hidden');
  6101. }
  6102. async function submitSaveAeroTUN(e) {
  6103. e.preventDefault();
  6104. const id = document.getElementById('aerotun-modal-id').value;
  6105. const name = document.getElementById('aerotun-modal-name').value.trim();
  6106. const mode = document.getElementById('aerotun-modal-mode').value;
  6107. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6108. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6109. const local = document.getElementById('aerotun-modal-local').value.trim();
  6110. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6111. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6112. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6113. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6114. const compression = document.getElementById('aerotun-modal-compression').checked;
  6115. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6116. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6117. if (mode === 'client' && !endpoint) {
  6118. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6119. return;
  6120. }
  6121. if (!psk) {
  6122. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6123. return;
  6124. }
  6125. try {
  6126. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6127. method: 'POST',
  6128. headers: { 'Content-Type': 'application/json' },
  6129. body: JSON.stringify({
  6130. id,
  6131. name,
  6132. mode,
  6133. listen_port: port,
  6134. remote_endpoint: endpoint,
  6135. local_address: local,
  6136. peer_address: peer,
  6137. psk,
  6138. mtu,
  6139. compression,
  6140. default_route: defaultRoute,
  6141. comment,
  6142. disabled
  6143. })
  6144. });
  6145. if (res.ok) {
  6146. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6147. closeAeroTUNModal();
  6148. loadAeroTUN(false);
  6149. fetchData(false);
  6150. } else {
  6151. const err = await res.text();
  6152. showToast('Error Saving Tunnel', err, 'error');
  6153. }
  6154. } catch (err) {
  6155. showToast('Network Error', err.message, 'error');
  6156. }
  6157. }
  6158. async function startAeroTUNTunnel(id) {
  6159. try {
  6160. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6161. if (res.ok) {
  6162. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6163. loadAeroTUN(false);
  6164. fetchData(false);
  6165. } else {
  6166. const err = await res.text();
  6167. showToast('Failed to Start', err, 'error');
  6168. }
  6169. } catch (err) {
  6170. showToast('Error', err.message, 'error');
  6171. }
  6172. }
  6173. async function stopAeroTUNTunnel(id) {
  6174. try {
  6175. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6176. if (res.ok) {
  6177. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6178. loadAeroTUN(false);
  6179. fetchData(false);
  6180. } else {
  6181. const err = await res.text();
  6182. showToast('Failed to Stop', err, 'error');
  6183. }
  6184. } catch (err) {
  6185. showToast('Error', err.message, 'error');
  6186. }
  6187. }
  6188. async function toggleAeroTUNState(id, disabled) {
  6189. try {
  6190. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6191. method: 'POST',
  6192. headers: { 'Content-Type': 'application/json' },
  6193. body: JSON.stringify({ disabled })
  6194. });
  6195. if (res.ok) {
  6196. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6197. loadAeroTUN(false);
  6198. fetchData(false);
  6199. }
  6200. } catch (err) {
  6201. showToast('Error', err.message, 'error');
  6202. }
  6203. }
  6204. async function deleteAeroTUN(id) {
  6205. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6206. try {
  6207. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6208. if (res.ok) {
  6209. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6210. loadAeroTUN(false);
  6211. fetchData(false);
  6212. }
  6213. } catch (err) {
  6214. showToast('Error', err.message, 'error');
  6215. }
  6216. }
  6217. // ======================== PPP Central Hub & Servers ========================
  6218. function switchPPPSubTab(tab) {
  6219. state.pppSubTab = tab;
  6220. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6221. tabs.forEach(t => {
  6222. const panel = document.getElementById(`ppp-subtab-${t}`);
  6223. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6224. if (panel) {
  6225. if (t === tab) panel.classList.remove('hidden');
  6226. else panel.classList.add('hidden');
  6227. }
  6228. if (btn) {
  6229. if (t === tab) {
  6230. 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';
  6231. } else {
  6232. 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';
  6233. }
  6234. }
  6235. });
  6236. const addBtn = document.getElementById('ppp-primary-add-btn');
  6237. if (addBtn) {
  6238. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6239. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6240. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6241. else addBtn.innerHTML = '<span>Save Config</span>';
  6242. }
  6243. if (tab === 'active') loadPPPSessions();
  6244. }
  6245. function openCurrentPPPModal() {
  6246. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6247. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6248. else if (state.pppSubTab === 'active') loadPPPSessions();
  6249. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6250. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6251. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6252. }
  6253. async function loadPPP(populateDropdowns = true) {
  6254. await Promise.all([
  6255. loadPPPSecrets(),
  6256. loadPPPProfiles(),
  6257. loadPPPServers(),
  6258. loadPPPSessions()
  6259. ]);
  6260. }
  6261. async function loadPPPSecrets() {
  6262. try {
  6263. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6264. const data = await res.json();
  6265. state.pppSecrets = Array.isArray(data) ? data : [];
  6266. const b = document.getElementById('ppp-badge-secrets');
  6267. if (b) b.innerText = state.pppSecrets.length;
  6268. const b2 = document.getElementById('secrets-count-badge');
  6269. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6270. renderPPPSecrets();
  6271. } catch (err) {
  6272. console.error('Failed to load PPP secrets:', err);
  6273. }
  6274. }
  6275. function renderPPPSecrets() {
  6276. const tbody = document.getElementById('secrets-table-body');
  6277. const empty = document.getElementById('secrets-empty');
  6278. if (!tbody) return;
  6279. tbody.innerHTML = '';
  6280. const secrets = state.pppSecrets || [];
  6281. if (secrets.length === 0) {
  6282. empty?.classList.remove('hidden');
  6283. return;
  6284. }
  6285. empty?.classList.add('hidden');
  6286. secrets.forEach(s => {
  6287. const tr = document.createElement('tr');
  6288. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6289. tr.innerHTML = `
  6290. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6291. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6292. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6293. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6294. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6295. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6296. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6297. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6298. <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>
  6299. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6300. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6301. </td>
  6302. `;
  6303. tbody.appendChild(tr);
  6304. });
  6305. }
  6306. async function loadPPPProfiles() {
  6307. try {
  6308. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6309. const data = await res.json();
  6310. state.pppProfiles = Array.isArray(data) ? data : [];
  6311. const b = document.getElementById('ppp-badge-profiles');
  6312. if (b) b.innerText = state.pppProfiles.length;
  6313. const b2 = document.getElementById('profiles-count-badge');
  6314. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6315. // Populate profile selects across modals
  6316. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6317. selects.forEach(sid => {
  6318. const el = document.getElementById(sid);
  6319. if (!el) return;
  6320. const cur = el.value;
  6321. el.innerHTML = '';
  6322. state.pppProfiles.forEach(p => {
  6323. const opt = document.createElement('option');
  6324. opt.value = p.name;
  6325. opt.innerText = `${p.name} (${p.remote_address})`;
  6326. if (p.name === cur) opt.selected = true;
  6327. el.appendChild(opt);
  6328. });
  6329. });
  6330. renderPPPProfiles();
  6331. } catch (err) {
  6332. console.error('Failed to load PPP profiles:', err);
  6333. }
  6334. }
  6335. function renderPPPProfiles() {
  6336. const tbody = document.getElementById('profiles-table-body');
  6337. if (!tbody) return;
  6338. tbody.innerHTML = '';
  6339. (state.pppProfiles || []).forEach(p => {
  6340. const isDefault = p.name.startsWith('default');
  6341. const tr = document.createElement('tr');
  6342. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6343. tr.innerHTML = `
  6344. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6345. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6346. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6347. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6348. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6349. <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>
  6350. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6351. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6352. ${!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>`}
  6353. </td>
  6354. `;
  6355. tbody.appendChild(tr);
  6356. });
  6357. }
  6358. async function loadPPPServers() {
  6359. try {
  6360. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6361. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6362. fetch(`${API_BASE}/vpn/servers/pptp`),
  6363. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6364. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6365. ]);
  6366. if (pppoeRes.ok) {
  6367. state.pppoeServer = await pppoeRes.json();
  6368. const s = state.pppoeServer;
  6369. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6370. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6371. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6372. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6373. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6374. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6375. const pill = document.getElementById('pppoe-server-status-pill');
  6376. if (pill) {
  6377. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6378. 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';
  6379. }
  6380. setDotBadge('ppp-badge-pppoe-state', s.running);
  6381. }
  6382. if (pptpRes.ok) {
  6383. state.pptpServer = await pptpRes.json();
  6384. const s = state.pptpServer;
  6385. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6386. document.getElementById('pptp-server-port').value = s.port || 1723;
  6387. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6388. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6389. const pill = document.getElementById('pptp-server-status-pill');
  6390. if (pill) {
  6391. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6392. 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';
  6393. }
  6394. setDotBadge('ppp-badge-pptp-state', s.running);
  6395. }
  6396. if (l2tpRes.ok) {
  6397. state.l2tpServer = await l2tpRes.json();
  6398. const s = state.l2tpServer;
  6399. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6400. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6401. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6402. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6403. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6404. const pill = document.getElementById('l2tp-server-status-pill');
  6405. if (pill) {
  6406. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6407. 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';
  6408. }
  6409. setDotBadge('ppp-badge-l2tp-state', s.running);
  6410. }
  6411. if (ipsecRes.ok) {
  6412. state.ipsecServer = await ipsecRes.json();
  6413. const s = state.ipsecServer;
  6414. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6415. if (modalEn) modalEn.checked = !!s.enabled;
  6416. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6417. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6418. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6419. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6420. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6421. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6422. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6423. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6424. const pill = document.getElementById('modal-ipsec-server-status');
  6425. if (pill) {
  6426. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6427. 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';
  6428. }
  6429. }
  6430. } catch (err) {
  6431. console.error('Failed to load VPN servers:', err);
  6432. }
  6433. }
  6434. async function loadPPPSessions() {
  6435. try {
  6436. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6437. const data = await res.json();
  6438. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6439. const b = document.getElementById('ppp-badge-active');
  6440. if (b) b.innerText = state.pppActiveSessions.length;
  6441. const sideB = document.getElementById('badge-ppp-sessions');
  6442. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6443. renderPPPSessions();
  6444. } catch (err) {
  6445. console.error('Failed to load active PPP sessions:', err);
  6446. }
  6447. }
  6448. function renderPPPSessions() {
  6449. const tbody = document.getElementById('active-ppp-table-body');
  6450. const empty = document.getElementById('active-ppp-empty');
  6451. if (!tbody) return;
  6452. tbody.innerHTML = '';
  6453. const list = state.pppActiveSessions || [];
  6454. if (list.length === 0) {
  6455. empty?.classList.remove('hidden');
  6456. return;
  6457. }
  6458. empty?.classList.add('hidden');
  6459. list.forEach(s => {
  6460. const tr = document.createElement('tr');
  6461. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6462. tr.innerHTML = `
  6463. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6464. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6465. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6466. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6467. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6468. <td class="py-2.5 px-3 text-[11px]">
  6469. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6470. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6471. </td>
  6472. <td class="py-2.5 px-3 text-right font-sans">
  6473. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6474. </td>
  6475. `;
  6476. tbody.appendChild(tr);
  6477. });
  6478. }
  6479. async function disconnectPPPSession(iface) {
  6480. if (!confirm(`Disconnect session ${iface}?`)) return;
  6481. try {
  6482. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6483. if (res.ok) {
  6484. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6485. loadPPPSessions();
  6486. }
  6487. } catch (err) {
  6488. showToast('Error', err.message, 'error');
  6489. }
  6490. }
  6491. // PPP Secret Modal handlers
  6492. function openAddPPPSecretModal() {
  6493. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6494. document.getElementById('secret-modal-id').value = '';
  6495. document.getElementById('secret-modal-name').value = '';
  6496. document.getElementById('secret-modal-password').value = '';
  6497. document.getElementById('secret-modal-service').value = 'any';
  6498. document.getElementById('secret-modal-profile').value = 'default';
  6499. document.getElementById('secret-modal-local').value = '';
  6500. document.getElementById('secret-modal-remote').value = '';
  6501. document.getElementById('secret-modal-comment').value = '';
  6502. document.getElementById('secret-modal-disabled').checked = false;
  6503. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6504. }
  6505. function openEditPPPSecretModal(id) {
  6506. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6507. if (!s) return;
  6508. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6509. document.getElementById('secret-modal-id').value = s.id;
  6510. document.getElementById('secret-modal-name').value = s.name;
  6511. document.getElementById('secret-modal-password').value = s.password;
  6512. document.getElementById('secret-modal-service').value = s.service || 'any';
  6513. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6514. document.getElementById('secret-modal-local').value = s.local_address || '';
  6515. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6516. document.getElementById('secret-modal-comment').value = s.comment || '';
  6517. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6518. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6519. }
  6520. function closePPPSecretModal() {
  6521. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6522. }
  6523. async function submitSavePPPSecret(e) {
  6524. e.preventDefault();
  6525. const id = document.getElementById('secret-modal-id').value;
  6526. const name = document.getElementById('secret-modal-name').value.trim();
  6527. const password = document.getElementById('secret-modal-password').value.trim();
  6528. const service = document.getElementById('secret-modal-service').value;
  6529. const profile = document.getElementById('secret-modal-profile').value;
  6530. const local = document.getElementById('secret-modal-local').value.trim();
  6531. const remote = document.getElementById('secret-modal-remote').value.trim();
  6532. const comment = document.getElementById('secret-modal-comment').value.trim();
  6533. const disabled = document.getElementById('secret-modal-disabled').checked;
  6534. try {
  6535. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6536. method: 'POST',
  6537. headers: { 'Content-Type': 'application/json' },
  6538. body: JSON.stringify({
  6539. id,
  6540. name,
  6541. password,
  6542. service,
  6543. profile,
  6544. local_address: local,
  6545. remote_address: remote,
  6546. comment,
  6547. disabled
  6548. })
  6549. });
  6550. if (res.ok) {
  6551. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6552. closePPPSecretModal();
  6553. loadPPPSecrets();
  6554. } else {
  6555. const err = await res.json();
  6556. showToast('Error', err.message, 'error');
  6557. }
  6558. } catch (err) {
  6559. showToast('Error', err.message, 'error');
  6560. }
  6561. }
  6562. async function togglePPPSecretState(id, disabled) {
  6563. try {
  6564. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6565. method: 'POST',
  6566. headers: { 'Content-Type': 'application/json' },
  6567. body: JSON.stringify({ disabled })
  6568. });
  6569. if (res.ok) {
  6570. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6571. loadPPPSecrets();
  6572. }
  6573. } catch (err) {
  6574. showToast('Error', err.message, 'error');
  6575. }
  6576. }
  6577. async function deletePPPSecret(id) {
  6578. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6579. try {
  6580. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6581. if (res.ok) {
  6582. showToast('Deleted', 'Secret account removed', 'success');
  6583. loadPPPSecrets();
  6584. }
  6585. } catch (err) {
  6586. showToast('Error', err.message, 'error');
  6587. }
  6588. }
  6589. // PPP Profile Modal handlers
  6590. function openAddPPPProfileModal() {
  6591. document.getElementById('profile-modal-name').value = '';
  6592. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6593. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6594. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6595. document.getElementById('profile-modal-encryption').value = 'required';
  6596. document.getElementById('profile-modal-onlyone').checked = true;
  6597. document.getElementById('profile-modal-comment').value = '';
  6598. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6599. }
  6600. function closePPPProfileModal() {
  6601. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6602. }
  6603. async function submitSavePPPProfile(e) {
  6604. e.preventDefault();
  6605. const name = document.getElementById('profile-modal-name').value.trim();
  6606. const local = document.getElementById('profile-modal-local').value.trim();
  6607. const remote = document.getElementById('profile-modal-remote').value.trim();
  6608. const dns = document.getElementById('profile-modal-dns').value.trim();
  6609. const enc = document.getElementById('profile-modal-encryption').value;
  6610. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6611. const comment = document.getElementById('profile-modal-comment').value.trim();
  6612. try {
  6613. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6614. method: 'POST',
  6615. headers: { 'Content-Type': 'application/json' },
  6616. body: JSON.stringify({
  6617. id: name,
  6618. name,
  6619. local_address: local,
  6620. remote_address: remote,
  6621. dns_servers: dns,
  6622. use_encryption: enc,
  6623. only_one: onlyone,
  6624. comment
  6625. })
  6626. });
  6627. if (res.ok) {
  6628. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6629. closePPPProfileModal();
  6630. loadPPPProfiles();
  6631. } else {
  6632. const err = await res.json();
  6633. showToast('Error', err.message, 'error');
  6634. }
  6635. } catch (err) {
  6636. showToast('Error', err.message, 'error');
  6637. }
  6638. }
  6639. async function deletePPPProfile(name) {
  6640. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6641. try {
  6642. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6643. if (res.ok) {
  6644. showToast('Deleted', 'Profile removed', 'success');
  6645. loadPPPProfiles();
  6646. } else {
  6647. const err = await res.json();
  6648. showToast('Error', err.message, 'error');
  6649. }
  6650. } catch (err) {
  6651. showToast('Error', err.message, 'error');
  6652. }
  6653. }
  6654. // Server Config submissions
  6655. async function savePPPoEServerConfig(e) {
  6656. e.preventDefault();
  6657. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6658. const name = document.getElementById('pppoe-server-name').value.trim();
  6659. const iface = document.getElementById('pppoe-server-iface').value;
  6660. const profile = document.getElementById('pppoe-server-profile').value;
  6661. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6662. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6663. try {
  6664. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6665. method: 'POST',
  6666. headers: { 'Content-Type': 'application/json' },
  6667. body: JSON.stringify({
  6668. enabled,
  6669. service_name: name,
  6670. interface: iface,
  6671. default_profile: profile,
  6672. max_mtu: mtu,
  6673. max_mru: mtu,
  6674. one_session_per_host: onesession
  6675. })
  6676. });
  6677. if (res.ok) {
  6678. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6679. loadPPPServers();
  6680. fetchData(false);
  6681. } else {
  6682. const err = await res.json();
  6683. showToast('Error', err.message, 'error');
  6684. }
  6685. } catch (err) {
  6686. showToast('Error', err.message, 'error');
  6687. }
  6688. }
  6689. async function savePPTPServerConfig(e) {
  6690. e.preventDefault();
  6691. const enabled = document.getElementById('pptp-server-enabled').checked;
  6692. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6693. const profile = document.getElementById('pptp-server-profile').value;
  6694. const mppe = document.getElementById('pptp-server-mppe').checked;
  6695. try {
  6696. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6697. method: 'POST',
  6698. headers: { 'Content-Type': 'application/json' },
  6699. body: JSON.stringify({
  6700. enabled,
  6701. port,
  6702. default_profile: profile,
  6703. require_mppe: mppe
  6704. })
  6705. });
  6706. if (res.ok) {
  6707. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6708. loadPPPServers();
  6709. fetchData(false);
  6710. } else {
  6711. const err = await res.json();
  6712. showToast('Error', err.message, 'error');
  6713. }
  6714. } catch (err) {
  6715. showToast('Error', err.message, 'error');
  6716. }
  6717. }
  6718. async function saveL2TPServerConfig(e) {
  6719. e.preventDefault();
  6720. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6721. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6722. const profile = document.getElementById('l2tp-server-profile').value;
  6723. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6724. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6725. try {
  6726. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6727. method: 'POST',
  6728. headers: { 'Content-Type': 'application/json' },
  6729. body: JSON.stringify({
  6730. enabled,
  6731. port,
  6732. default_profile: profile,
  6733. use_ipsec: useipsec,
  6734. ipsec_secret: psk
  6735. })
  6736. });
  6737. if (res.ok) {
  6738. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6739. loadPPPServers();
  6740. fetchData(false);
  6741. } else {
  6742. const err = await res.json();
  6743. showToast('Error', err.message, 'error');
  6744. }
  6745. } catch (err) {
  6746. showToast('Error', err.message, 'error');
  6747. }
  6748. }
  6749. // IPSec Server Modal
  6750. function openIPSecServerModal() {
  6751. loadPPPServers();
  6752. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6753. }
  6754. function closeIPSecServerModal() {
  6755. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6756. }
  6757. async function submitSaveIPSecServer(e) {
  6758. e.preventDefault();
  6759. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6760. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6761. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6762. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6763. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6764. try {
  6765. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6766. method: 'POST',
  6767. headers: { 'Content-Type': 'application/json' },
  6768. body: JSON.stringify({
  6769. enabled,
  6770. preshared_key: psk,
  6771. pool_address: pool,
  6772. dns_servers: dns,
  6773. local_subnet: subnet
  6774. })
  6775. });
  6776. if (res.ok) {
  6777. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6778. closeIPSecServerModal();
  6779. loadPPPServers();
  6780. fetchData(false);
  6781. } else {
  6782. const err = await res.json();
  6783. showToast('Error', err.message, 'error');
  6784. }
  6785. } catch (err) {
  6786. showToast('Error', err.message, 'error');
  6787. }
  6788. }
  6789. // WireGuard Client Config Viewer
  6790. let currentWGClientConf = '';
  6791. async function openWGClientConfModal(iface, clientIP) {
  6792. try {
  6793. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6794. method: 'POST',
  6795. headers: { 'Content-Type': 'application/json' },
  6796. body: JSON.stringify({
  6797. interface: iface,
  6798. address: clientIP || '10.10.0.2/32',
  6799. dns: '1.1.1.1, 8.8.8.8'
  6800. })
  6801. });
  6802. if (res.ok) {
  6803. const data = await res.json();
  6804. currentWGClientConf = data.config;
  6805. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6806. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6807. } else {
  6808. const err = await res.json();
  6809. showToast('Error', err.message, 'error');
  6810. }
  6811. } catch (err) {
  6812. showToast('Error', err.message, 'error');
  6813. }
  6814. }
  6815. function closeWGClientConfModal() {
  6816. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6817. }
  6818. function copyWGClientConf() {
  6819. if (!currentWGClientConf) return;
  6820. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6821. }
  6822. function downloadWGClientConf() {
  6823. if (!currentWGClientConf) return;
  6824. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6825. const a = document.createElement('a');
  6826. a.href = URL.createObjectURL(blob);
  6827. a.download = 'wireguard-client.conf';
  6828. document.body.appendChild(a);
  6829. a.click();
  6830. document.body.removeChild(a);
  6831. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6832. }
  6833. // =========================================================================
  6834. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6835. // =========================================================================
  6836. state.activeDynSubTab = 'bgp-peers';
  6837. state.activeBgpSubTab = 'bgp-peers';
  6838. state.activeOspfTab = 'instances';
  6839. state.bgpInstance = null;
  6840. state.bgpPeers = [];
  6841. state.bgpNets = [];
  6842. state.bgpRoutes = [];
  6843. state.ospfInstance = null;
  6844. state.ospfInstances = [];
  6845. state.ospfAreas = [];
  6846. state.ospfAreaRanges = [];
  6847. state.ospfTemplates = [];
  6848. state.ospfLiveInterfaces = [];
  6849. state.ospfStaticNbrs = [];
  6850. state.ospfNeighbors = [];
  6851. state.ospfLSA = [];
  6852. state.ospfRoutes = [];
  6853. state.selectedOspfRow = {
  6854. instances: null,
  6855. areas: null,
  6856. 'area-ranges': null,
  6857. templates: null,
  6858. interfaces: null,
  6859. 'static-nbrs': null,
  6860. neighbors: null,
  6861. lsa: null,
  6862. };
  6863. state.ospfSort = {
  6864. instances: { col: 'name', asc: true },
  6865. areas: { col: 'name', asc: true },
  6866. ranges: { col: 'area', asc: true },
  6867. templates: { col: 'interfaces', asc: true },
  6868. live_ifaces: { col: 'interface', asc: true },
  6869. snbrs: { col: 'address', asc: true },
  6870. neighbors: { col: 'address', asc: true },
  6871. lsa: { col: 'instance', asc: true },
  6872. };
  6873. function switchBgpSubTab(subTab) {
  6874. state.activeBgpSubTab = subTab;
  6875. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6876. tabs.forEach(t => {
  6877. const el = document.getElementById(`dyn-subtab-${t}`);
  6878. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6879. if (el) el.classList.toggle('hidden', t !== subTab);
  6880. if (btn) {
  6881. if (t === subTab) {
  6882. 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';
  6883. } else {
  6884. 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';
  6885. }
  6886. }
  6887. });
  6888. }
  6889. function switchOspfTab(tabName) {
  6890. state.activeOspfTab = tabName;
  6891. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6892. tabs.forEach(t => {
  6893. const pane = document.getElementById(`ospf-pane-${t}`);
  6894. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6895. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6896. if (btn) {
  6897. if (t === tabName) {
  6898. 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';
  6899. } else {
  6900. 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';
  6901. }
  6902. }
  6903. });
  6904. }
  6905. function switchOspfSubTab(tab) {
  6906. // Legacy alias
  6907. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6908. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6909. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6910. else switchOspfTab('instances');
  6911. }
  6912. function switchDynSubTab(subTab) {
  6913. if (subTab.startsWith('bgp')) {
  6914. if (state.activeTab !== 'bgp') navigate('bgp');
  6915. switchBgpSubTab(subTab);
  6916. } else if (subTab.startsWith('ospf')) {
  6917. if (state.activeTab !== 'ospf') navigate('ospf');
  6918. switchOspfTab('instances');
  6919. }
  6920. }
  6921. async function loadDynamicRouting(showToastMsg = false) {
  6922. try {
  6923. const fetchSafeJson = async (url) => {
  6924. try {
  6925. const r = await fetch(url);
  6926. return r.ok ? await r.json() : null;
  6927. } catch (e) {
  6928. return null;
  6929. }
  6930. };
  6931. const [
  6932. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6933. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6934. selectRules, commLists, asLists
  6935. ] = await Promise.all([
  6936. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6937. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6938. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6939. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6940. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6941. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6942. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6943. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6944. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6945. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6946. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6947. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6948. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6949. fetchSafeJson(`${API_BASE}/routing/filters`),
  6950. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6951. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6952. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6953. ]);
  6954. if (sum) state.dynSummary = sum;
  6955. if (bgpInst) state.bgpInstance = bgpInst;
  6956. if (bgpPeers) state.bgpPeers = bgpPeers;
  6957. if (bgpNets) state.bgpNets = bgpNets;
  6958. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6959. if (ospfInsts) state.ospfInstances = ospfInsts;
  6960. if (ospfAreas) state.ospfAreas = ospfAreas;
  6961. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6962. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6963. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6964. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6965. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6966. if (ospfLsa) state.ospfLSA = ospfLsa;
  6967. if (filters) state.routingFilters = filters;
  6968. if (selectRules) state.routingSelectRules = selectRules;
  6969. if (commLists) state.routingCommunityLists = commLists;
  6970. if (asLists) state.routingASLists = asLists;
  6971. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6972. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6973. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6974. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6975. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6976. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6977. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6978. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6979. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6980. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6981. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6982. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6983. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6984. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6985. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6986. } catch (err) {
  6987. console.error('Failed to load dynamic routing:', err);
  6988. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6989. }
  6990. }
  6991. async function loadOspfAll() {
  6992. await loadDynamicRouting(true);
  6993. }
  6994. function renderBgpStatusPill() {
  6995. const pill = document.getElementById('bgp-live-status-pill');
  6996. if (!pill) return;
  6997. const inst = state.bgpInstance;
  6998. if (!inst || !inst.enabled) {
  6999. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7000. pill.innerText = 'BGP DISABLED';
  7001. } else if (inst.running) {
  7002. 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';
  7003. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7004. } else {
  7005. 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';
  7006. pill.innerText = 'BGP STARTING...';
  7007. }
  7008. }
  7009. function renderBgpPeers() {
  7010. const tbody = document.getElementById('bgp-peers-table-body');
  7011. if (!tbody) return;
  7012. const empty = document.getElementById('bgp-peers-empty');
  7013. const countBadge = document.getElementById('bgp-peers-count-badge');
  7014. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7015. const peers = state.bgpPeers || [];
  7016. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7017. if (navBadge) navBadge.innerText = peers.length;
  7018. if (peers.length === 0) {
  7019. tbody.innerHTML = '';
  7020. if (empty) empty.classList.remove('hidden');
  7021. return;
  7022. }
  7023. if (empty) empty.classList.add('hidden');
  7024. tbody.innerHTML = peers.map(p => {
  7025. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7026. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7027. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7028. let stateBadge = '';
  7029. if (p.disabled) {
  7030. 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>';
  7031. } else if (p.state === 'Established') {
  7032. 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>';
  7033. } else if (p.state === 'Connect' || p.state === 'Active') {
  7034. 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>`;
  7035. } else {
  7036. 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>`;
  7037. }
  7038. return `
  7039. <tr class="hover:bg-slate-800/40 transition">
  7040. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7041. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7042. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7043. <td class="py-2.5 px-3">
  7044. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7045. ${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>`}
  7046. </td>
  7047. <td class="py-2.5 px-3">${stateBadge}</td>
  7048. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7049. <td class="py-2.5 px-3 text-slate-300">
  7050. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7051. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7052. </td>
  7053. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7054. ${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> ` : ''}
  7055. ${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>` : ''}
  7056. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7057. </td>
  7058. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7059. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7060. <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'}">
  7061. ${p.disabled ? 'Enable' : 'Disable'}
  7062. </button>
  7063. <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">
  7064. Edit
  7065. </button>
  7066. <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">
  7067. Delete
  7068. </button>
  7069. </td>
  7070. </tr>
  7071. `;
  7072. }).join('');
  7073. }
  7074. function renderBgpNetworks() {
  7075. const tbody = document.getElementById('bgp-nets-table-body');
  7076. if (!tbody) return;
  7077. const empty = document.getElementById('bgp-nets-empty');
  7078. const countBadge = document.getElementById('bgp-nets-count-badge');
  7079. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7080. const nets = state.bgpNets || [];
  7081. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7082. if (navBadge) navBadge.innerText = nets.length;
  7083. if (nets.length === 0) {
  7084. tbody.innerHTML = '';
  7085. if (empty) empty.classList.remove('hidden');
  7086. return;
  7087. }
  7088. if (empty) empty.classList.add('hidden');
  7089. tbody.innerHTML = nets.map(n => `
  7090. <tr class="hover:bg-slate-800/40 transition">
  7091. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7092. <td class="py-2.5 px-3">
  7093. ${n.disabled
  7094. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7095. : '<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>'}
  7096. </td>
  7097. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7098. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7099. <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">
  7100. Delete
  7101. </button>
  7102. </td>
  7103. </tr>
  7104. `).join('');
  7105. }
  7106. function renderBgpRoutes() {
  7107. const tbody = document.getElementById('bgp-routes-table-body');
  7108. if (!tbody) return;
  7109. const empty = document.getElementById('bgp-routes-empty');
  7110. const countBadge = document.getElementById('bgp-routes-count-badge');
  7111. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7112. const routes = state.bgpRoutes || [];
  7113. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7114. if (navBadge) navBadge.innerText = routes.length;
  7115. if (routes.length === 0) {
  7116. tbody.innerHTML = '';
  7117. if (empty) empty.classList.remove('hidden');
  7118. return;
  7119. }
  7120. if (empty) empty.classList.add('hidden');
  7121. tbody.innerHTML = routes.map(r => `
  7122. <tr class="hover:bg-slate-800/40 transition">
  7123. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7124. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7125. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7126. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7127. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7128. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7129. </tr>
  7130. `).join('');
  7131. }
  7132. // =========================================================================
  7133. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7134. // =========================================================================
  7135. function sortOspfTable(tab, col) {
  7136. if (!state.ospfSort) state.ospfSort = {};
  7137. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7138. if (state.ospfSort[tab].col === col) {
  7139. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7140. } else {
  7141. state.ospfSort[tab].col = col;
  7142. state.ospfSort[tab].asc = true;
  7143. }
  7144. const asc = state.ospfSort[tab].asc;
  7145. let list = [];
  7146. if (tab === 'instances') list = state.ospfInstances || [];
  7147. else if (tab === 'areas') list = state.ospfAreas || [];
  7148. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7149. else if (tab === 'templates') list = state.ospfTemplates || [];
  7150. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7151. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7152. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7153. else if (tab === 'lsa') list = state.ospfLSA || [];
  7154. list.sort((a, b) => {
  7155. let valA = a[col] ?? '';
  7156. let valB = b[col] ?? '';
  7157. if (typeof valA === 'number' && typeof valB === 'number') {
  7158. return asc ? valA - valB : valB - valA;
  7159. }
  7160. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7161. });
  7162. if (tab === 'instances') renderOspfInstances();
  7163. else if (tab === 'areas') renderOspfAreas();
  7164. else if (tab === 'ranges') renderOspfAreaRanges();
  7165. else if (tab === 'templates') renderOspfTemplates();
  7166. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7167. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7168. else if (tab === 'neighbors') renderOspfNeighbors();
  7169. else if (tab === 'lsa') renderOspfLSA();
  7170. }
  7171. function selectOspfRow(tab, id) {
  7172. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7173. state.selectedOspfRow[tab] = id;
  7174. if (tab === 'instances') {
  7175. renderOspfInstances();
  7176. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7177. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7178. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7179. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7180. if (btnEn) btnEn.disabled = false;
  7181. if (btnDis) btnDis.disabled = false;
  7182. if (btnRem) btnRem.disabled = false;
  7183. if (btnCom) btnCom.disabled = false;
  7184. } else if (tab === 'areas') {
  7185. renderOspfAreas();
  7186. const btnEn = document.getElementById('btn-ospf-area-enable');
  7187. const btnDis = document.getElementById('btn-ospf-area-disable');
  7188. const btnRem = document.getElementById('btn-ospf-area-remove');
  7189. const btnCom = document.getElementById('btn-ospf-area-comment');
  7190. if (btnEn) btnEn.disabled = false;
  7191. if (btnDis) btnDis.disabled = false;
  7192. if (btnRem) btnRem.disabled = false;
  7193. if (btnCom) btnCom.disabled = false;
  7194. } else if (tab === 'ranges') {
  7195. renderOspfAreaRanges();
  7196. const btnEn = document.getElementById('btn-ospf-range-enable');
  7197. const btnDis = document.getElementById('btn-ospf-range-disable');
  7198. const btnRem = document.getElementById('btn-ospf-range-remove');
  7199. const btnCom = document.getElementById('btn-ospf-range-comment');
  7200. if (btnEn) btnEn.disabled = false;
  7201. if (btnDis) btnDis.disabled = false;
  7202. if (btnRem) btnRem.disabled = false;
  7203. if (btnCom) btnCom.disabled = false;
  7204. } else if (tab === 'templates') {
  7205. renderOspfTemplates();
  7206. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7207. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7208. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7209. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7210. if (btnEn) btnEn.disabled = false;
  7211. if (btnDis) btnDis.disabled = false;
  7212. if (btnRem) btnRem.disabled = false;
  7213. if (btnCom) btnCom.disabled = false;
  7214. } else if (tab === 'snbrs') {
  7215. renderOspfStaticNbrs();
  7216. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7217. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7218. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7219. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7220. if (btnEn) btnEn.disabled = false;
  7221. if (btnDis) btnDis.disabled = false;
  7222. if (btnRem) btnRem.disabled = false;
  7223. if (btnCom) btnCom.disabled = false;
  7224. }
  7225. }
  7226. // TAB 1: INSTANCES
  7227. function renderOspfInstances() {
  7228. const tbody = document.getElementById('ospf-instances-table-body');
  7229. if (!tbody) return;
  7230. const countEl = document.getElementById('ospf-instances-footer-count');
  7231. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7232. let list = state.ospfInstances || [];
  7233. if (filter) {
  7234. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7235. }
  7236. if (countEl) countEl.innerText = list.length;
  7237. const selId = state.selectedOspfRow?.instances;
  7238. tbody.innerHTML = list.map((inst, idx) => {
  7239. const isSel = inst.id === selId;
  7240. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7241. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7242. return `
  7243. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7244. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7245. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7246. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7247. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7248. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7249. </td>
  7250. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7251. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7252. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7253. </tr>
  7254. `;
  7255. }).join('');
  7256. }
  7257. // TAB 2: AREAS
  7258. function renderOspfAreas() {
  7259. const tbody = document.getElementById('ospf-areas-table-body');
  7260. if (!tbody) return;
  7261. const countEl = document.getElementById('ospf-areas-footer-count');
  7262. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7263. let list = state.ospfAreas || [];
  7264. if (filter) {
  7265. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7266. }
  7267. if (countEl) countEl.innerText = list.length;
  7268. const selId = state.selectedOspfRow?.areas;
  7269. tbody.innerHTML = list.map((a, idx) => {
  7270. const isSel = a.id === selId;
  7271. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7272. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7273. return `
  7274. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7275. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7276. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7277. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7278. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7279. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7280. </td>
  7281. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7282. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7283. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7284. </tr>
  7285. `;
  7286. }).join('');
  7287. }
  7288. // TAB 3: AREA RANGES
  7289. function renderOspfAreaRanges() {
  7290. const tbody = document.getElementById('ospf-ranges-table-body');
  7291. if (!tbody) return;
  7292. const countEl = document.getElementById('ospf-ranges-footer-count');
  7293. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7294. let list = state.ospfAreaRanges || [];
  7295. if (filter) {
  7296. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7297. }
  7298. if (countEl) countEl.innerText = list.length;
  7299. const selId = state.selectedOspfRow?.['area-ranges'];
  7300. tbody.innerHTML = list.map((r, idx) => {
  7301. const isSel = r.id === selId;
  7302. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7303. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7304. return `
  7305. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7306. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7307. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7308. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7309. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7310. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7311. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7312. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7313. </tr>
  7314. `;
  7315. }).join('');
  7316. }
  7317. // TAB 4: INTERFACE TEMPLATES
  7318. function renderOspfTemplates() {
  7319. const tbody = document.getElementById('ospf-templates-table-body');
  7320. if (!tbody) return;
  7321. const countEl = document.getElementById('ospf-templates-footer-count');
  7322. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7323. let list = state.ospfTemplates || [];
  7324. if (filter) {
  7325. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7326. }
  7327. if (countEl) countEl.innerText = list.length;
  7328. const selId = state.selectedOspfRow?.templates;
  7329. tbody.innerHTML = list.map((t, idx) => {
  7330. const isSel = t.id === selId;
  7331. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7332. const ifaces = t.interfaces || t.interface || 'all';
  7333. const nets = t.networks || t.network || '';
  7334. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7335. return `
  7336. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7337. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7338. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7339. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7340. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7341. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7342. </td>
  7343. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7344. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7345. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7346. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7347. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7348. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7349. </tr>
  7350. `;
  7351. }).join('');
  7352. }
  7353. // TAB 5: LIVE INTERFACES
  7354. function renderOspfLiveInterfaces() {
  7355. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7356. if (!tbody) return;
  7357. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7358. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7359. let list = state.ospfLiveInterfaces || [];
  7360. if (filter) {
  7361. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7362. }
  7363. if (countEl) countEl.innerText = list.length;
  7364. tbody.innerHTML = list.map(i => `
  7365. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7366. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7367. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7368. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7369. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7370. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7371. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7372. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7373. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7374. </tr>
  7375. `).join('');
  7376. }
  7377. // TAB 6: STATIC NEIGHBORS
  7378. function renderOspfStaticNbrs() {
  7379. const tbody = document.getElementById('ospf-snbrs-table-body');
  7380. if (!tbody) return;
  7381. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7382. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7383. let list = state.ospfStaticNbrs || [];
  7384. if (filter) {
  7385. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7386. }
  7387. if (countEl) countEl.innerText = list.length;
  7388. const selId = state.selectedOspfRow?.['static-nbrs'];
  7389. tbody.innerHTML = list.map((n, idx) => {
  7390. const isSel = n.id === selId;
  7391. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7392. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7393. return `
  7394. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7395. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7396. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7397. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7398. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7399. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7400. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7401. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7402. </tr>
  7403. `;
  7404. }).join('');
  7405. }
  7406. // TAB 7: LIVE NEIGHBORS
  7407. function renderOspfNeighbors() {
  7408. const tbody = document.getElementById('ospf-neighbors-table-body');
  7409. if (!tbody) return;
  7410. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7411. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7412. let list = state.ospfNeighbors || [];
  7413. if (filter) {
  7414. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7415. }
  7416. if (countEl) countEl.innerText = list.length;
  7417. tbody.innerHTML = list.map(n => `
  7418. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7419. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7420. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7421. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7422. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7423. </td>
  7424. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7425. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7426. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7427. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7428. </tr>
  7429. `).join('');
  7430. }
  7431. // TAB 8: LINK-STATE DATABASE (LSA)
  7432. function renderOspfLSA() {
  7433. const tbody = document.getElementById('ospf-lsa-table-body');
  7434. if (!tbody) return;
  7435. const countEl = document.getElementById('ospf-lsa-footer-count');
  7436. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7437. let list = state.ospfLSA || [];
  7438. if (filter) {
  7439. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7440. }
  7441. if (countEl) countEl.innerText = list.length;
  7442. tbody.innerHTML = list.map(l => `
  7443. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7444. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7445. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7446. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7447. </td>
  7448. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7449. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7450. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7451. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7452. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7453. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7454. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7455. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7456. </tr>
  7457. `).join('');
  7458. }
  7459. function renderOspfStatusPill() {
  7460. // Maintained for backward compatibility
  7461. const pill = document.getElementById('ospf-live-status-pill');
  7462. if (!pill) return;
  7463. 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';
  7464. pill.innerText = 'OSPF ACTIVE';
  7465. }
  7466. function renderOspfInterfaces() {
  7467. renderOspfTemplates();
  7468. }
  7469. function renderOspfRoutes() {
  7470. // Routes retained in background
  7471. }
  7472. // BGP Modals & Actions
  7473. function openBgpInstanceModal() {
  7474. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7475. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7476. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7477. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7478. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7479. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7480. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7481. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7482. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7483. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7484. }
  7485. function closeBgpInstanceModal() {
  7486. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7487. }
  7488. async function submitBgpInstance(e) {
  7489. e.preventDefault();
  7490. const payload = {
  7491. enabled: document.getElementById('modal-bgp-enabled').checked,
  7492. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7493. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7494. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7495. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7496. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7497. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7498. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7499. };
  7500. try {
  7501. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7502. method: 'POST',
  7503. headers: { 'Content-Type': 'application/json' },
  7504. body: JSON.stringify(payload)
  7505. });
  7506. if (res.ok) {
  7507. closeBgpInstanceModal();
  7508. showToast('Success', 'BGP instance configuration updated', 'success');
  7509. loadDynamicRouting();
  7510. } else {
  7511. const err = await res.json();
  7512. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7513. }
  7514. } catch (err) {
  7515. showToast('Error', err.message, 'error');
  7516. }
  7517. }
  7518. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7519. function switchBgpPeerModalTab(tab) {
  7520. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7521. tabs.forEach(t => {
  7522. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7523. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7524. if (t === tab) {
  7525. if (pane) pane.classList.remove('hidden');
  7526. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7527. } else {
  7528. if (pane) pane.classList.add('hidden');
  7529. 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';
  7530. }
  7531. });
  7532. }
  7533. function addOutputNetworkRow(val = '') {
  7534. const container = document.getElementById('modal-bgp-output-networks-container');
  7535. if (!container) return;
  7536. const row = document.createElement('div');
  7537. row.className = 'flex items-center gap-2 output-net-row';
  7538. row.innerHTML = `
  7539. <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">
  7540. <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>
  7541. `;
  7542. container.appendChild(row);
  7543. }
  7544. function parseBgpTime(val) {
  7545. if (!val) return 0;
  7546. val = String(val).trim();
  7547. if (val.includes(':')) {
  7548. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7549. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7550. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7551. }
  7552. return parseInt(val, 10) || 0;
  7553. }
  7554. function formatBgpTime(secs) {
  7555. if (!secs || secs <= 0) return '00:00:00';
  7556. const h = Math.floor(secs / 3600);
  7557. const m = Math.floor((secs % 3600) / 60);
  7558. const s = secs % 60;
  7559. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7560. }
  7561. function populateBgpRoutingTables() {
  7562. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7563. if (!sel) return;
  7564. const cur = sel.value || 'main';
  7565. sel.innerHTML = '<option value="main">main</option>';
  7566. (state.routingTables || []).forEach(t => {
  7567. if (t.name !== 'main') {
  7568. const opt = document.createElement('option');
  7569. opt.value = t.name;
  7570. opt.innerText = t.name;
  7571. sel.appendChild(opt);
  7572. }
  7573. });
  7574. sel.value = cur;
  7575. }
  7576. function openAddBgpPeerModal() {
  7577. document.getElementById('bgp-peer-form').reset();
  7578. document.getElementById('modal-bgp-peer-id').value = '';
  7579. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7580. // General Tab
  7581. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7582. document.getElementById('modal-bgp-peer-comment').value = '';
  7583. document.getElementById('modal-bgp-peer-name').value = '';
  7584. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7585. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7586. document.getElementById('modal-bgp-peer-local-as').value = '';
  7587. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7588. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7589. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7590. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7591. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7592. document.getElementById('modal-bgp-peer-router-id').value = '';
  7593. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7594. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7595. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7596. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7597. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7598. document.getElementById('modal-bgp-peer-local-port').value = '';
  7599. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7600. document.getElementById('modal-bgp-peer-password').value = '';
  7601. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7602. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7603. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7604. document.getElementById('modal-bgp-peer-connect').checked = true;
  7605. document.getElementById('modal-bgp-peer-listen').checked = true;
  7606. // Extra Tab
  7607. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7608. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7609. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7610. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7611. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7612. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7613. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7614. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7615. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7616. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7617. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7618. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7619. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7620. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7621. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7622. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7623. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7624. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7625. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7626. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7627. // Attributes Tab
  7628. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7629. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7630. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7631. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7632. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7633. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7634. // Filter Tab
  7635. populateFilterChainsDatalist();
  7636. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7637. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7638. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7639. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7640. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7641. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7642. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7643. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7644. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7645. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7646. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7647. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7648. populateBgpRoutingTables();
  7649. const container = document.getElementById('modal-bgp-output-networks-container');
  7650. if (container) {
  7651. container.innerHTML = '';
  7652. addOutputNetworkRow('');
  7653. }
  7654. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7655. if (removeBtn) removeBtn.classList.add('hidden');
  7656. switchBgpPeerModalTab('general');
  7657. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7658. }
  7659. function populateFilterChainsDatalist() {
  7660. const dl = document.getElementById('filter-chains-list');
  7661. if (!dl) return;
  7662. const chains = new Set();
  7663. (state.routingFilters || []).forEach(f => {
  7664. if (f.chain) chains.add(f.chain);
  7665. });
  7666. if (chains.size === 0) {
  7667. chains.add('awmn');
  7668. chains.add('bgp-in');
  7669. chains.add('bgp-out');
  7670. }
  7671. dl.innerHTML = '';
  7672. chains.forEach(c => {
  7673. const opt = document.createElement('option');
  7674. opt.value = c;
  7675. dl.appendChild(opt);
  7676. });
  7677. }
  7678. function openEditBgpPeerModal(id) {
  7679. const p = (state.bgpPeers || []).find(item => item.id === id);
  7680. if (!p) return;
  7681. populateBgpRoutingTables();
  7682. populateFilterChainsDatalist();
  7683. document.getElementById('modal-bgp-peer-id').value = p.id;
  7684. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7685. // General Tab
  7686. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7687. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7688. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7689. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7690. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7691. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7692. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7693. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7694. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7695. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7696. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7697. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7698. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7699. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7700. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7701. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7702. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7703. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7704. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7705. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7706. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7707. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7708. // Extra Tab
  7709. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7710. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7711. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7712. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7713. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7714. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7715. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7716. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7717. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7718. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7719. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7720. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7721. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7722. 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;
  7723. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7724. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7725. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7726. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7727. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7728. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7729. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7730. // Attributes Tab
  7731. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7732. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7733. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7734. 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;
  7735. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7736. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7737. // Filter Tab
  7738. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7739. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7740. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7741. 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 || '';
  7742. 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 || '';
  7743. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7744. 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 || '';
  7745. 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 || '';
  7746. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7747. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7748. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7749. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7750. // Output Networks
  7751. const container = document.getElementById('modal-bgp-output-networks-container');
  7752. if (container) {
  7753. container.innerHTML = '';
  7754. if (p.output_networks && p.output_networks.length > 0) {
  7755. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7756. } else {
  7757. addOutputNetworkRow('');
  7758. }
  7759. }
  7760. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7761. if (removeBtn) removeBtn.classList.remove('hidden');
  7762. switchBgpPeerModalTab('general');
  7763. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7764. }
  7765. function copyCurrentBgpPeer() {
  7766. document.getElementById('modal-bgp-peer-id').value = '';
  7767. const nameEl = document.getElementById('modal-bgp-peer-name');
  7768. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7769. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7770. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7771. if (removeBtn) removeBtn.classList.add('hidden');
  7772. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7773. }
  7774. function removeCurrentBgpPeer() {
  7775. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7776. if (!id) return;
  7777. deleteBgpPeer(id);
  7778. closeBgpPeerModal();
  7779. }
  7780. function closeBgpPeerModal() {
  7781. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7782. }
  7783. function getBgpPeerFormData() {
  7784. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7785. const outputNetworks = [];
  7786. netInputs.forEach(inp => {
  7787. const v = inp.value.trim();
  7788. if (v) outputNetworks.push(v);
  7789. });
  7790. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7791. return {
  7792. id: document.getElementById('modal-bgp-peer-id').value,
  7793. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7794. enabled: enabled,
  7795. disabled: !enabled,
  7796. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7797. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7798. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7799. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7800. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7801. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7802. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7803. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7804. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7805. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7806. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7807. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7808. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7809. password: document.getElementById('modal-bgp-peer-password').value,
  7810. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7811. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7812. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7813. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7814. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7815. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7816. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7817. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7818. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7819. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7820. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7821. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7822. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7823. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7824. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7825. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7826. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7827. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7828. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7829. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7830. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7831. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7832. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7833. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7834. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7835. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7836. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7837. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7838. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7839. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7840. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7841. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7842. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7843. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7844. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7845. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7846. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7847. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7848. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7849. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7850. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7851. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7852. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7853. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7854. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7855. output_networks: outputNetworks
  7856. };
  7857. }
  7858. async function submitBgpPeer(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. closeBgpPeerModal();
  7869. showToast('Success', 'BGP Connection saved', 'success');
  7870. loadDynamicRouting();
  7871. } else {
  7872. const err = await res.json();
  7873. showToast('Error', err.error || 'Failed to save peer', 'error');
  7874. }
  7875. } catch (err) {
  7876. showToast('Error', err.message, 'error');
  7877. }
  7878. }
  7879. async function applyBgpPeerModal(e) {
  7880. if (e) e.preventDefault();
  7881. const payload = getBgpPeerFormData();
  7882. try {
  7883. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7884. method: 'POST',
  7885. headers: { 'Content-Type': 'application/json' },
  7886. body: JSON.stringify(payload)
  7887. });
  7888. if (res.ok) {
  7889. const data = await res.json();
  7890. if (data.peer && data.peer.id) {
  7891. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7892. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7893. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7894. }
  7895. showToast('Applied', 'BGP Connection applied', 'success');
  7896. loadDynamicRouting();
  7897. } else {
  7898. const err = await res.json();
  7899. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7900. }
  7901. } catch (err) {
  7902. showToast('Error', err.message, 'error');
  7903. }
  7904. }
  7905. async function deleteBgpPeer(id) {
  7906. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7907. try {
  7908. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7909. if (res.ok) {
  7910. showToast('Deleted', 'BGP peer removed', 'success');
  7911. loadDynamicRouting();
  7912. }
  7913. } catch (err) {
  7914. showToast('Error', err.message, 'error');
  7915. }
  7916. }
  7917. async function toggleBgpPeerState(id, disabled) {
  7918. try {
  7919. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7920. method: 'POST',
  7921. headers: { 'Content-Type': 'application/json' },
  7922. body: JSON.stringify({ disabled })
  7923. });
  7924. if (res.ok) {
  7925. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7926. loadDynamicRouting();
  7927. }
  7928. } catch (err) {
  7929. showToast('Error', err.message, 'error');
  7930. }
  7931. }
  7932. function openAddBgpNetworkModal() {
  7933. document.getElementById('bgp-network-form').reset();
  7934. document.getElementById('modal-bgp-net-id').value = '';
  7935. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7936. }
  7937. function closeBgpNetworkModal() {
  7938. document.getElementById('bgp-network-modal').classList.add('hidden');
  7939. }
  7940. async function submitBgpNetwork(e) {
  7941. e.preventDefault();
  7942. const payload = {
  7943. id: document.getElementById('modal-bgp-net-id').value,
  7944. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7945. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7946. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7947. };
  7948. try {
  7949. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7950. method: 'POST',
  7951. headers: { 'Content-Type': 'application/json' },
  7952. body: JSON.stringify(payload)
  7953. });
  7954. if (res.ok) {
  7955. closeBgpNetworkModal();
  7956. showToast('Success', 'BGP network advertisement saved', 'success');
  7957. loadDynamicRouting();
  7958. } else {
  7959. const err = await res.json();
  7960. showToast('Error', err.error || 'Failed to save network', 'error');
  7961. }
  7962. } catch (err) {
  7963. showToast('Error', err.message, 'error');
  7964. }
  7965. }
  7966. async function deleteBgpNetwork(id) {
  7967. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7968. try {
  7969. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7970. if (res.ok) {
  7971. showToast('Deleted', 'Network advertisement removed', 'success');
  7972. loadDynamicRouting();
  7973. }
  7974. } catch (err) {
  7975. showToast('Error', err.message, 'error');
  7976. }
  7977. }
  7978. // =========================================================================
  7979. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7980. // =========================================================================
  7981. // --- 1. OSPF INSTANCE ---
  7982. function openOspfInstanceModal(id = null) {
  7983. const isEdit = !!id;
  7984. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7985. id: '',
  7986. name: 'Default',
  7987. version: 2,
  7988. vrf: 'main',
  7989. router_id: '192.168.131.56',
  7990. routing_table: 'main',
  7991. enabled: true,
  7992. redistribute_connected: false,
  7993. redistribute_static: true,
  7994. redistribute_bgp: false,
  7995. comment: ''
  7996. };
  7997. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7998. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7999. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8000. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8001. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8002. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8003. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8004. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8005. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8006. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8007. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8008. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8009. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8010. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8011. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8012. }
  8013. function openEditOspfInstanceModal(id) {
  8014. openOspfInstanceModal(id);
  8015. }
  8016. function closeOspfInstanceModal() {
  8017. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8018. }
  8019. async function submitOspfInstance(e) {
  8020. if (e) e.preventDefault();
  8021. const payload = {
  8022. id: document.getElementById('modal-ospf-inst-id').value,
  8023. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8024. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8025. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8026. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8027. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8028. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8029. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8030. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8031. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8032. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8033. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8034. };
  8035. try {
  8036. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8037. method: 'POST',
  8038. headers: { 'Content-Type': 'application/json' },
  8039. body: JSON.stringify(payload)
  8040. });
  8041. if (res.ok) {
  8042. closeOspfInstanceModal();
  8043. showToast('Saved', 'OSPF instance updated', 'success');
  8044. loadDynamicRouting();
  8045. } else {
  8046. const err = await res.json();
  8047. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8048. }
  8049. } catch (err) {
  8050. showToast('Error', err.message, 'error');
  8051. }
  8052. }
  8053. function applyOspfInstanceForm() {
  8054. submitOspfInstance(null);
  8055. }
  8056. function copyOspfInstance() {
  8057. document.getElementById('modal-ospf-inst-id').value = '';
  8058. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8059. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8060. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8061. }
  8062. async function deleteCurrentOspfInstance() {
  8063. const id = document.getElementById('modal-ospf-inst-id').value;
  8064. if (!id) return;
  8065. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8066. try {
  8067. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8068. if (res.ok) {
  8069. closeOspfInstanceModal();
  8070. showToast('Removed', 'OSPF instance deleted', 'success');
  8071. loadDynamicRouting();
  8072. }
  8073. } catch (err) {
  8074. showToast('Error', err.message, 'error');
  8075. }
  8076. }
  8077. async function enableSelectedOspfInstance() {
  8078. const id = state.selectedOspfRow?.instances;
  8079. if (!id) return;
  8080. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8081. method: 'POST',
  8082. headers: { 'Content-Type': 'application/json' },
  8083. body: JSON.stringify({ disabled: false })
  8084. });
  8085. loadDynamicRouting();
  8086. }
  8087. async function disableSelectedOspfInstance() {
  8088. const id = state.selectedOspfRow?.instances;
  8089. if (!id) return;
  8090. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8091. method: 'POST',
  8092. headers: { 'Content-Type': 'application/json' },
  8093. body: JSON.stringify({ disabled: true })
  8094. });
  8095. loadDynamicRouting();
  8096. }
  8097. async function removeSelectedOspfInstance() {
  8098. const id = state.selectedOspfRow?.instances;
  8099. if (!id) return;
  8100. if (!confirm('Delete selected OSPF instance?')) return;
  8101. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8102. loadDynamicRouting();
  8103. }
  8104. async function promptCommentOspfInstance() {
  8105. const id = state.selectedOspfRow?.instances;
  8106. if (!id) return;
  8107. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8108. if (!inst) return;
  8109. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8110. if (comment === null) return;
  8111. inst.comment = comment;
  8112. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8113. method: 'POST',
  8114. headers: { 'Content-Type': 'application/json' },
  8115. body: JSON.stringify(inst)
  8116. });
  8117. loadDynamicRouting();
  8118. }
  8119. // --- 2. OSPF AREA ---
  8120. function populateOspfAreaDropdowns() {
  8121. const instSelect = document.getElementById('modal-ospf-area-instance');
  8122. if (instSelect) {
  8123. const cur = instSelect.value;
  8124. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8125. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8126. if (cur) instSelect.value = cur;
  8127. }
  8128. }
  8129. function openOspfAreaModal(id = null) {
  8130. const isEdit = !!id;
  8131. populateOspfAreaDropdowns();
  8132. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8133. id: '',
  8134. name: 'Default',
  8135. instance: 'Default',
  8136. area_id: '0.0.0.0',
  8137. area_type: 'default',
  8138. default_cost: 1,
  8139. no_summaries: false,
  8140. disabled: false,
  8141. comment: ''
  8142. };
  8143. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8144. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8145. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8146. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8147. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8148. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8149. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8150. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8151. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8152. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8153. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8154. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8155. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8156. }
  8157. function openEditOspfAreaModal(id) {
  8158. openOspfAreaModal(id);
  8159. }
  8160. function closeOspfAreaModal() {
  8161. document.getElementById('ospf-area-modal').classList.add('hidden');
  8162. }
  8163. async function submitOspfArea(e) {
  8164. if (e) e.preventDefault();
  8165. const payload = {
  8166. id: document.getElementById('modal-ospf-area-id').value,
  8167. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8168. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8169. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8170. area_type: document.getElementById('modal-ospf-area-type').value,
  8171. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8172. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8173. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8174. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8175. };
  8176. try {
  8177. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8178. method: 'POST',
  8179. headers: { 'Content-Type': 'application/json' },
  8180. body: JSON.stringify(payload)
  8181. });
  8182. if (res.ok) {
  8183. closeOspfAreaModal();
  8184. showToast('Saved', 'OSPF area saved', 'success');
  8185. loadDynamicRouting();
  8186. } else {
  8187. const err = await res.json();
  8188. showToast('Error', err.error || 'Failed to save area', 'error');
  8189. }
  8190. } catch (err) {
  8191. showToast('Error', err.message, 'error');
  8192. }
  8193. }
  8194. function applyOspfAreaForm() {
  8195. submitOspfArea(null);
  8196. }
  8197. function copyOspfArea() {
  8198. document.getElementById('modal-ospf-area-id').value = '';
  8199. document.getElementById('modal-ospf-area-name').value += '-copy';
  8200. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8201. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8202. }
  8203. async function deleteCurrentOspfArea() {
  8204. const id = document.getElementById('modal-ospf-area-id').value;
  8205. if (!id) return;
  8206. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8207. try {
  8208. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8209. if (res.ok) {
  8210. closeOspfAreaModal();
  8211. showToast('Removed', 'OSPF area deleted', 'success');
  8212. loadDynamicRouting();
  8213. }
  8214. } catch (err) {
  8215. showToast('Error', err.message, 'error');
  8216. }
  8217. }
  8218. async function enableSelectedOspfArea() {
  8219. const id = state.selectedOspfRow?.areas;
  8220. if (!id) return;
  8221. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8222. method: 'POST',
  8223. headers: { 'Content-Type': 'application/json' },
  8224. body: JSON.stringify({ disabled: false })
  8225. });
  8226. loadDynamicRouting();
  8227. }
  8228. async function disableSelectedOspfArea() {
  8229. const id = state.selectedOspfRow?.areas;
  8230. if (!id) return;
  8231. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8232. method: 'POST',
  8233. headers: { 'Content-Type': 'application/json' },
  8234. body: JSON.stringify({ disabled: true })
  8235. });
  8236. loadDynamicRouting();
  8237. }
  8238. async function removeSelectedOspfArea() {
  8239. const id = state.selectedOspfRow?.areas;
  8240. if (!id) return;
  8241. if (!confirm('Delete selected OSPF area?')) return;
  8242. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8243. loadDynamicRouting();
  8244. }
  8245. async function promptCommentOspfArea() {
  8246. const id = state.selectedOspfRow?.areas;
  8247. if (!id) return;
  8248. const area = (state.ospfAreas || []).find(a => a.id === id);
  8249. if (!area) return;
  8250. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8251. if (comment === null) return;
  8252. area.comment = comment;
  8253. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8254. method: 'POST',
  8255. headers: { 'Content-Type': 'application/json' },
  8256. body: JSON.stringify(area)
  8257. });
  8258. loadDynamicRouting();
  8259. }
  8260. // --- 3. OSPF AREA RANGE ---
  8261. function populateAreaRangeDropdowns() {
  8262. const select = document.getElementById('modal-ospf-range-area');
  8263. if (select) {
  8264. const cur = select.value;
  8265. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8266. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8267. if (cur) select.value = cur;
  8268. }
  8269. }
  8270. function openOspfAreaRangeModal(id = null) {
  8271. const isEdit = !!id;
  8272. populateAreaRangeDropdowns();
  8273. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8274. id: '',
  8275. area: 'Default',
  8276. prefix: '',
  8277. cost: 1,
  8278. advertise: true,
  8279. disabled: false,
  8280. comment: ''
  8281. };
  8282. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8283. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8284. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8285. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8286. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8287. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8288. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8289. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8290. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8291. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8292. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8293. }
  8294. function openEditOspfAreaRangeModal(id) {
  8295. openOspfAreaRangeModal(id);
  8296. }
  8297. function closeOspfAreaRangeModal() {
  8298. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8299. }
  8300. async function submitOspfAreaRange(e) {
  8301. if (e) e.preventDefault();
  8302. const payload = {
  8303. id: document.getElementById('modal-ospf-range-id').value,
  8304. area: document.getElementById('modal-ospf-range-area').value,
  8305. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8306. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8307. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8308. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8309. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8310. };
  8311. try {
  8312. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8313. method: 'POST',
  8314. headers: { 'Content-Type': 'application/json' },
  8315. body: JSON.stringify(payload)
  8316. });
  8317. if (res.ok) {
  8318. closeOspfAreaRangeModal();
  8319. showToast('Saved', 'Area range saved', 'success');
  8320. loadDynamicRouting();
  8321. } else {
  8322. const err = await res.json();
  8323. showToast('Error', err.error || 'Failed to save area range', 'error');
  8324. }
  8325. } catch (err) {
  8326. showToast('Error', err.message, 'error');
  8327. }
  8328. }
  8329. function applyOspfAreaRangeForm() {
  8330. submitOspfAreaRange(null);
  8331. }
  8332. async function deleteCurrentOspfAreaRange() {
  8333. const id = document.getElementById('modal-ospf-range-id').value;
  8334. if (!id) return;
  8335. if (!confirm('Delete this area range?')) return;
  8336. try {
  8337. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8338. closeOspfAreaRangeModal();
  8339. showToast('Removed', 'Area range removed', 'success');
  8340. loadDynamicRouting();
  8341. } catch (err) {
  8342. showToast('Error', err.message, 'error');
  8343. }
  8344. }
  8345. async function enableSelectedOspfAreaRange() {
  8346. const id = state.selectedOspfRow?.['area-ranges'];
  8347. if (!id) return;
  8348. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8349. if (!r) return;
  8350. r.disabled = false;
  8351. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8352. loadDynamicRouting();
  8353. }
  8354. async function disableSelectedOspfAreaRange() {
  8355. const id = state.selectedOspfRow?.['area-ranges'];
  8356. if (!id) return;
  8357. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8358. if (!r) return;
  8359. r.disabled = true;
  8360. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8361. loadDynamicRouting();
  8362. }
  8363. async function removeSelectedOspfAreaRange() {
  8364. const id = state.selectedOspfRow?.['area-ranges'];
  8365. if (!id) return;
  8366. if (!confirm('Delete selected area range?')) return;
  8367. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8368. loadDynamicRouting();
  8369. }
  8370. async function promptCommentOspfAreaRange() {
  8371. const id = state.selectedOspfRow?.['area-ranges'];
  8372. if (!id) return;
  8373. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8374. if (!r) return;
  8375. const comment = prompt('Enter comment for area range:', r.comment || '');
  8376. if (comment === null) return;
  8377. r.comment = comment;
  8378. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8379. loadDynamicRouting();
  8380. }
  8381. // --- 4. OSPF INTERFACE TEMPLATE ---
  8382. function switchOspfTemplateTab(tab) {
  8383. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8384. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8385. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8386. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8387. if (tab === 'general') {
  8388. if (tabGen) tabGen.classList.remove('hidden');
  8389. if (tabAuth) tabAuth.classList.add('hidden');
  8390. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8391. 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';
  8392. } else {
  8393. if (tabGen) tabGen.classList.add('hidden');
  8394. if (tabAuth) tabAuth.classList.remove('hidden');
  8395. 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';
  8396. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8397. }
  8398. }
  8399. function populateTemplateAreaDropdowns() {
  8400. const select = document.getElementById('modal-ospf-tmpl-area');
  8401. if (select) {
  8402. const cur = select.value;
  8403. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8404. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8405. if (cur) select.value = cur;
  8406. }
  8407. }
  8408. function openOspfTemplateModal(id = null) {
  8409. const isEdit = !!id;
  8410. populateTemplateAreaDropdowns();
  8411. switchOspfTemplateTab('general');
  8412. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8413. id: '',
  8414. interfaces: '',
  8415. area: 'Default',
  8416. networks: '',
  8417. network_type: 'broadcast',
  8418. cost: 1,
  8419. priority: 128,
  8420. passive: false,
  8421. hello_interval: 10,
  8422. dead_interval: 40,
  8423. auth: 'none',
  8424. auth_key: '',
  8425. disabled: false,
  8426. comment: ''
  8427. };
  8428. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8429. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8430. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8431. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8432. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8433. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8434. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8435. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8436. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8437. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8438. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8439. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8440. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8441. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8442. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8443. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8444. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8445. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8446. }
  8447. function openEditOspfTemplateModal(id) {
  8448. openOspfTemplateModal(id);
  8449. }
  8450. function closeOspfTemplateModal() {
  8451. document.getElementById('ospf-template-modal').classList.add('hidden');
  8452. }
  8453. async function submitOspfTemplate(e) {
  8454. if (e) e.preventDefault();
  8455. const payload = {
  8456. id: document.getElementById('modal-ospf-tmpl-id').value,
  8457. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8458. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8459. area: document.getElementById('modal-ospf-tmpl-area').value,
  8460. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8461. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8462. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8463. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8464. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8465. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8466. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8467. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8468. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8469. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8470. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8471. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8472. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8473. };
  8474. try {
  8475. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8476. method: 'POST',
  8477. headers: { 'Content-Type': 'application/json' },
  8478. body: JSON.stringify(payload)
  8479. });
  8480. if (res.ok) {
  8481. closeOspfTemplateModal();
  8482. showToast('Saved', 'Interface template saved', 'success');
  8483. loadDynamicRouting();
  8484. } else {
  8485. const err = await res.json();
  8486. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8487. }
  8488. } catch (err) {
  8489. showToast('Error', err.message, 'error');
  8490. }
  8491. }
  8492. function applyOspfTemplateForm() {
  8493. submitOspfTemplate(null);
  8494. }
  8495. function copyOspfTemplate() {
  8496. document.getElementById('modal-ospf-tmpl-id').value = '';
  8497. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8498. showToast('Copied', 'Duplicated as new template', 'info');
  8499. }
  8500. async function deleteCurrentOspfTemplate() {
  8501. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8502. if (!id) return;
  8503. if (!confirm('Delete this interface template?')) return;
  8504. try {
  8505. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8506. closeOspfTemplateModal();
  8507. showToast('Removed', 'Interface template deleted', 'success');
  8508. loadDynamicRouting();
  8509. } catch (err) {
  8510. showToast('Error', err.message, 'error');
  8511. }
  8512. }
  8513. async function enableSelectedOspfTemplate() {
  8514. const id = state.selectedOspfRow?.templates;
  8515. if (!id) return;
  8516. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8517. method: 'POST',
  8518. headers: { 'Content-Type': 'application/json' },
  8519. body: JSON.stringify({ disabled: false })
  8520. });
  8521. loadDynamicRouting();
  8522. }
  8523. async function disableSelectedOspfTemplate() {
  8524. const id = state.selectedOspfRow?.templates;
  8525. if (!id) return;
  8526. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8527. method: 'POST',
  8528. headers: { 'Content-Type': 'application/json' },
  8529. body: JSON.stringify({ disabled: true })
  8530. });
  8531. loadDynamicRouting();
  8532. }
  8533. async function removeSelectedOspfTemplate() {
  8534. const id = state.selectedOspfRow?.templates;
  8535. if (!id) return;
  8536. if (!confirm('Delete selected interface template?')) return;
  8537. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8538. loadDynamicRouting();
  8539. }
  8540. async function promptCommentOspfTemplate() {
  8541. const id = state.selectedOspfRow?.templates;
  8542. if (!id) return;
  8543. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8544. if (!tmpl) return;
  8545. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8546. if (comment === null) return;
  8547. tmpl.comment = comment;
  8548. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8549. method: 'POST',
  8550. headers: { 'Content-Type': 'application/json' },
  8551. body: JSON.stringify(tmpl)
  8552. });
  8553. loadDynamicRouting();
  8554. }
  8555. // --- 5. OSPF STATIC NEIGHBOR ---
  8556. function populateStaticNbrAreaDropdowns() {
  8557. const select = document.getElementById('modal-ospf-snbr-area');
  8558. if (select) {
  8559. const cur = select.value;
  8560. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8561. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8562. if (cur) select.value = cur;
  8563. }
  8564. }
  8565. function openOspfStaticNbrModal(id = null) {
  8566. const isEdit = !!id;
  8567. populateStaticNbrAreaDropdowns();
  8568. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8569. id: '',
  8570. address: '',
  8571. area: 'Default',
  8572. poll_interval: 120,
  8573. cost: 1,
  8574. disabled: false,
  8575. comment: ''
  8576. };
  8577. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8578. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8579. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8580. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8581. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8582. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8583. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8584. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8585. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8586. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8587. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8588. }
  8589. function openEditOspfStaticNbrModal(id) {
  8590. openOspfStaticNbrModal(id);
  8591. }
  8592. function closeOspfStaticNbrModal() {
  8593. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8594. }
  8595. async function submitOspfStaticNbr(e) {
  8596. if (e) e.preventDefault();
  8597. const payload = {
  8598. id: document.getElementById('modal-ospf-snbr-id').value,
  8599. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8600. area: document.getElementById('modal-ospf-snbr-area').value,
  8601. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8602. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8603. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8604. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8605. };
  8606. try {
  8607. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8608. method: 'POST',
  8609. headers: { 'Content-Type': 'application/json' },
  8610. body: JSON.stringify(payload)
  8611. });
  8612. if (res.ok) {
  8613. closeOspfStaticNbrModal();
  8614. showToast('Saved', 'Static neighbor saved', 'success');
  8615. loadDynamicRouting();
  8616. } else {
  8617. const err = await res.json();
  8618. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8619. }
  8620. } catch (err) {
  8621. showToast('Error', err.message, 'error');
  8622. }
  8623. }
  8624. function applyOspfStaticNbrForm() {
  8625. submitOspfStaticNbr(null);
  8626. }
  8627. async function deleteCurrentOspfStaticNbr() {
  8628. const id = document.getElementById('modal-ospf-snbr-id').value;
  8629. if (!id) return;
  8630. if (!confirm('Delete this static neighbor?')) return;
  8631. try {
  8632. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8633. closeOspfStaticNbrModal();
  8634. showToast('Removed', 'Static neighbor removed', 'success');
  8635. loadDynamicRouting();
  8636. } catch (err) {
  8637. showToast('Error', err.message, 'error');
  8638. }
  8639. }
  8640. async function enableSelectedOspfStaticNbr() {
  8641. const id = state.selectedOspfRow?.['static-nbrs'];
  8642. if (!id) return;
  8643. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8644. if (!n) return;
  8645. n.disabled = false;
  8646. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8647. loadDynamicRouting();
  8648. }
  8649. async function disableSelectedOspfStaticNbr() {
  8650. const id = state.selectedOspfRow?.['static-nbrs'];
  8651. if (!id) return;
  8652. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8653. if (!n) return;
  8654. n.disabled = true;
  8655. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8656. loadDynamicRouting();
  8657. }
  8658. async function removeSelectedOspfStaticNbr() {
  8659. const id = state.selectedOspfRow?.['static-nbrs'];
  8660. if (!id) return;
  8661. if (!confirm('Delete selected static neighbor?')) return;
  8662. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8663. loadDynamicRouting();
  8664. }
  8665. async function promptCommentOspfStaticNbr() {
  8666. const id = state.selectedOspfRow?.['static-nbrs'];
  8667. if (!id) return;
  8668. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8669. if (!n) return;
  8670. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8671. if (comment === null) return;
  8672. n.comment = comment;
  8673. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8674. loadDynamicRouting();
  8675. }
  8676. // Backward-compat aliases
  8677. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8678. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8679. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8680. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8681. function deleteOspfInterface(id) {
  8682. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8683. }
  8684. function toggleOspfInterfaceState(id, disabled) {
  8685. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8686. method: 'POST',
  8687. headers: { 'Content-Type': 'application/json' },
  8688. body: JSON.stringify({ disabled })
  8689. }).then(() => loadDynamicRouting());
  8690. }
  8691. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8692. function deleteOspfArea(id) {
  8693. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8694. }
  8695. // ============================================================================
  8696. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8697. // ============================================================================
  8698. function switchBridgeSubTab(tab) {
  8699. state.bridgeSubTab = tab;
  8700. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8701. tabs.forEach(t => {
  8702. const panel = document.getElementById(`bridge-subtab-${t}`);
  8703. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8704. if (panel) {
  8705. if (t === tab) panel.classList.remove('hidden');
  8706. else panel.classList.add('hidden');
  8707. }
  8708. if (btn) {
  8709. if (t === tab) {
  8710. 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';
  8711. } else {
  8712. 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';
  8713. }
  8714. }
  8715. });
  8716. const addBtn = document.getElementById('bridge-top-action-btn');
  8717. if (addBtn) {
  8718. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8719. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8720. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8721. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8722. }
  8723. if (tab === 'hosts') loadBridgeHosts();
  8724. setTimeout(initTableSorting, 50);
  8725. }
  8726. function openCurrentBridgeModal() {
  8727. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8728. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8729. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8730. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8731. }
  8732. async function loadBridge() {
  8733. try {
  8734. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8735. fetch(`${API_BASE}/bridge/bridges`),
  8736. fetch(`${API_BASE}/bridge/ports`),
  8737. fetch(`${API_BASE}/bridge/vlans`),
  8738. fetch(`${API_BASE}/bridge/summary`),
  8739. fetch(`${API_BASE}/vpn/eoip`),
  8740. fetch(`${API_BASE}/vlans`)
  8741. ]);
  8742. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8743. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8744. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8745. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8746. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8747. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8748. // Badges & Stats
  8749. const bBridges = document.getElementById('bridge-badge-bridges');
  8750. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8751. const bPorts = document.getElementById('bridge-badge-ports');
  8752. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8753. const bVlans = document.getElementById('bridge-badge-vlans');
  8754. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8755. const bHosts = document.getElementById('bridge-badge-hosts');
  8756. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8757. const sBr = document.getElementById('bridge-stat-bridges');
  8758. if (sBr) sBr.innerText = (state.bridges || []).length;
  8759. const sPorts = document.getElementById('bridge-stat-ports');
  8760. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8761. const sHosts = document.getElementById('bridge-stat-hosts');
  8762. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8763. renderBridges();
  8764. renderBridgePorts();
  8765. renderBridgeVLANs();
  8766. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8767. } catch (err) {
  8768. console.error('Failed to load bridge subsystem:', err);
  8769. }
  8770. }
  8771. // ----------------- Bridges -----------------
  8772. function renderBridges() {
  8773. const tbody = document.getElementById('bridge-table-body');
  8774. const empty = document.getElementById('bridge-empty-bridges');
  8775. const countBadge = document.getElementById('bridge-count-badge');
  8776. if (!tbody) return;
  8777. tbody.innerHTML = '';
  8778. const bridges = state.bridges || [];
  8779. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8780. if (bridges.length === 0) {
  8781. empty?.classList.remove('hidden');
  8782. return;
  8783. }
  8784. empty?.classList.add('hidden');
  8785. bridges.forEach((b, idx) => {
  8786. const tr = document.createElement('tr');
  8787. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8788. // Format IP addresses pill list
  8789. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8790. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8791. ipsHtml = b.ip_addresses.map(ip => `
  8792. <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">
  8793. <span>${ip}</span>
  8794. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8795. </span>
  8796. `).join(' ');
  8797. }
  8798. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8799. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8800. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  8801. tr.innerHTML = `
  8802. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  8803. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  8804. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8805. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8806. </td>
  8807. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8808. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8809. <td class="py-2.5 px-3">
  8810. <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>
  8811. </td>
  8812. <td class="py-2.5 px-3 text-center">
  8813. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8814. </td>
  8815. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8816. <td class="py-2.5 px-3">
  8817. <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>
  8818. </td>
  8819. <td class="py-2.5 px-3">
  8820. <div class="flex items-center gap-1.5 flex-wrap">
  8821. ${ipsHtml}
  8822. <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>
  8823. </div>
  8824. </td>
  8825. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8826. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8827. </td>
  8828. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8829. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8830. <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>
  8831. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8832. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8833. </td>
  8834. `;
  8835. tbody.appendChild(tr);
  8836. });
  8837. }
  8838. function openAddBridgeModal() {
  8839. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8840. document.getElementById('bridge-modal-id').value = '';
  8841. document.getElementById('bridge-modal-name').value = 'bridge1';
  8842. document.getElementById('bridge-modal-name').disabled = false;
  8843. document.getElementById('bridge-modal-mtu').value = '1500';
  8844. document.getElementById('bridge-modal-mac').value = '';
  8845. document.getElementById('bridge-modal-stp').value = 'rstp';
  8846. document.getElementById('bridge-modal-priority').value = '32768';
  8847. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8848. document.getElementById('bridge-modal-pvid').value = '1';
  8849. document.getElementById('bridge-modal-fastforward').checked = true;
  8850. document.getElementById('bridge-modal-comment').value = '';
  8851. document.getElementById('bridge-modal-disabled').checked = false;
  8852. toggleBridgeModalVlanFiltering();
  8853. document.getElementById('bridge-modal').classList.remove('hidden');
  8854. }
  8855. function openEditBridgeModal(id) {
  8856. const b = (state.bridges || []).find(x => x.id === id);
  8857. if (!b) return;
  8858. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8859. document.getElementById('bridge-modal-id').value = b.id;
  8860. document.getElementById('bridge-modal-name').value = b.name;
  8861. document.getElementById('bridge-modal-name').disabled = true;
  8862. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8863. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8864. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8865. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8866. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8867. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8868. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8869. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8870. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8871. toggleBridgeModalVlanFiltering();
  8872. document.getElementById('bridge-modal').classList.remove('hidden');
  8873. }
  8874. function closeBridgeModal() {
  8875. document.getElementById('bridge-modal').classList.add('hidden');
  8876. }
  8877. function toggleBridgeModalVlanFiltering() {
  8878. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8879. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8880. if (pvidBox) {
  8881. if (chk) pvidBox.classList.remove('opacity-40');
  8882. else pvidBox.classList.add('opacity-40');
  8883. }
  8884. }
  8885. async function submitSaveBridge(e) {
  8886. e.preventDefault();
  8887. const id = document.getElementById('bridge-modal-id').value;
  8888. const name = document.getElementById('bridge-modal-name').value.trim();
  8889. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8890. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8891. const stp = document.getElementById('bridge-modal-stp').value;
  8892. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8893. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8894. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8895. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8896. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8897. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8898. try {
  8899. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8900. method: 'POST',
  8901. headers: { 'Content-Type': 'application/json' },
  8902. body: JSON.stringify({
  8903. id,
  8904. name,
  8905. mtu,
  8906. mac_address: mac,
  8907. stp,
  8908. priority,
  8909. vlan_filtering: vlanFiltering,
  8910. pvid,
  8911. fast_forward: fastForward,
  8912. comment,
  8913. disabled
  8914. })
  8915. });
  8916. if (res.ok) {
  8917. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8918. closeBridgeModal();
  8919. loadBridge();
  8920. fetchData(false);
  8921. } else {
  8922. const err = await res.json();
  8923. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8924. }
  8925. } catch (err) {
  8926. showToast('Error', err.message, 'error');
  8927. }
  8928. }
  8929. async function toggleBridgeState(id, disabled) {
  8930. try {
  8931. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8932. method: 'POST',
  8933. headers: { 'Content-Type': 'application/json' },
  8934. body: JSON.stringify({ disabled })
  8935. });
  8936. if (res.ok) {
  8937. loadBridge();
  8938. fetchData(false);
  8939. }
  8940. } catch (err) {
  8941. showToast('Error', err.message, 'error');
  8942. }
  8943. }
  8944. async function deleteBridge(id) {
  8945. const b = (state.bridges || []).find(x => x.id === id);
  8946. const name = b ? b.name : id;
  8947. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8948. try {
  8949. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8950. if (res.ok) {
  8951. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8952. loadBridge();
  8953. fetchData(false);
  8954. } else {
  8955. const err = await res.json();
  8956. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8957. }
  8958. } catch (err) {
  8959. showToast('Error', err.message, 'error');
  8960. }
  8961. }
  8962. // ----------------- Bridge IP Assignments -----------------
  8963. function openAddBridgeIPModal(id, name) {
  8964. document.getElementById('bridge-ip-modal-id').value = id;
  8965. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8966. document.getElementById('bridge-ip-modal-cidr').value = '';
  8967. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8968. }
  8969. function closeBridgeIPModal() {
  8970. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8971. }
  8972. async function submitAddBridgeIP(e) {
  8973. e.preventDefault();
  8974. const id = document.getElementById('bridge-ip-modal-id').value;
  8975. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8976. try {
  8977. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8978. method: 'POST',
  8979. headers: { 'Content-Type': 'application/json' },
  8980. body: JSON.stringify({ ip })
  8981. });
  8982. if (res.ok) {
  8983. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8984. closeBridgeIPModal();
  8985. loadBridge();
  8986. fetchData(false);
  8987. } else {
  8988. const err = await res.json();
  8989. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8990. }
  8991. } catch (err) {
  8992. showToast('Error', err.message, 'error');
  8993. }
  8994. }
  8995. async function deleteBridgeIP(id, ip) {
  8996. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8997. try {
  8998. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8999. method: 'DELETE',
  9000. headers: { 'Content-Type': 'application/json' },
  9001. body: JSON.stringify({ ip })
  9002. });
  9003. if (res.ok) {
  9004. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9005. loadBridge();
  9006. fetchData(false);
  9007. }
  9008. } catch (err) {
  9009. showToast('Error', err.message, 'error');
  9010. }
  9011. }
  9012. // ----------------- Bridge Ports -----------------
  9013. function renderBridgePorts() {
  9014. const tbody = document.getElementById('bridge-ports-table-body');
  9015. const empty = document.getElementById('bridge-empty-ports');
  9016. const countBadge = document.getElementById('bridge-ports-count-badge');
  9017. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9018. if (!tbody) return;
  9019. tbody.innerHTML = '';
  9020. // Update filter select
  9021. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9022. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9023. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9024. if (ports.length === 0) {
  9025. empty?.classList.remove('hidden');
  9026. return;
  9027. }
  9028. empty?.classList.add('hidden');
  9029. ports.forEach((p, idx) => {
  9030. const tr = document.createElement('tr');
  9031. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9032. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9033. tr.innerHTML = `
  9034. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9035. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9036. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9037. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9038. </td>
  9039. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9040. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9041. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9042. <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>
  9043. <td class="py-2.5 px-3">
  9044. ${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>'}
  9045. </td>
  9046. <td class="py-2.5 px-3">
  9047. <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>
  9048. </td>
  9049. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9050. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9051. <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>
  9052. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9053. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9054. </td>
  9055. `;
  9056. tbody.appendChild(tr);
  9057. });
  9058. }
  9059. function openAddBridgePortModal() {
  9060. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9061. document.getElementById('bridge-port-modal-id').value = '';
  9062. populateBridgeSelect('bridge-port-modal-bridge');
  9063. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9064. document.getElementById('bridge-port-modal-pvid').value = '1';
  9065. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9066. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9067. document.getElementById('bridge-port-modal-horizon').value = '0';
  9068. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9069. document.getElementById('bridge-port-modal-priority').value = '128';
  9070. document.getElementById('bridge-port-modal-learn').checked = true;
  9071. document.getElementById('bridge-port-modal-comment').value = '';
  9072. document.getElementById('bridge-port-modal-disabled').checked = false;
  9073. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9074. }
  9075. function openEditBridgePortModal(id) {
  9076. const p = (state.bridgePorts || []).find(x => x.id === id);
  9077. if (!p) return;
  9078. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9079. document.getElementById('bridge-port-modal-id').value = p.id;
  9080. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9081. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9082. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9083. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9084. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9085. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9086. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9087. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9088. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9089. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9090. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9091. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9092. }
  9093. function closeBridgePortModal() {
  9094. document.getElementById('bridge-port-modal').classList.add('hidden');
  9095. }
  9096. async function submitSaveBridgePort(e) {
  9097. e.preventDefault();
  9098. const id = document.getElementById('bridge-port-modal-id').value;
  9099. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9100. const iface = document.getElementById('bridge-port-modal-interface').value;
  9101. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9102. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9103. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9104. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9105. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9106. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9107. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9108. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9109. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9110. try {
  9111. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9112. method: 'POST',
  9113. headers: { 'Content-Type': 'application/json' },
  9114. body: JSON.stringify({
  9115. id,
  9116. bridge,
  9117. interface: iface,
  9118. pvid,
  9119. frame_types: frameTypes,
  9120. ingress_filtering: ingressFiltering,
  9121. horizon,
  9122. path_cost: pathCost,
  9123. priority,
  9124. learn,
  9125. comment,
  9126. disabled
  9127. })
  9128. });
  9129. if (res.ok) {
  9130. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9131. closeBridgePortModal();
  9132. loadBridge();
  9133. fetchData(false);
  9134. } else {
  9135. const err = await res.json();
  9136. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9137. }
  9138. } catch (err) {
  9139. showToast('Error', err.message, 'error');
  9140. }
  9141. }
  9142. async function toggleBridgePortState(id, disabled) {
  9143. try {
  9144. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9145. method: 'POST',
  9146. headers: { 'Content-Type': 'application/json' },
  9147. body: JSON.stringify({ disabled })
  9148. });
  9149. if (res.ok) {
  9150. loadBridge();
  9151. fetchData(false);
  9152. }
  9153. } catch (err) {
  9154. showToast('Error', err.message, 'error');
  9155. }
  9156. }
  9157. async function deleteBridgePort(id) {
  9158. const p = (state.bridgePorts || []).find(x => x.id === id);
  9159. const iface = p ? p.interface : id;
  9160. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9161. try {
  9162. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9163. if (res.ok) {
  9164. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9165. loadBridge();
  9166. fetchData(false);
  9167. }
  9168. } catch (err) {
  9169. showToast('Error', err.message, 'error');
  9170. }
  9171. }
  9172. // ----------------- Bridge VLANs -----------------
  9173. function renderBridgeVLANs() {
  9174. const tbody = document.getElementById('bridge-vlans-table-body');
  9175. const empty = document.getElementById('bridge-empty-vlans');
  9176. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9177. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9178. if (!tbody) return;
  9179. tbody.innerHTML = '';
  9180. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9181. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9182. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9183. if (vlans.length === 0) {
  9184. empty?.classList.remove('hidden');
  9185. return;
  9186. }
  9187. empty?.classList.add('hidden');
  9188. vlans.forEach((v, idx) => {
  9189. const tr = document.createElement('tr');
  9190. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9191. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9192. ? 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(' ')
  9193. : '<span class="text-slate-600">none</span>';
  9194. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9195. ? 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(' ')
  9196. : '<span class="text-slate-600">none</span>';
  9197. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9198. tr.innerHTML = `
  9199. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9200. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9201. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9202. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9203. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9204. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9205. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9206. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9207. <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>
  9208. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9209. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9210. </td>
  9211. `;
  9212. tbody.appendChild(tr);
  9213. });
  9214. }
  9215. function openAddBridgeVLANModal() {
  9216. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9217. document.getElementById('bridge-vlan-modal-id').value = '';
  9218. populateBridgeSelect('bridge-vlan-modal-bridge');
  9219. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9220. document.getElementById('bridge-vlan-modal-comment').value = '';
  9221. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9222. updateBridgeVlanPortCheckboxes();
  9223. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9224. }
  9225. function openEditBridgeVLANModal(id) {
  9226. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9227. if (!v) return;
  9228. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9229. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9230. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9231. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9232. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9233. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9234. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9235. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9236. }
  9237. function closeBridgeVlanModal() {
  9238. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9239. }
  9240. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9241. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9242. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9243. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9244. if (!taggedBox || !untaggedBox) return;
  9245. // Ports belonging to the selected bridge
  9246. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9247. if (memberPorts.length === 0) {
  9248. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9249. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9250. return;
  9251. }
  9252. taggedBox.innerHTML = memberPorts.map(p => `
  9253. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9254. <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">
  9255. <span>${p.interface}</span>
  9256. </label>
  9257. `).join('');
  9258. untaggedBox.innerHTML = memberPorts.map(p => `
  9259. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9260. <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">
  9261. <span>${p.interface}</span>
  9262. </label>
  9263. `).join('');
  9264. }
  9265. async function submitSaveBridgeVLAN(e) {
  9266. e.preventDefault();
  9267. const id = document.getElementById('bridge-vlan-modal-id').value;
  9268. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9269. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9270. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9271. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9272. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9273. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9274. try {
  9275. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9276. method: 'POST',
  9277. headers: { 'Content-Type': 'application/json' },
  9278. body: JSON.stringify({
  9279. id,
  9280. bridge,
  9281. vlan_ids: vlanIDs,
  9282. tagged,
  9283. untagged,
  9284. comment,
  9285. disabled
  9286. })
  9287. });
  9288. if (res.ok) {
  9289. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9290. closeBridgeVlanModal();
  9291. loadBridge();
  9292. } else {
  9293. const err = await res.json();
  9294. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9295. }
  9296. } catch (err) {
  9297. showToast('Error', err.message, 'error');
  9298. }
  9299. }
  9300. async function toggleBridgeVLANState(id, disabled) {
  9301. try {
  9302. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9303. method: 'POST',
  9304. headers: { 'Content-Type': 'application/json' },
  9305. body: JSON.stringify({ disabled })
  9306. });
  9307. if (res.ok) loadBridge();
  9308. } catch (err) {
  9309. showToast('Error', err.message, 'error');
  9310. }
  9311. }
  9312. async function deleteBridgeVLAN(id) {
  9313. if (!confirm('Delete this bridge VLAN entry?')) return;
  9314. try {
  9315. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9316. if (res.ok) {
  9317. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9318. loadBridge();
  9319. }
  9320. } catch (err) {
  9321. showToast('Error', err.message, 'error');
  9322. }
  9323. }
  9324. // ----------------- Hosts / MAC Table -----------------
  9325. async function loadBridgeHosts() {
  9326. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9327. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9328. try {
  9329. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9330. const res = await fetch(url);
  9331. if (res.ok) {
  9332. state.bridgeHosts = await res.json();
  9333. renderBridgeHosts();
  9334. }
  9335. } catch (err) {
  9336. console.error('Failed to load bridge hosts:', err);
  9337. }
  9338. }
  9339. function renderBridgeHosts() {
  9340. const tbody = document.getElementById('bridge-hosts-table-body');
  9341. const empty = document.getElementById('bridge-empty-hosts');
  9342. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9343. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9344. if (!tbody) return;
  9345. tbody.innerHTML = '';
  9346. const hosts = (state.bridgeHosts || []).filter(h => {
  9347. if (!search) return true;
  9348. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9349. });
  9350. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9351. if (hosts.length === 0) {
  9352. empty?.classList.remove('hidden');
  9353. return;
  9354. }
  9355. empty?.classList.add('hidden');
  9356. hosts.forEach(h => {
  9357. const tr = document.createElement('tr');
  9358. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9359. let flagBadges = '';
  9360. 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>';
  9361. 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>';
  9362. 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>';
  9363. tr.innerHTML = `
  9364. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9365. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9366. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9367. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9368. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9369. <td class="py-2.5 px-3">${flagBadges}</td>
  9370. `;
  9371. tbody.appendChild(tr);
  9372. });
  9373. }
  9374. async function flushBridgeHosts() {
  9375. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9376. if (!selBridge) {
  9377. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9378. return;
  9379. }
  9380. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9381. try {
  9382. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9383. method: 'POST',
  9384. headers: { 'Content-Type': 'application/json' },
  9385. body: JSON.stringify({ bridge: selBridge })
  9386. });
  9387. if (res.ok) {
  9388. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9389. loadBridgeHosts();
  9390. }
  9391. } catch (err) {
  9392. showToast('Error', err.message, 'error');
  9393. }
  9394. }
  9395. // ----------------- Helpers -----------------
  9396. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9397. const sel = document.getElementById(selectId);
  9398. if (!sel) return;
  9399. const prevVal = currentVal || sel.value;
  9400. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9401. (state.bridges || []).forEach(b => {
  9402. const opt = document.createElement('option');
  9403. opt.value = b.name;
  9404. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9405. if (b.name === prevVal) opt.selected = true;
  9406. sel.appendChild(opt);
  9407. });
  9408. }
  9409. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9410. const sel = document.getElementById(selectId);
  9411. if (!sel) return;
  9412. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9413. // 1. Physical Interfaces
  9414. const grpPhys = document.createElement('optgroup');
  9415. grpPhys.label = 'Physical Interfaces';
  9416. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9417. const opt = document.createElement('option');
  9418. opt.value = i.name;
  9419. opt.innerText = `${i.name} (${i.role || i.type})`;
  9420. if (i.name === currentVal) opt.selected = true;
  9421. grpPhys.appendChild(opt);
  9422. });
  9423. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9424. // 2. VLAN Sub-interfaces
  9425. const grpVlans = document.createElement('optgroup');
  9426. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9427. (state.vlans || []).forEach(v => {
  9428. const opt = document.createElement('option');
  9429. opt.value = v.name;
  9430. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9431. if (v.name === currentVal) opt.selected = true;
  9432. grpVlans.appendChild(opt);
  9433. });
  9434. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9435. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9436. const grpEoip = document.createElement('optgroup');
  9437. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9438. (state.eoipTunnels || []).forEach(t => {
  9439. const opt = document.createElement('option');
  9440. opt.value = t.name;
  9441. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9442. if (t.name === currentVal) opt.selected = true;
  9443. grpEoip.appendChild(opt);
  9444. });
  9445. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9446. }
  9447. // -------------------------------------------------------------
  9448. // RouterOS v7 Routing Filters Management (/routing filter)
  9449. // -------------------------------------------------------------
  9450. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9451. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9452. if (!state.rfSort) state.rfSort = {};
  9453. function switchRoutingFilterTab(tab) {
  9454. state.activeRoutingFilterTab = tab;
  9455. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9456. tabs.forEach(t => {
  9457. const btn = document.getElementById(`tab-rf-${t}`);
  9458. const content = document.getElementById(`tab-content-rf-${t}`);
  9459. if (btn) {
  9460. if (t === tab) {
  9461. 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';
  9462. } else {
  9463. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9464. }
  9465. }
  9466. if (content) {
  9467. if (t === tab) content.classList.remove('hidden');
  9468. else content.classList.add('hidden');
  9469. }
  9470. });
  9471. const chainContainer = document.getElementById('rf-chain-filter-container');
  9472. if (chainContainer) {
  9473. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9474. else chainContainer.classList.add('hidden');
  9475. }
  9476. renderRoutingFilters();
  9477. }
  9478. function selectFilterRow(tab, id) {
  9479. if (state.selectedFilterRow[tab] === id) {
  9480. delete state.selectedFilterRow[tab];
  9481. } else {
  9482. state.selectedFilterRow[tab] = id;
  9483. }
  9484. if (tab === 'rules') renderRoutingFilterRules();
  9485. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9486. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9487. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9488. }
  9489. function openRoutingFilterNewModal() {
  9490. const tab = state.activeRoutingFilterTab || 'rules';
  9491. if (tab === 'rules') openAddRoutingFilterModal();
  9492. else if (tab === 'select-rules') openAddSelectRuleModal();
  9493. else if (tab === 'community-lists') openAddCommunityListModal();
  9494. else if (tab === 'as-lists') openAddASListModal();
  9495. }
  9496. function toggleSelectedRoutingFilter(disabled) {
  9497. const tab = state.activeRoutingFilterTab || 'rules';
  9498. const id = state.selectedFilterRow[tab];
  9499. if (!id) {
  9500. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9501. return;
  9502. }
  9503. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9504. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9505. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9506. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9507. }
  9508. function removeSelectedRoutingFilter() {
  9509. const tab = state.activeRoutingFilterTab || 'rules';
  9510. const id = state.selectedFilterRow[tab];
  9511. if (!id) {
  9512. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9513. return;
  9514. }
  9515. if (tab === 'rules') deleteRoutingFilter(id);
  9516. else if (tab === 'select-rules') deleteSelectRule(id);
  9517. else if (tab === 'community-lists') deleteCommunityList(id);
  9518. else if (tab === 'as-lists') deleteASList(id);
  9519. }
  9520. function searchRoutingFilters(q) {
  9521. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9522. renderRoutingFilters();
  9523. }
  9524. function sortFilterTable(tab, col) {
  9525. if (!state.rfSort) state.rfSort = {};
  9526. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9527. if (state.rfSort[tab].col === col) {
  9528. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9529. } else {
  9530. state.rfSort[tab].col = col;
  9531. state.rfSort[tab].asc = true;
  9532. }
  9533. const asc = state.rfSort[tab].asc;
  9534. let list = [];
  9535. if (tab === 'rules') list = state.routingFilters || [];
  9536. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9537. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9538. else if (tab === 'as-lists') list = state.routingASLists || [];
  9539. list.sort((a, b) => {
  9540. let valA = a[col] ?? '';
  9541. let valB = b[col] ?? '';
  9542. if (col === 'flags') {
  9543. valA = a.disabled ? 'X' : 'A';
  9544. valB = b.disabled ? 'X' : 'A';
  9545. }
  9546. if (typeof valA === 'number' && typeof valB === 'number') {
  9547. return asc ? valA - valB : valB - valA;
  9548. }
  9549. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9550. });
  9551. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9552. allCols.forEach(c => {
  9553. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9554. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9555. });
  9556. if (tab === 'rules') renderRoutingFilterRules();
  9557. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9558. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9559. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9560. }
  9561. function renderRoutingFilters() {
  9562. const navBadge = document.getElementById('badge-filters-count');
  9563. const allRules = state.routingFilters || [];
  9564. if (navBadge) navBadge.innerText = allRules.length;
  9565. // Populate chain filter select options and datalist
  9566. const chainSelect = document.getElementById('routing-filter-chain-select');
  9567. const chainDatalist = document.getElementById('dl-routing-chains');
  9568. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9569. if (chainSelect) {
  9570. const currentVal = state.filterChainSelected || 'all';
  9571. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9572. uniqueChains.map(ch => {
  9573. const count = allRules.filter(r => r.chain === ch).length;
  9574. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9575. }).join('');
  9576. chainSelect.value = currentVal;
  9577. }
  9578. if (chainDatalist) {
  9579. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9580. }
  9581. renderRoutingFilterRules();
  9582. renderRoutingFilterSelectRules();
  9583. renderRoutingFilterCommunityLists();
  9584. renderRoutingFilterASLists();
  9585. }
  9586. function filterRoutingFiltersByChain(chain) {
  9587. state.filterChainSelected = chain;
  9588. renderRoutingFilters();
  9589. }
  9590. // -------------------------------------------------------------
  9591. // TAB 1: RULES (/routing filter rule)
  9592. // -------------------------------------------------------------
  9593. function renderRoutingFilterRules() {
  9594. const tbody = document.getElementById('routing-filter-rules-tbody');
  9595. if (!tbody) return;
  9596. const empty = document.getElementById('rf-rules-empty');
  9597. const statusCount = document.getElementById('rf-status-count');
  9598. let list = (state.routingFilters || []).slice();
  9599. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9600. list = list.filter(r => r.chain === state.filterChainSelected);
  9601. }
  9602. const q = state.rfSearchQuery;
  9603. if (q) {
  9604. list = list.filter(r =>
  9605. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9606. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9607. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9608. (r.comment && r.comment.toLowerCase().includes(q))
  9609. );
  9610. }
  9611. if (!state.rfSort?.['rules']) {
  9612. list.sort((a, b) => {
  9613. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9614. return (a.rule_order || 0) - (b.rule_order || 0);
  9615. });
  9616. }
  9617. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9618. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9619. }
  9620. if (list.length === 0) {
  9621. tbody.innerHTML = '';
  9622. if (empty) empty.classList.remove('hidden');
  9623. return;
  9624. }
  9625. if (empty) empty.classList.add('hidden');
  9626. tbody.innerHTML = list.map(r => {
  9627. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9628. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9629. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9630. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9631. let ruleDisplay = '';
  9632. if (r.rule && r.rule.trim() !== '') {
  9633. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9634. } else {
  9635. let conds = [];
  9636. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9637. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9638. let act = r.action || 'accept';
  9639. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9640. }
  9641. return `
  9642. <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'}">
  9643. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9644. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9645. <td class="py-2 px-3">
  9646. <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>
  9647. </td>
  9648. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9649. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9650. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9651. <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>
  9652. <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>
  9653. <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'}">
  9654. ${r.disabled ? 'Enable' : 'Disable'}
  9655. </button>
  9656. <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">
  9657. Edit
  9658. </button>
  9659. <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">
  9660. ✕
  9661. </button>
  9662. </td>
  9663. </tr>
  9664. `;
  9665. }).join('');
  9666. }
  9667. // -------------------------------------------------------------
  9668. // TAB 2: SELECT RULES (/routing filter select-rule)
  9669. // -------------------------------------------------------------
  9670. function renderRoutingFilterSelectRules() {
  9671. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9672. if (!tbody) return;
  9673. const empty = document.getElementById('rf-select-rules-empty');
  9674. const statusCount = document.getElementById('rf-status-count');
  9675. let list = (state.routingSelectRules || []).slice();
  9676. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9677. list = list.filter(r => r.chain === state.filterChainSelected);
  9678. }
  9679. const q = state.rfSearchQuery;
  9680. if (q) {
  9681. list = list.filter(r =>
  9682. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9683. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9684. (r.comment && r.comment.toLowerCase().includes(q))
  9685. );
  9686. }
  9687. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9688. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9689. }
  9690. if (list.length === 0) {
  9691. tbody.innerHTML = '';
  9692. if (empty) empty.classList.remove('hidden');
  9693. return;
  9694. }
  9695. if (empty) empty.classList.add('hidden');
  9696. tbody.innerHTML = list.map(r => {
  9697. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9698. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9699. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9700. return `
  9701. <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'}">
  9702. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9703. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9704. <td class="py-2 px-3">
  9705. <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>
  9706. </td>
  9707. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9708. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9709. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9710. <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'}">
  9711. ${r.disabled ? 'Enable' : 'Disable'}
  9712. </button>
  9713. <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">
  9714. Edit
  9715. </button>
  9716. <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">
  9717. ✕
  9718. </button>
  9719. </td>
  9720. </tr>
  9721. `;
  9722. }).join('');
  9723. }
  9724. // -------------------------------------------------------------
  9725. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9726. // -------------------------------------------------------------
  9727. function renderRoutingFilterCommunityLists() {
  9728. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9729. if (!tbody) return;
  9730. const empty = document.getElementById('rf-comm-lists-empty');
  9731. const statusCount = document.getElementById('rf-status-count');
  9732. let list = (state.routingCommunityLists || []).slice();
  9733. const q = state.rfSearchQuery;
  9734. if (q) {
  9735. list = list.filter(cl =>
  9736. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9737. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9738. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9739. );
  9740. }
  9741. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9742. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9743. }
  9744. if (list.length === 0) {
  9745. tbody.innerHTML = '';
  9746. if (empty) empty.classList.remove('hidden');
  9747. return;
  9748. }
  9749. if (empty) empty.classList.add('hidden');
  9750. tbody.innerHTML = list.map(cl => {
  9751. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9752. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9753. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9754. const commBadges = (cl.communities || []).map(c =>
  9755. `<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>`
  9756. ).join(' ');
  9757. return `
  9758. <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'}">
  9759. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9760. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9761. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9762. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9763. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9764. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9765. <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'}">
  9766. ${cl.disabled ? 'Enable' : 'Disable'}
  9767. </button>
  9768. <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">
  9769. Edit
  9770. </button>
  9771. <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">
  9772. ✕
  9773. </button>
  9774. </td>
  9775. </tr>
  9776. `;
  9777. }).join('');
  9778. }
  9779. // -------------------------------------------------------------
  9780. // TAB 4: AS LISTS (/routing filter num-list)
  9781. // -------------------------------------------------------------
  9782. function renderRoutingFilterASLists() {
  9783. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9784. if (!tbody) return;
  9785. const empty = document.getElementById('rf-as-lists-empty');
  9786. const statusCount = document.getElementById('rf-status-count');
  9787. let list = (state.routingASLists || []).slice();
  9788. const q = state.rfSearchQuery;
  9789. if (q) {
  9790. list = list.filter(al =>
  9791. (al.name && al.name.toLowerCase().includes(q)) ||
  9792. (al.range && al.range.toLowerCase().includes(q)) ||
  9793. (al.comment && al.comment.toLowerCase().includes(q))
  9794. );
  9795. }
  9796. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9797. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9798. }
  9799. if (list.length === 0) {
  9800. tbody.innerHTML = '';
  9801. if (empty) empty.classList.remove('hidden');
  9802. return;
  9803. }
  9804. if (empty) empty.classList.add('hidden');
  9805. tbody.innerHTML = list.map(al => {
  9806. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9807. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9808. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9809. return `
  9810. <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'}">
  9811. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9812. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9813. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9814. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9815. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9816. <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'}">
  9817. ${al.disabled ? 'Enable' : 'Disable'}
  9818. </button>
  9819. <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">
  9820. Edit
  9821. </button>
  9822. <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">
  9823. ✕
  9824. </button>
  9825. </td>
  9826. </tr>
  9827. `;
  9828. }).join('');
  9829. }
  9830. // -------------------------------------------------------------
  9831. // SNIPPETS & WIZARD HELPERS
  9832. // -------------------------------------------------------------
  9833. function insertRuleSnippet(type) {
  9834. const textarea = document.getElementById('modal-rf-rule');
  9835. if (!textarea) return;
  9836. let snippet = '';
  9837. switch (type) {
  9838. case 'accept-default':
  9839. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9840. break;
  9841. case 'drop-rfc1918':
  9842. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9843. break;
  9844. case 'len-24':
  9845. snippet = 'if (dst-len > 24) { reject; }';
  9846. break;
  9847. case 'local-pref-150':
  9848. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9849. break;
  9850. case 'as-prepend-2':
  9851. snippet = 'set bgp-path-prepend 2; accept;';
  9852. break;
  9853. case 'set-comm':
  9854. snippet = 'set bgp-communities.add 65000:100; accept;';
  9855. break;
  9856. case 'match-comm':
  9857. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9858. break;
  9859. case 'reject-all':
  9860. snippet = 'reject;';
  9861. break;
  9862. }
  9863. if (!snippet) return;
  9864. if (!textarea.value.trim()) {
  9865. textarea.value = snippet;
  9866. } else {
  9867. textarea.value = textarea.value.trim() + '\n' + snippet;
  9868. }
  9869. }
  9870. function generateScriptFromWizard() {
  9871. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9872. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9873. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9874. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9875. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9876. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9877. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9878. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9879. const conds = [];
  9880. if (pfx) {
  9881. if (pfxLen) {
  9882. if (pfxLen.includes('-')) {
  9883. const parts = pfxLen.split('-');
  9884. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9885. } else {
  9886. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9887. }
  9888. } else {
  9889. conds.push(`dst in ${pfx}`);
  9890. }
  9891. }
  9892. if (proto && proto !== 'any') {
  9893. conds.push(`protocol ${proto}`);
  9894. }
  9895. if (asp) {
  9896. conds.push(`bgp-as-path "${asp}"`);
  9897. }
  9898. if (comm) {
  9899. conds.push(`bgp-communities includes ${comm}`);
  9900. }
  9901. const actions = [];
  9902. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9903. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9904. actions.push(`${act};`);
  9905. let code = '';
  9906. if (conds.length > 0) {
  9907. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9908. } else {
  9909. code = actions.join(' ');
  9910. }
  9911. const textarea = document.getElementById('modal-rf-rule');
  9912. if (textarea) textarea.value = code;
  9913. }
  9914. // -------------------------------------------------------------
  9915. // MODAL CRUD: RULES (/routing filter rule)
  9916. // -------------------------------------------------------------
  9917. function openAddRoutingFilterModal(defaultChain = '') {
  9918. const form = document.getElementById('routing-filter-form');
  9919. if (form) form.reset();
  9920. const idEl = document.getElementById('modal-rf-id');
  9921. if (idEl) idEl.value = '';
  9922. const titleEl = document.getElementById('modal-rf-title');
  9923. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9924. const chainEl = document.getElementById('modal-rf-chain');
  9925. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9926. const orderEl = document.getElementById('modal-rf-order');
  9927. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9928. const ruleEl = document.getElementById('modal-rf-rule');
  9929. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9930. const disEl = document.getElementById('modal-rf-disabled');
  9931. if (disEl) disEl.checked = false;
  9932. const modal = document.getElementById('modal-routing-filter');
  9933. if (modal) modal.classList.remove('hidden');
  9934. }
  9935. function openEditRoutingFilterModal(id) {
  9936. const r = (state.routingFilters || []).find(item => item.id === id);
  9937. if (!r) return;
  9938. const idEl = document.getElementById('modal-rf-id');
  9939. if (idEl) idEl.value = r.id;
  9940. const titleEl = document.getElementById('modal-rf-title');
  9941. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9942. const chainEl = document.getElementById('modal-rf-chain');
  9943. if (chainEl) chainEl.value = r.chain || '';
  9944. const orderEl = document.getElementById('modal-rf-order');
  9945. if (orderEl) orderEl.value = r.rule_order || 10;
  9946. const ruleEl = document.getElementById('modal-rf-rule');
  9947. if (ruleEl) {
  9948. if (r.rule) {
  9949. ruleEl.value = r.rule;
  9950. } else {
  9951. let conds = [];
  9952. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9953. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9954. let act = r.action || 'accept';
  9955. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9956. }
  9957. }
  9958. const comEl = document.getElementById('modal-rf-comment');
  9959. if (comEl) comEl.value = r.comment || '';
  9960. const disEl = document.getElementById('modal-rf-disabled');
  9961. if (disEl) disEl.checked = !!r.disabled;
  9962. const modal = document.getElementById('modal-routing-filter');
  9963. if (modal) modal.classList.remove('hidden');
  9964. }
  9965. function closeRoutingFilterModal() {
  9966. const modal = document.getElementById('modal-routing-filter');
  9967. if (modal) modal.classList.add('hidden');
  9968. }
  9969. async function submitRoutingFilter(e) {
  9970. if (e) e.preventDefault();
  9971. const payload = {
  9972. id: document.getElementById('modal-rf-id').value,
  9973. chain: document.getElementById('modal-rf-chain').value.trim(),
  9974. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9975. rule: document.getElementById('modal-rf-rule').value.trim(),
  9976. comment: document.getElementById('modal-rf-comment').value.trim(),
  9977. disabled: document.getElementById('modal-rf-disabled').checked
  9978. };
  9979. try {
  9980. const res = await fetch(`${API_BASE}/routing/filters`, {
  9981. method: 'POST',
  9982. headers: { 'Content-Type': 'application/json' },
  9983. body: JSON.stringify(payload)
  9984. });
  9985. if (res.ok) {
  9986. closeRoutingFilterModal();
  9987. showToast('Success', 'Routing filter rule saved', 'success');
  9988. loadDynamicRouting();
  9989. } else {
  9990. const err = await res.json();
  9991. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9992. }
  9993. } catch (err) {
  9994. showToast('Error', err.message, 'error');
  9995. }
  9996. }
  9997. async function applyRoutingFilterForm() {
  9998. const payload = {
  9999. id: document.getElementById('modal-rf-id').value,
  10000. chain: document.getElementById('modal-rf-chain').value.trim(),
  10001. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10002. rule: document.getElementById('modal-rf-rule').value.trim(),
  10003. comment: document.getElementById('modal-rf-comment').value.trim(),
  10004. disabled: document.getElementById('modal-rf-disabled').checked
  10005. };
  10006. try {
  10007. const res = await fetch(`${API_BASE}/routing/filters`, {
  10008. method: 'POST',
  10009. headers: { 'Content-Type': 'application/json' },
  10010. body: JSON.stringify(payload)
  10011. });
  10012. if (res.ok) {
  10013. const data = await res.json();
  10014. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10015. showToast('Applied', 'Routing filter configuration applied', 'success');
  10016. loadDynamicRouting();
  10017. } else {
  10018. const err = await res.json();
  10019. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10020. }
  10021. } catch (err) {
  10022. showToast('Error', err.message, 'error');
  10023. }
  10024. }
  10025. async function moveRoutingFilterOrder(id, delta) {
  10026. const list = state.routingFilters || [];
  10027. const idx = list.findIndex(r => r.id === id);
  10028. if (idx < 0) return;
  10029. const targetIdx = idx + delta;
  10030. if (targetIdx < 0 || targetIdx >= list.length) return;
  10031. const currentOrder = list[idx].rule_order || 10;
  10032. const targetOrder = list[targetIdx].rule_order || 20;
  10033. list[idx].rule_order = targetOrder;
  10034. list[targetIdx].rule_order = currentOrder;
  10035. try {
  10036. await fetch(`${API_BASE}/routing/filters`, {
  10037. method: 'POST',
  10038. headers: { 'Content-Type': 'application/json' },
  10039. body: JSON.stringify(list[idx])
  10040. });
  10041. await fetch(`${API_BASE}/routing/filters`, {
  10042. method: 'POST',
  10043. headers: { 'Content-Type': 'application/json' },
  10044. body: JSON.stringify(list[targetIdx])
  10045. });
  10046. loadDynamicRouting();
  10047. } catch (e) {
  10048. console.error('Reorder error:', e);
  10049. }
  10050. }
  10051. async function deleteRoutingFilter(id) {
  10052. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10053. try {
  10054. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10055. if (res.ok) {
  10056. showToast('Deleted', 'Routing filter rule removed', 'info');
  10057. loadDynamicRouting();
  10058. } else {
  10059. const err = await res.json();
  10060. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10061. }
  10062. } catch (err) {
  10063. showToast('Error', err.message, 'error');
  10064. }
  10065. }
  10066. async function toggleRoutingFilterState(id, disabled) {
  10067. try {
  10068. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10069. method: 'POST',
  10070. headers: { 'Content-Type': 'application/json' },
  10071. body: JSON.stringify({ disabled })
  10072. });
  10073. if (res.ok) {
  10074. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10075. loadDynamicRouting();
  10076. } else {
  10077. const err = await res.json();
  10078. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10079. }
  10080. } catch (err) {
  10081. showToast('Error', err.message, 'error');
  10082. }
  10083. }
  10084. // -------------------------------------------------------------
  10085. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10086. // -------------------------------------------------------------
  10087. function openAddSelectRuleModal() {
  10088. document.getElementById('modal-rf-sr-id').value = '';
  10089. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10090. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10091. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10092. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10093. document.getElementById('modal-rf-sr-comment').value = '';
  10094. document.getElementById('modal-rf-sr-disabled').checked = false;
  10095. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10096. }
  10097. function openEditSelectRuleModal(id) {
  10098. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10099. if (!r) return;
  10100. document.getElementById('modal-rf-sr-id').value = r.id;
  10101. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10102. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10103. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10104. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10105. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10106. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10107. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10108. }
  10109. function closeSelectRuleModal() {
  10110. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10111. }
  10112. async function submitSelectRule(e) {
  10113. e.preventDefault();
  10114. const payload = {
  10115. id: document.getElementById('modal-rf-sr-id').value,
  10116. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10117. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10118. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10119. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10120. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10121. };
  10122. try {
  10123. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10124. method: 'POST',
  10125. headers: { 'Content-Type': 'application/json' },
  10126. body: JSON.stringify(payload)
  10127. });
  10128. if (res.ok) {
  10129. closeSelectRuleModal();
  10130. showToast('Success', 'Select rule saved', 'success');
  10131. loadDynamicRouting();
  10132. } else {
  10133. const err = await res.json();
  10134. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10135. }
  10136. } catch (err) {
  10137. showToast('Error', err.message, 'error');
  10138. }
  10139. }
  10140. async function deleteSelectRule(id) {
  10141. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10142. try {
  10143. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10144. if (res.ok) {
  10145. showToast('Deleted', 'Select rule removed', 'info');
  10146. loadDynamicRouting();
  10147. } else {
  10148. const err = await res.json();
  10149. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10150. }
  10151. } catch (err) {
  10152. showToast('Error', err.message, 'error');
  10153. }
  10154. }
  10155. async function toggleSelectRuleState(id, disabled) {
  10156. try {
  10157. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10158. method: 'POST',
  10159. headers: { 'Content-Type': 'application/json' },
  10160. body: JSON.stringify({ disabled })
  10161. });
  10162. if (res.ok) {
  10163. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10164. loadDynamicRouting();
  10165. } else {
  10166. const err = await res.json();
  10167. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10168. }
  10169. } catch (err) {
  10170. showToast('Error', err.message, 'error');
  10171. }
  10172. }
  10173. // -------------------------------------------------------------
  10174. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10175. // -------------------------------------------------------------
  10176. function openAddCommunityListModal() {
  10177. document.getElementById('modal-rf-cl-id').value = '';
  10178. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10179. document.getElementById('modal-rf-cl-name').value = '';
  10180. document.getElementById('modal-rf-cl-communities').value = '';
  10181. document.getElementById('modal-rf-cl-regexp').value = '';
  10182. document.getElementById('modal-rf-cl-comment').value = '';
  10183. document.getElementById('modal-rf-cl-disabled').checked = false;
  10184. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10185. }
  10186. function openEditCommunityListModal(id) {
  10187. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10188. if (!cl) return;
  10189. document.getElementById('modal-rf-cl-id').value = cl.id;
  10190. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10191. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10192. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10193. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10194. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10195. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10196. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10197. }
  10198. function closeCommunityListModal() {
  10199. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10200. }
  10201. async function submitCommunityList(e) {
  10202. e.preventDefault();
  10203. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10204. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10205. const payload = {
  10206. id: document.getElementById('modal-rf-cl-id').value,
  10207. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10208. communities: comms,
  10209. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10210. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10211. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10212. };
  10213. try {
  10214. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10215. method: 'POST',
  10216. headers: { 'Content-Type': 'application/json' },
  10217. body: JSON.stringify(payload)
  10218. });
  10219. if (res.ok) {
  10220. closeCommunityListModal();
  10221. showToast('Success', 'Community list saved', 'success');
  10222. loadDynamicRouting();
  10223. } else {
  10224. const err = await res.json();
  10225. showToast('Error', err.error || 'Failed to save community list', 'error');
  10226. }
  10227. } catch (err) {
  10228. showToast('Error', err.message, 'error');
  10229. }
  10230. }
  10231. async function deleteCommunityList(id) {
  10232. if (!confirm('Are you sure you want to delete this community list?')) return;
  10233. try {
  10234. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10235. if (res.ok) {
  10236. showToast('Deleted', 'Community list removed', 'info');
  10237. loadDynamicRouting();
  10238. } else {
  10239. const err = await res.json();
  10240. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10241. }
  10242. } catch (err) {
  10243. showToast('Error', err.message, 'error');
  10244. }
  10245. }
  10246. async function toggleCommunityListState(id, disabled) {
  10247. try {
  10248. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10249. method: 'POST',
  10250. headers: { 'Content-Type': 'application/json' },
  10251. body: JSON.stringify({ disabled })
  10252. });
  10253. if (res.ok) {
  10254. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10255. loadDynamicRouting();
  10256. } else {
  10257. const err = await res.json();
  10258. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10259. }
  10260. } catch (err) {
  10261. showToast('Error', err.message, 'error');
  10262. }
  10263. }
  10264. // -------------------------------------------------------------
  10265. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10266. // -------------------------------------------------------------
  10267. function openAddASListModal() {
  10268. document.getElementById('modal-rf-al-id').value = '';
  10269. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10270. document.getElementById('modal-rf-al-name').value = '';
  10271. document.getElementById('modal-rf-al-range').value = '';
  10272. document.getElementById('modal-rf-al-comment').value = '';
  10273. document.getElementById('modal-rf-al-disabled').checked = false;
  10274. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10275. }
  10276. function openEditASListModal(id) {
  10277. const al = (state.routingASLists || []).find(item => item.id === id);
  10278. if (!al) return;
  10279. document.getElementById('modal-rf-al-id').value = al.id;
  10280. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10281. document.getElementById('modal-rf-al-name').value = al.name || '';
  10282. document.getElementById('modal-rf-al-range').value = al.range || '';
  10283. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10284. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10285. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10286. }
  10287. function closeASListModal() {
  10288. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10289. }
  10290. async function submitASList(e) {
  10291. e.preventDefault();
  10292. const payload = {
  10293. id: document.getElementById('modal-rf-al-id').value,
  10294. name: document.getElementById('modal-rf-al-name').value.trim(),
  10295. range: document.getElementById('modal-rf-al-range').value.trim(),
  10296. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10297. disabled: document.getElementById('modal-rf-al-disabled').checked
  10298. };
  10299. try {
  10300. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10301. method: 'POST',
  10302. headers: { 'Content-Type': 'application/json' },
  10303. body: JSON.stringify(payload)
  10304. });
  10305. if (res.ok) {
  10306. closeASListModal();
  10307. showToast('Success', 'AS number list saved', 'success');
  10308. loadDynamicRouting();
  10309. } else {
  10310. const err = await res.json();
  10311. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10312. }
  10313. } catch (err) {
  10314. showToast('Error', err.message, 'error');
  10315. }
  10316. }
  10317. async function deleteASList(id) {
  10318. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10319. try {
  10320. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10321. if (res.ok) {
  10322. showToast('Deleted', 'AS list removed', 'info');
  10323. loadDynamicRouting();
  10324. } else {
  10325. const err = await res.json();
  10326. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10327. }
  10328. } catch (err) {
  10329. showToast('Error', err.message, 'error');
  10330. }
  10331. }
  10332. async function toggleASListState(id, disabled) {
  10333. try {
  10334. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10335. method: 'POST',
  10336. headers: { 'Content-Type': 'application/json' },
  10337. body: JSON.stringify({ disabled })
  10338. });
  10339. if (res.ok) {
  10340. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10341. loadDynamicRouting();
  10342. } else {
  10343. const err = await res.json();
  10344. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10345. }
  10346. } catch (err) {
  10347. showToast('Error', err.message, 'error');
  10348. }
  10349. }
  10350. // ==========================================
  10351. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10352. // ==========================================
  10353. function loadToolsView() {
  10354. populateToolsInterfaces();
  10355. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10356. }
  10357. function populateToolsInterfaces() {
  10358. const pingSel = document.getElementById('tools-ping-iface');
  10359. const traceSel = document.getElementById('tools-tr-iface');
  10360. let opts = '<option value="">Auto (Default Route)</option>';
  10361. if (Array.isArray(state.interfaces)) {
  10362. state.interfaces.forEach(iface => {
  10363. if (iface.name) {
  10364. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10365. }
  10366. });
  10367. }
  10368. if (pingSel) {
  10369. const cur = pingSel.value;
  10370. pingSel.innerHTML = opts;
  10371. if (cur) pingSel.value = cur;
  10372. }
  10373. if (traceSel) {
  10374. const cur = traceSel.value;
  10375. traceSel.innerHTML = opts;
  10376. if (cur) traceSel.value = cur;
  10377. }
  10378. }
  10379. function switchToolsSubTab(subTab) {
  10380. state.activeToolsSubTab = subTab;
  10381. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10382. tabs.forEach(t => {
  10383. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10384. const view = document.getElementById(`tools-view-${t}`);
  10385. if (btn) {
  10386. if (t === subTab) {
  10387. 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';
  10388. } else {
  10389. 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';
  10390. }
  10391. }
  10392. if (view) {
  10393. if (t === subTab) {
  10394. view.classList.remove('hidden');
  10395. } else {
  10396. view.classList.add('hidden');
  10397. }
  10398. }
  10399. });
  10400. }
  10401. function setPortPreset(port) {
  10402. const input = document.getElementById('tools-port-num');
  10403. if (input) input.value = port;
  10404. }
  10405. let pingAbortController = null;
  10406. let tracerouteAbortController = null;
  10407. function clearPingTable() {
  10408. const tbody = document.getElementById('tools-ping-tbody');
  10409. if (tbody) tbody.innerHTML = '';
  10410. const rawEl = document.getElementById('tools-ping-raw');
  10411. if (rawEl) rawEl.innerText = '';
  10412. const sentEl = document.getElementById('tools-ping-stat-sent');
  10413. if (sentEl) sentEl.innerText = '0';
  10414. const recvEl = document.getElementById('tools-ping-stat-recv');
  10415. if (recvEl) recvEl.innerText = '0';
  10416. const lossEl = document.getElementById('tools-ping-stat-loss');
  10417. if (lossEl) lossEl.innerText = '0%';
  10418. const avgEl = document.getElementById('tools-ping-stat-avg');
  10419. if (avgEl) avgEl.innerText = '0 ms';
  10420. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10421. if (minMaxEl) minMaxEl.innerText = '-';
  10422. const badge = document.getElementById('tools-ping-status-badge');
  10423. if (badge) {
  10424. badge.className = '';
  10425. badge.innerText = '';
  10426. }
  10427. }
  10428. function clearTracerouteTable() {
  10429. const tbody = document.getElementById('tools-tr-tbody');
  10430. if (tbody) tbody.innerHTML = '';
  10431. const rawEl = document.getElementById('tools-tr-raw');
  10432. if (rawEl) rawEl.innerText = '';
  10433. const statHops = document.getElementById('tools-tr-hops-count');
  10434. if (statHops) statHops.innerText = '0 Hops';
  10435. }
  10436. function resetPingButton() {
  10437. const btn = document.getElementById('tools-ping-btn');
  10438. const btnText = document.getElementById('tools-ping-btn-text');
  10439. const spinner = document.getElementById('tools-ping-spinner');
  10440. if (btn) {
  10441. btn.disabled = false;
  10442. 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';
  10443. }
  10444. if (btnText) btnText.innerText = 'Start Ping';
  10445. if (spinner) spinner.classList.add('hidden');
  10446. }
  10447. function setPingRunningButton() {
  10448. const btn = document.getElementById('tools-ping-btn');
  10449. const btnText = document.getElementById('tools-ping-btn-text');
  10450. const spinner = document.getElementById('tools-ping-spinner');
  10451. if (btn) {
  10452. btn.disabled = false;
  10453. 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';
  10454. }
  10455. if (btnText) btnText.innerText = 'Stop Ping';
  10456. if (spinner) spinner.classList.remove('hidden');
  10457. }
  10458. function resetTracerouteButton() {
  10459. const btn = document.getElementById('tools-tr-btn');
  10460. const btnText = document.getElementById('tools-tr-btn-text');
  10461. const spinner = document.getElementById('tools-tr-spinner');
  10462. if (btn) {
  10463. btn.disabled = false;
  10464. 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';
  10465. }
  10466. if (btnText) btnText.innerText = 'Start Traceroute';
  10467. if (spinner) spinner.classList.add('hidden');
  10468. }
  10469. function setTracerouteRunningButton() {
  10470. const btn = document.getElementById('tools-tr-btn');
  10471. const btnText = document.getElementById('tools-tr-btn-text');
  10472. const spinner = document.getElementById('tools-tr-spinner');
  10473. if (btn) {
  10474. btn.disabled = false;
  10475. 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';
  10476. }
  10477. if (btnText) btnText.innerText = 'Stop Traceroute';
  10478. if (spinner) spinner.classList.remove('hidden');
  10479. }
  10480. async function executePing(e) {
  10481. if (e) e.preventDefault();
  10482. // If already running, clicking the button stops the stream!
  10483. if (pingAbortController) {
  10484. pingAbortController.abort();
  10485. pingAbortController = null;
  10486. resetPingButton();
  10487. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10488. return;
  10489. }
  10490. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10491. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10492. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10493. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10494. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10495. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10496. if (!target) {
  10497. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10498. return;
  10499. }
  10500. clearPingTable();
  10501. const resCard = document.getElementById('tools-ping-results');
  10502. if (resCard) resCard.classList.remove('hidden');
  10503. pingAbortController = new AbortController();
  10504. setPingRunningButton();
  10505. try {
  10506. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10507. method: 'POST',
  10508. headers: { 'Content-Type': 'application/json' },
  10509. body: JSON.stringify({
  10510. target,
  10511. count,
  10512. size,
  10513. timeout,
  10514. interface: iface,
  10515. dont_frag: dontFrag
  10516. }),
  10517. signal: pingAbortController.signal
  10518. });
  10519. if (!res.ok) {
  10520. const errText = await res.text();
  10521. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10522. resetPingButton();
  10523. pingAbortController = null;
  10524. return;
  10525. }
  10526. const reader = res.body.getReader();
  10527. const decoder = new TextDecoder('utf-8');
  10528. let buffer = '';
  10529. while (true) {
  10530. const { done, value } = await reader.read();
  10531. if (done) break;
  10532. buffer += decoder.decode(value, { stream: true });
  10533. const blocks = buffer.split('\n\n');
  10534. buffer = blocks.pop() || '';
  10535. for (const block of blocks) {
  10536. const trimmed = block.trim();
  10537. if (!trimmed) continue;
  10538. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10539. try {
  10540. const evt = JSON.parse(line);
  10541. handleLivePingEvent(evt);
  10542. } catch (parseErr) {
  10543. console.warn('Ping SSE parse error:', parseErr, line);
  10544. }
  10545. }
  10546. }
  10547. } catch (err) {
  10548. if (err.name === 'AbortError') {
  10549. // User aborted normally
  10550. } else {
  10551. showToast('Ping Error', err.message, 'error');
  10552. }
  10553. } finally {
  10554. pingAbortController = null;
  10555. resetPingButton();
  10556. }
  10557. }
  10558. function handleLivePingEvent(evt) {
  10559. const sentEl = document.getElementById('tools-ping-stat-sent');
  10560. const recvEl = document.getElementById('tools-ping-stat-recv');
  10561. const lossEl = document.getElementById('tools-ping-stat-loss');
  10562. const avgEl = document.getElementById('tools-ping-stat-avg');
  10563. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10564. const badge = document.getElementById('tools-ping-status-badge');
  10565. const tbody = document.getElementById('tools-ping-tbody');
  10566. const rawEl = document.getElementById('tools-ping-raw');
  10567. if (evt.raw && rawEl) {
  10568. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10569. rawEl.scrollTop = rawEl.scrollHeight;
  10570. }
  10571. if (evt.type === 'reply') {
  10572. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10573. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10574. if (lossEl && evt.packet_loss_pct !== undefined) {
  10575. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10576. lossEl.className = evt.packet_loss_pct === 0
  10577. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10578. : (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');
  10579. }
  10580. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10581. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10582. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10583. }
  10584. if (badge) {
  10585. if (evt.packet_loss_pct === 0) {
  10586. 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';
  10587. badge.innerText = '100% OK';
  10588. } else {
  10589. 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';
  10590. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10591. }
  10592. }
  10593. if (tbody) {
  10594. const tr = document.createElement('tr');
  10595. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10596. tr.innerHTML = `
  10597. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10598. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10599. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10600. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10601. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10602. <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>
  10603. `;
  10604. tbody.appendChild(tr);
  10605. }
  10606. } else if (evt.type === 'timeout') {
  10607. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10608. if (lossEl && evt.packet_loss_pct !== undefined) {
  10609. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10610. 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';
  10611. }
  10612. if (badge) {
  10613. 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';
  10614. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10615. }
  10616. if (tbody) {
  10617. const tr = document.createElement('tr');
  10618. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10619. tr.innerHTML = `
  10620. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10621. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10622. <td class="py-2 px-3 text-slate-600">--</td>
  10623. <td class="py-2 px-3 text-slate-600">--</td>
  10624. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10625. <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>
  10626. `;
  10627. tbody.appendChild(tr);
  10628. }
  10629. } else if (evt.type === 'unreach') {
  10630. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10631. if (lossEl && evt.packet_loss_pct !== undefined) {
  10632. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10633. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10634. }
  10635. if (badge) {
  10636. 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';
  10637. badge.innerText = 'UNREACHABLE';
  10638. }
  10639. if (tbody) {
  10640. const tr = document.createElement('tr');
  10641. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10642. tr.innerHTML = `
  10643. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10644. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10645. <td class="py-2 px-3 text-slate-600">--</td>
  10646. <td class="py-2 px-3 text-slate-600">--</td>
  10647. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10648. <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>
  10649. `;
  10650. tbody.appendChild(tr);
  10651. }
  10652. } else if (evt.type === 'stats') {
  10653. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10654. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10655. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10656. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10657. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10658. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10659. }
  10660. } else if (evt.type === 'done') {
  10661. 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');
  10662. }
  10663. }
  10664. async function executeTraceroute(e) {
  10665. if (e) e.preventDefault();
  10666. if (tracerouteAbortController) {
  10667. tracerouteAbortController.abort();
  10668. tracerouteAbortController = null;
  10669. resetTracerouteButton();
  10670. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10671. return;
  10672. }
  10673. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10674. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10675. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10676. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10677. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10678. if (!target) {
  10679. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10680. return;
  10681. }
  10682. clearTracerouteTable();
  10683. const resCard = document.getElementById('tools-tr-results');
  10684. if (resCard) resCard.classList.remove('hidden');
  10685. tracerouteAbortController = new AbortController();
  10686. setTracerouteRunningButton();
  10687. try {
  10688. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10689. method: 'POST',
  10690. headers: { 'Content-Type': 'application/json' },
  10691. body: JSON.stringify({
  10692. target,
  10693. max_hops: maxHops,
  10694. protocol,
  10695. interface: iface,
  10696. resolve
  10697. }),
  10698. signal: tracerouteAbortController.signal
  10699. });
  10700. if (!res.ok) {
  10701. const errText = await res.text();
  10702. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10703. resetTracerouteButton();
  10704. tracerouteAbortController = null;
  10705. return;
  10706. }
  10707. const reader = res.body.getReader();
  10708. const decoder = new TextDecoder('utf-8');
  10709. let buffer = '';
  10710. while (true) {
  10711. const { done, value } = await reader.read();
  10712. if (done) break;
  10713. buffer += decoder.decode(value, { stream: true });
  10714. const blocks = buffer.split('\n\n');
  10715. buffer = blocks.pop() || '';
  10716. for (const block of blocks) {
  10717. const trimmed = block.trim();
  10718. if (!trimmed) continue;
  10719. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10720. try {
  10721. const evt = JSON.parse(line);
  10722. handleLiveTracerouteEvent(evt);
  10723. } catch (parseErr) {
  10724. console.warn('Traceroute SSE parse error:', parseErr, line);
  10725. }
  10726. }
  10727. }
  10728. } catch (err) {
  10729. if (err.name === 'AbortError') {
  10730. // User aborted normally
  10731. } else {
  10732. showToast('Traceroute Error', err.message, 'error');
  10733. }
  10734. } finally {
  10735. tracerouteAbortController = null;
  10736. resetTracerouteButton();
  10737. }
  10738. }
  10739. function handleLiveTracerouteEvent(evt) {
  10740. const statHops = document.getElementById('tools-tr-hops-count');
  10741. const tbody = document.getElementById('tools-tr-tbody');
  10742. const rawEl = document.getElementById('tools-tr-raw');
  10743. if (evt.raw && rawEl) {
  10744. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10745. rawEl.scrollTop = rawEl.scrollHeight;
  10746. }
  10747. if (evt.hops_count !== undefined && statHops) {
  10748. statHops.innerText = `${evt.hops_count} Hops`;
  10749. }
  10750. if (evt.type === 'hop' && evt.hop && tbody) {
  10751. const h = evt.hop;
  10752. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10753. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10754. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10755. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10756. const tr = document.createElement('tr');
  10757. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10758. tr.innerHTML = `
  10759. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10760. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10761. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10762. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10763. <td class="py-2.5 px-3 text-right">
  10764. ${isTimeout
  10765. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10766. : '<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>'}
  10767. </td>
  10768. `;
  10769. tbody.appendChild(tr);
  10770. } else if (evt.type === 'done') {
  10771. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10772. }
  10773. }
  10774. async function executeMTR(e) {
  10775. if (e) e.preventDefault();
  10776. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10777. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10778. if (!target) {
  10779. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10780. return;
  10781. }
  10782. const btn = document.getElementById('tools-mtr-btn');
  10783. const spinner = document.getElementById('tools-mtr-spinner');
  10784. if (btn) btn.disabled = true;
  10785. if (spinner) spinner.classList.remove('hidden');
  10786. try {
  10787. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10788. method: 'POST',
  10789. headers: { 'Content-Type': 'application/json' },
  10790. body: JSON.stringify({ target, count: cycles })
  10791. });
  10792. const data = await res.json();
  10793. if (!res.ok) {
  10794. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10795. return;
  10796. }
  10797. const resCard = document.getElementById('tools-mtr-results');
  10798. if (resCard) resCard.classList.remove('hidden');
  10799. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10800. const statHops = document.getElementById('tools-mtr-hops-count');
  10801. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10802. const tbody = document.getElementById('tools-mtr-tbody');
  10803. if (tbody) {
  10804. if (hopsCount > 0) {
  10805. tbody.innerHTML = data.hops.map(h => {
  10806. 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');
  10807. return `
  10808. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10809. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10810. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10811. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10812. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10813. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10814. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10815. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10816. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10817. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10818. </tr>
  10819. `;
  10820. }).join('');
  10821. } else {
  10822. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10823. }
  10824. }
  10825. const rawEl = document.getElementById('tools-mtr-raw');
  10826. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10827. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10828. } catch (err) {
  10829. showToast('MTR Error', err.message, 'error');
  10830. } finally {
  10831. if (btn) btn.disabled = false;
  10832. if (spinner) spinner.classList.add('hidden');
  10833. }
  10834. }
  10835. async function executeDNS(e) {
  10836. if (e) e.preventDefault();
  10837. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10838. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10839. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10840. if (!domain) {
  10841. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10842. return;
  10843. }
  10844. const btn = document.getElementById('tools-dns-btn');
  10845. const spinner = document.getElementById('tools-dns-spinner');
  10846. if (btn) btn.disabled = true;
  10847. if (spinner) spinner.classList.remove('hidden');
  10848. try {
  10849. const res = await fetch(`${API_BASE}/tools/dns`, {
  10850. method: 'POST',
  10851. headers: { 'Content-Type': 'application/json' },
  10852. body: JSON.stringify({ domain, type, server })
  10853. });
  10854. const data = await res.json();
  10855. if (!res.ok) {
  10856. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10857. return;
  10858. }
  10859. const resCard = document.getElementById('tools-dns-results');
  10860. if (resCard) resCard.classList.remove('hidden');
  10861. const metaEl = document.getElementById('tools-dns-meta');
  10862. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10863. const tbody = document.getElementById('tools-dns-tbody');
  10864. if (tbody) {
  10865. if (Array.isArray(data.records) && data.records.length > 0) {
  10866. tbody.innerHTML = data.records.map(r => `
  10867. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10868. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10869. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10870. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10871. <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>
  10872. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10873. </tr>
  10874. `).join('');
  10875. } else {
  10876. 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>`;
  10877. }
  10878. }
  10879. const rawEl = document.getElementById('tools-dns-raw');
  10880. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10881. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10882. } catch (err) {
  10883. showToast('DNS Error', err.message, 'error');
  10884. } finally {
  10885. if (btn) btn.disabled = false;
  10886. if (spinner) spinner.classList.add('hidden');
  10887. }
  10888. }
  10889. async function executePortProbe(e) {
  10890. if (e) e.preventDefault();
  10891. const target = document.getElementById('tools-port-target')?.value?.trim();
  10892. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10893. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10894. if (!target || !port) {
  10895. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10896. return;
  10897. }
  10898. const btn = document.getElementById('tools-port-btn');
  10899. const spinner = document.getElementById('tools-port-spinner');
  10900. if (btn) btn.disabled = true;
  10901. if (spinner) spinner.classList.remove('hidden');
  10902. try {
  10903. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10904. method: 'POST',
  10905. headers: { 'Content-Type': 'application/json' },
  10906. body: JSON.stringify({ target, port, timeout })
  10907. });
  10908. const data = await res.json();
  10909. if (!res.ok) {
  10910. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10911. return;
  10912. }
  10913. const resCard = document.getElementById('tools-port-results');
  10914. if (resCard) resCard.classList.remove('hidden');
  10915. const banner = document.getElementById('tools-port-banner');
  10916. const icon = document.getElementById('tools-port-icon');
  10917. const title = document.getElementById('tools-port-title');
  10918. const sub = document.getElementById('tools-port-sub');
  10919. const latency = document.getElementById('tools-port-latency');
  10920. if (data.open) {
  10921. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10922. if (icon) {
  10923. 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';
  10924. icon.innerText = '✓';
  10925. }
  10926. if (title) {
  10927. title.className = 'text-sm font-bold text-emerald-300';
  10928. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10929. }
  10930. if (sub) {
  10931. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10932. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10933. }
  10934. if (latency) {
  10935. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10936. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10937. }
  10938. } else {
  10939. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10940. if (icon) {
  10941. 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';
  10942. icon.innerText = '✕';
  10943. }
  10944. if (title) {
  10945. title.className = 'text-sm font-bold text-rose-300';
  10946. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10947. }
  10948. if (sub) {
  10949. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10950. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10951. }
  10952. if (latency) {
  10953. latency.className = 'text-base font-bold font-mono text-slate-500';
  10954. latency.innerText = '--';
  10955. }
  10956. }
  10957. const rawEl = document.getElementById('tools-port-raw');
  10958. 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'}`);
  10959. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10960. } catch (err) {
  10961. showToast('Probe Error', err.message, 'error');
  10962. } finally {
  10963. if (btn) btn.disabled = false;
  10964. if (spinner) spinner.classList.add('hidden');
  10965. }
  10966. }
  10967. // ==========================================
  10968. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10969. // ==========================================
  10970. async function loadDHCPClients(showToastMsg = false) {
  10971. try {
  10972. const [clientsRes, sumRes] = await Promise.all([
  10973. fetch(`${API_BASE}/dhcp/clients`),
  10974. fetch(`${API_BASE}/dhcp/clients/summary`)
  10975. ]);
  10976. if (clientsRes.ok) {
  10977. state.dhcpClients = await clientsRes.json();
  10978. }
  10979. if (sumRes.ok) {
  10980. state.dhcpSummary = await sumRes.json();
  10981. }
  10982. renderDHCPClients();
  10983. updateDHCPSummaryCards();
  10984. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10985. if (bDhcp && state.dhcpSummary) {
  10986. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10987. }
  10988. if (showToastMsg) {
  10989. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10990. }
  10991. } catch (err) {
  10992. console.error('Failed to load DHCP clients:', err);
  10993. if (showToastMsg) {
  10994. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10995. }
  10996. }
  10997. }
  10998. function updateDHCPSummaryCards() {
  10999. const sum = state.dhcpSummary || {
  11000. total_clients: (state.dhcpClients || []).length,
  11001. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11002. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11003. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11004. };
  11005. const totalEl = document.getElementById('dhcp-stat-total');
  11006. const boundEl = document.getElementById('dhcp-stat-bound');
  11007. const searchEl = document.getElementById('dhcp-stat-searching');
  11008. const disEl = document.getElementById('dhcp-stat-disabled');
  11009. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11010. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11011. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11012. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11013. }
  11014. function renderDHCPClients() {
  11015. const tbody = document.getElementById('dhcp-clients-tbody');
  11016. const emptyState = document.getElementById('dhcp-clients-empty');
  11017. if (!tbody) return;
  11018. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11019. if (clients.length === 0) {
  11020. tbody.innerHTML = '';
  11021. if (emptyState) emptyState.classList.remove('hidden');
  11022. return;
  11023. }
  11024. if (emptyState) emptyState.classList.add('hidden');
  11025. tbody.innerHTML = clients.map(c => {
  11026. let statusBadge = '';
  11027. if (!c.enabled) {
  11028. 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>';
  11029. } else if (c.status === 'bound') {
  11030. 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>';
  11031. } else if (c.status === 'searching') {
  11032. 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>';
  11033. } else if (c.status === 'stopped') {
  11034. 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>';
  11035. } else {
  11036. 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>`;
  11037. }
  11038. 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>';
  11039. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11040. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11041. 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>';
  11042. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11043. // Option flags
  11044. const flags = [];
  11045. 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>');
  11046. 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>');
  11047. 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>');
  11048. 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>`);
  11049. return `
  11050. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11051. <td class="py-3 px-4">
  11052. <div class="flex items-center gap-2">
  11053. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11054. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11055. </div>
  11056. </td>
  11057. <td class="py-3 px-4">${statusBadge}</td>
  11058. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11059. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11060. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11061. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11062. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11063. <td class="py-3 px-4">
  11064. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11065. </td>
  11066. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11067. ${c.enabled ? `
  11068. <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>
  11069. <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>
  11070. <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>
  11071. ` : `
  11072. <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>
  11073. `}
  11074. <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>
  11075. <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>
  11076. </td>
  11077. </tr>
  11078. `;
  11079. }).join('');
  11080. }
  11081. function openDHCPClientModal(clientId = null) {
  11082. const modal = document.getElementById('modal-dhcp-client');
  11083. if (!modal) return;
  11084. const title = document.getElementById('modal-dhcp-title');
  11085. const idInput = document.getElementById('modal-dhcp-id');
  11086. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11087. const distInput = document.getElementById('modal-dhcp-distance');
  11088. const commentInput = document.getElementById('modal-dhcp-comment');
  11089. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11090. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11091. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11092. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11093. // Populate interfaces
  11094. if (ifaceSelect) {
  11095. let opts = '<option value="">Select interface...</option>';
  11096. const allIfaces = state.interfaces || [];
  11097. const allVlans = state.vlans || [];
  11098. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11099. // Group 1: Physical & Bridge Interfaces
  11100. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11101. allIfaces.forEach(i => {
  11102. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11103. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11104. });
  11105. opts += '</optgroup>';
  11106. // Group 2: VLAN Interfaces
  11107. if (allVlans.length > 0) {
  11108. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11109. allVlans.forEach(v => {
  11110. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11111. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11112. });
  11113. opts += '</optgroup>';
  11114. }
  11115. ifaceSelect.innerHTML = opts;
  11116. }
  11117. if (clientId) {
  11118. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11119. if (client) {
  11120. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11121. if (idInput) idInput.value = client.id;
  11122. if (ifaceSelect) {
  11123. ifaceSelect.value = client.interface;
  11124. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11125. }
  11126. if (distInput) distInput.value = client.default_route_distance || 1;
  11127. if (commentInput) commentInput.value = client.comment || '';
  11128. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11129. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11130. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11131. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11132. }
  11133. } else {
  11134. if (title) title.innerText = 'Add DHCP Client';
  11135. if (idInput) idInput.value = '';
  11136. if (ifaceSelect) {
  11137. ifaceSelect.value = '';
  11138. ifaceSelect.disabled = false;
  11139. }
  11140. if (distInput) distInput.value = 1;
  11141. if (commentInput) commentInput.value = '';
  11142. if (defRouteCheck) defRouteCheck.checked = true;
  11143. if (peerDnsCheck) peerDnsCheck.checked = true;
  11144. if (peerNtpCheck) peerNtpCheck.checked = true;
  11145. if (enabledCheck) enabledCheck.checked = true;
  11146. }
  11147. modal.classList.remove('hidden');
  11148. }
  11149. function openDHCPClientModalForIface(ifaceName) {
  11150. openDHCPClientModal();
  11151. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11152. if (ifaceSelect && ifaceName) {
  11153. ifaceSelect.value = ifaceName;
  11154. }
  11155. }
  11156. function closeDHCPClientModal() {
  11157. const modal = document.getElementById('modal-dhcp-client');
  11158. if (modal) modal.classList.add('hidden');
  11159. }
  11160. async function submitSaveDHCPClient(e) {
  11161. if (e) e.preventDefault();
  11162. const id = document.getElementById('modal-dhcp-id')?.value;
  11163. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11164. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11165. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11166. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11167. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11168. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11169. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11170. if (!id && !iface) {
  11171. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11172. return;
  11173. }
  11174. try {
  11175. let res;
  11176. if (id) {
  11177. // PUT update
  11178. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11179. method: 'PUT',
  11180. headers: { 'Content-Type': 'application/json' },
  11181. body: JSON.stringify({
  11182. enabled,
  11183. add_default_route: defRoute,
  11184. default_route_distance: distance,
  11185. use_peer_dns: peerDns,
  11186. use_peer_ntp: peerNtp,
  11187. comment
  11188. })
  11189. });
  11190. } else {
  11191. // POST create
  11192. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11193. method: 'POST',
  11194. headers: { 'Content-Type': 'application/json' },
  11195. body: JSON.stringify({
  11196. interface: iface,
  11197. enabled,
  11198. add_default_route: defRoute,
  11199. default_route_distance: distance,
  11200. use_peer_dns: peerDns,
  11201. use_peer_ntp: peerNtp,
  11202. comment
  11203. })
  11204. });
  11205. }
  11206. const data = await res.json();
  11207. if (!res.ok) {
  11208. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11209. return;
  11210. }
  11211. closeDHCPClientModal();
  11212. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11213. await loadDHCPClients();
  11214. fetchData(); // refresh interfaces list with new lease/status
  11215. } catch (err) {
  11216. showToast('Error', err.message, 'error');
  11217. }
  11218. }
  11219. async function toggleDHCPClientState(id, enabled) {
  11220. try {
  11221. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11222. method: 'POST',
  11223. headers: { 'Content-Type': 'application/json' },
  11224. body: JSON.stringify({ enabled })
  11225. });
  11226. const data = await res.json();
  11227. if (!res.ok) {
  11228. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11229. return;
  11230. }
  11231. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11232. await loadDHCPClients();
  11233. fetchData();
  11234. } catch (err) {
  11235. showToast('Error', err.message, 'error');
  11236. }
  11237. }
  11238. async function renewDHCPClient(id) {
  11239. try {
  11240. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11241. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11242. method: 'POST'
  11243. });
  11244. const data = await res.json();
  11245. if (!res.ok) {
  11246. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11247. return;
  11248. }
  11249. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11250. setTimeout(() => {
  11251. loadDHCPClients();
  11252. fetchData();
  11253. }, 1500);
  11254. } catch (err) {
  11255. showToast('Error', err.message, 'error');
  11256. }
  11257. }
  11258. async function releaseDHCPClient(id) {
  11259. try {
  11260. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11261. method: 'POST'
  11262. });
  11263. const data = await res.json();
  11264. if (!res.ok) {
  11265. showToast('Error', data.error || 'Failed to release lease', 'error');
  11266. return;
  11267. }
  11268. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11269. await loadDHCPClients();
  11270. fetchData();
  11271. } catch (err) {
  11272. showToast('Error', err.message, 'error');
  11273. }
  11274. }
  11275. async function deleteDHCPClient(id, ifaceName) {
  11276. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11277. return;
  11278. }
  11279. try {
  11280. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11281. method: 'DELETE'
  11282. });
  11283. const data = await res.json();
  11284. if (!res.ok) {
  11285. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11286. return;
  11287. }
  11288. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11289. await loadDHCPClients();
  11290. fetchData();
  11291. } catch (err) {
  11292. showToast('Error', err.message, 'error');
  11293. }
  11294. }
  11295. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11296. async function loadDHCPServer(populate = true) {
  11297. try {
  11298. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11299. fetch(`${API_BASE}/dhcp-server/summary`),
  11300. fetch(`${API_BASE}/dhcp-server/servers`),
  11301. fetch(`${API_BASE}/dhcp-server/networks`),
  11302. fetch(`${API_BASE}/dhcp-server/leases`),
  11303. fetch(`${API_BASE}/dhcp-server/options`)
  11304. ]);
  11305. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11306. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11307. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11308. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11309. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11310. const sum = state.dhcpServerSummary || {};
  11311. const srvs = state.dhcpServers || [];
  11312. const nets = state.dhcpNetworks || [];
  11313. const leases = state.dhcpLeases || [];
  11314. const opts = state.dhcpOptions || [];
  11315. // KPI Cards
  11316. const statActive = document.getElementById('dhcp-server-stat-active');
  11317. if (statActive) {
  11318. const activeCount = srvs.filter(s => s.running).length;
  11319. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11320. }
  11321. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11322. if (statLeases) {
  11323. statLeases.innerText = leases.length;
  11324. }
  11325. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11326. if (statLeasesSub) {
  11327. const dyn = leases.filter(l => l.dynamic).length;
  11328. const st = leases.filter(l => !l.dynamic).length;
  11329. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11330. }
  11331. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11332. if (statNetworks) {
  11333. statNetworks.innerText = nets.length;
  11334. }
  11335. // Subtab Badges
  11336. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11337. if (bSrv) bSrv.innerText = srvs.length;
  11338. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11339. if (bNet) bNet.innerText = nets.length;
  11340. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11341. if (bLease) bLease.innerText = leases.length;
  11342. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11343. if (bOpt) bOpt.innerText = opts.length;
  11344. // Sidebar Badge
  11345. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11346. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11347. renderCurrentDHCPServerTab();
  11348. } catch (err) {
  11349. console.error('Failed to load DHCP Server:', err);
  11350. }
  11351. }
  11352. function switchDHCPServerTab(tab) {
  11353. state.dhcpServerTab = tab;
  11354. const tabs = ['servers', 'networks', 'leases', 'options'];
  11355. tabs.forEach(t => {
  11356. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11357. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11358. if (panel) {
  11359. if (t === tab) panel.classList.remove('hidden');
  11360. else panel.classList.add('hidden');
  11361. }
  11362. if (btn) {
  11363. if (t === tab) {
  11364. 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';
  11365. } else {
  11366. 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';
  11367. }
  11368. }
  11369. });
  11370. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11371. if (addBtn) {
  11372. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11373. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11374. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11375. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11376. }
  11377. renderCurrentDHCPServerTab();
  11378. }
  11379. function handleDHCPServerPrimaryAdd() {
  11380. const tab = state.dhcpServerTab || 'servers';
  11381. if (tab === 'servers') openAddDHCPServerModal();
  11382. else if (tab === 'networks') openAddDHCPNetworkModal();
  11383. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11384. else if (tab === 'options') openAddDHCPOptionModal();
  11385. }
  11386. function renderCurrentDHCPServerTab() {
  11387. const tab = state.dhcpServerTab || 'servers';
  11388. if (tab === 'servers') renderDHCPServers();
  11389. else if (tab === 'networks') renderDHCPNetworks();
  11390. else if (tab === 'leases') renderDHCPLeases();
  11391. else if (tab === 'options') renderDHCPOptions();
  11392. }
  11393. function renderDHCPServers() {
  11394. const tbody = document.getElementById('dhcp-server-tbody');
  11395. const empty = document.getElementById('dhcp-server-empty');
  11396. if (!tbody) return;
  11397. tbody.innerHTML = '';
  11398. const servers = state.dhcpServers || [];
  11399. if (servers.length === 0) {
  11400. empty?.classList.remove('hidden');
  11401. return;
  11402. }
  11403. empty?.classList.add('hidden');
  11404. servers.forEach(s => {
  11405. const tr = document.createElement('tr');
  11406. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11407. tr.innerHTML = `
  11408. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11409. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11410. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11411. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  11412. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11413. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11414. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  11415. <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">${s.active_leases || 0}</span></td>
  11416. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11417. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11418. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  11419. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11420. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11421. </td>
  11422. `;
  11423. tbody.appendChild(tr);
  11424. });
  11425. }
  11426. function renderDHCPNetworks() {
  11427. const tbody = document.getElementById('dhcp-networks-tbody');
  11428. const empty = document.getElementById('dhcp-networks-empty');
  11429. if (!tbody) return;
  11430. tbody.innerHTML = '';
  11431. const networks = state.dhcpNetworks || [];
  11432. if (networks.length === 0) {
  11433. empty?.classList.remove('hidden');
  11434. return;
  11435. }
  11436. empty?.classList.add('hidden');
  11437. networks.forEach(n => {
  11438. const tr = document.createElement('tr');
  11439. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11440. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11441. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11442. tr.innerHTML = `
  11443. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11444. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11445. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11446. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11447. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11448. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11449. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11450. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11451. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11452. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11453. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11454. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11455. </td>
  11456. `;
  11457. tbody.appendChild(tr);
  11458. });
  11459. }
  11460. function renderDHCPLeases() {
  11461. const tbody = document.getElementById('dhcp-leases-tbody');
  11462. const empty = document.getElementById('dhcp-leases-empty');
  11463. if (!tbody) return;
  11464. tbody.innerHTML = '';
  11465. const leases = state.dhcpLeases || [];
  11466. if (leases.length === 0) {
  11467. empty?.classList.remove('hidden');
  11468. return;
  11469. }
  11470. empty?.classList.add('hidden');
  11471. leases.forEach(l => {
  11472. const tr = document.createElement('tr');
  11473. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11474. const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
  11475. const statusBadge = l.status === 'bound'
  11476. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
  11477. : l.status === 'static'
  11478. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
  11479. : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
  11480. const makeStaticBtn = l.dynamic
  11481. ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
  11482. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11483. tr.innerHTML = `
  11484. <td class="py-2.5 px-3 text-center">${flag}</td>
  11485. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11486. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11487. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11488. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11489. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11490. <td class="py-2.5 px-3">${statusBadge}</td>
  11491. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11492. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11493. ${makeStaticBtn}
  11494. </td>
  11495. `;
  11496. tbody.appendChild(tr);
  11497. });
  11498. }
  11499. function renderDHCPOptions() {
  11500. const tbody = document.getElementById('dhcp-options-tbody');
  11501. const empty = document.getElementById('dhcp-options-empty');
  11502. if (!tbody) return;
  11503. tbody.innerHTML = '';
  11504. const options = state.dhcpOptions || [];
  11505. if (options.length === 0) {
  11506. empty?.classList.remove('hidden');
  11507. return;
  11508. }
  11509. empty?.classList.add('hidden');
  11510. options.forEach(o => {
  11511. const tr = document.createElement('tr');
  11512. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11513. tr.innerHTML = `
  11514. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11515. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11516. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11517. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11518. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11519. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11520. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11521. </td>
  11522. `;
  11523. tbody.appendChild(tr);
  11524. });
  11525. }
  11526. // ==================== MODALS & ACTIONS: SERVER ====================
  11527. function populateDHCPNetworkSelect(elemId, selectedVal) {
  11528. const sel = document.getElementById(elemId);
  11529. if (!sel) return;
  11530. sel.innerHTML = '<option value="">Select network subnet...</option>';
  11531. const networks = state.dhcpNetworks || [];
  11532. networks.forEach(n => {
  11533. const opt = document.createElement('option');
  11534. opt.value = n.address;
  11535. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  11536. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  11537. opt.selected = true;
  11538. }
  11539. sel.appendChild(opt);
  11540. });
  11541. }
  11542. function onDHCPServerNetworkChange() {
  11543. const netSel = document.getElementById('dhcp-server-modal-network');
  11544. if (!netSel) return;
  11545. const netVal = netSel.value;
  11546. if (!netVal) return;
  11547. const poolInput = document.getElementById('dhcp-server-modal-pool');
  11548. if (!poolInput) return;
  11549. // Auto-calculate suggested address pool based on subnet CIDR
  11550. const parts = netVal.split('/');
  11551. const ip = parts[0];
  11552. const cidr = parseInt(parts[1] || '24', 10);
  11553. if (cidr === 24) {
  11554. const octets = ip.split('.');
  11555. if (octets.length === 4) {
  11556. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  11557. poolInput.value = `${base}.10-${base}.254`;
  11558. }
  11559. }
  11560. }
  11561. function openAddDHCPServerModal() {
  11562. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11563. document.getElementById('dhcp-server-modal-id').value = '';
  11564. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11565. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11566. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11567. document.getElementById('dhcp-server-modal-comment').value = '';
  11568. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11569. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11570. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11571. const networks = state.dhcpNetworks || [];
  11572. const defaultNet = networks.length > 0 ? networks[0].address : '';
  11573. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  11574. if (defaultNet) {
  11575. onDHCPServerNetworkChange();
  11576. }
  11577. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11578. }
  11579. function openEditDHCPServerModal(id) {
  11580. const s = (state.dhcpServers || []).find(item => item.id === id);
  11581. if (!s) return;
  11582. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11583. document.getElementById('dhcp-server-modal-id').value = s.id;
  11584. document.getElementById('dhcp-server-modal-name').value = s.name;
  11585. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11586. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11587. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11588. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11589. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11590. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11591. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  11592. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11593. }
  11594. function closeDHCPServerModal() {
  11595. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11596. }
  11597. async function submitSaveDHCPServer(e) {
  11598. e.preventDefault();
  11599. const id = document.getElementById('dhcp-server-modal-id').value;
  11600. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11601. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11602. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  11603. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11604. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11605. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11606. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11607. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11608. try {
  11609. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11610. method: 'POST',
  11611. headers: { 'Content-Type': 'application/json' },
  11612. body: JSON.stringify({
  11613. id,
  11614. name,
  11615. interface: iface,
  11616. network,
  11617. address_pool: pool,
  11618. lease_time: leaseTime,
  11619. authoritative,
  11620. disabled,
  11621. comment
  11622. })
  11623. });
  11624. if (res.ok) {
  11625. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11626. closeDHCPServerModal();
  11627. loadDHCPServer(false);
  11628. fetchData(false);
  11629. } else {
  11630. const err = await res.text();
  11631. showToast('Error', err, 'error');
  11632. }
  11633. } catch (err) {
  11634. showToast('Error', err.message, 'error');
  11635. }
  11636. }
  11637. async function toggleDHCPServerState(id, disabled) {
  11638. try {
  11639. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11640. method: 'POST',
  11641. headers: { 'Content-Type': 'application/json' },
  11642. body: JSON.stringify({ disabled })
  11643. });
  11644. if (res.ok) {
  11645. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11646. loadDHCPServer(false);
  11647. fetchData(false);
  11648. }
  11649. } catch (err) {
  11650. showToast('Error', err.message, 'error');
  11651. }
  11652. }
  11653. async function deleteDHCPServer(id, name) {
  11654. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11655. try {
  11656. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11657. if (res.ok) {
  11658. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11659. loadDHCPServer(false);
  11660. fetchData(false);
  11661. }
  11662. } catch (err) {
  11663. showToast('Error', err.message, 'error');
  11664. }
  11665. }
  11666. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11667. function openAddDHCPNetworkModal() {
  11668. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11669. document.getElementById('dhcp-network-modal-id').value = '';
  11670. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11671. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11672. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11673. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  11674. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  11675. document.getElementById('dhcp-network-modal-tftp').value = '';
  11676. document.getElementById('dhcp-network-modal-bootfile').value = '';
  11677. document.getElementById('dhcp-network-modal-wins').value = '';
  11678. document.getElementById('dhcp-network-modal-netmask').value = '';
  11679. document.getElementById('dhcp-network-modal-comment').value = '';
  11680. renderDHCPNetworkOptionsCheckboxes([]);
  11681. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11682. }
  11683. function openEditDHCPNetworkModal(id) {
  11684. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  11685. if (!n) return;
  11686. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  11687. document.getElementById('dhcp-network-modal-id').value = n.id;
  11688. document.getElementById('dhcp-network-modal-address').value = n.address;
  11689. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  11690. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  11691. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  11692. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  11693. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  11694. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  11695. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  11696. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  11697. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  11698. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  11699. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11700. }
  11701. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  11702. const container = document.getElementById('dhcp-network-modal-options-list');
  11703. if (!container) return;
  11704. container.innerHTML = '';
  11705. const opts = state.dhcpOptions || [];
  11706. if (opts.length === 0) {
  11707. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  11708. return;
  11709. }
  11710. opts.forEach(o => {
  11711. const isChecked = selectedIds.includes(o.id);
  11712. const label = document.createElement('label');
  11713. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  11714. label.innerHTML = `
  11715. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  11716. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  11717. `;
  11718. container.appendChild(label);
  11719. });
  11720. }
  11721. function closeDHCPNetworkModal() {
  11722. document.getElementById('dhcp-network-modal').classList.add('hidden');
  11723. }
  11724. async function submitSaveDHCPNetwork(e) {
  11725. e.preventDefault();
  11726. const id = document.getElementById('dhcp-network-modal-id').value;
  11727. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  11728. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  11729. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  11730. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  11731. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  11732. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  11733. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  11734. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  11735. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  11736. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  11737. const selectedOpts = [];
  11738. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  11739. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11740. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11741. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11742. try {
  11743. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  11744. method: 'POST',
  11745. headers: { 'Content-Type': 'application/json' },
  11746. body: JSON.stringify({
  11747. id,
  11748. address,
  11749. gateway,
  11750. netmask,
  11751. dns_servers: dnsServers,
  11752. domain,
  11753. ntp_servers: ntpServers,
  11754. next_server: tftp,
  11755. boot_file_name: bootfile,
  11756. wins_servers: winsServers,
  11757. dhcp_options: selectedOpts,
  11758. comment
  11759. })
  11760. });
  11761. if (res.ok) {
  11762. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  11763. closeDHCPNetworkModal();
  11764. loadDHCPServer(false);
  11765. fetchData(false);
  11766. } else {
  11767. const err = await res.text();
  11768. showToast('Error', err, 'error');
  11769. }
  11770. } catch (err) {
  11771. showToast('Error', err.message, 'error');
  11772. }
  11773. }
  11774. async function deleteDHCPNetwork(id, addr) {
  11775. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  11776. try {
  11777. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11778. if (res.ok) {
  11779. showToast('Deleted', `Network ${addr} removed`, 'success');
  11780. loadDHCPServer(false);
  11781. fetchData(false);
  11782. }
  11783. } catch (err) {
  11784. showToast('Error', err.message, 'error');
  11785. }
  11786. }
  11787. // ==================== MODALS & ACTIONS: LEASES ====================
  11788. function openAddDHCPStaticLeaseModal() {
  11789. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  11790. document.getElementById('dhcp-static-lease-modal-id').value = '';
  11791. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  11792. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  11793. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  11794. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  11795. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  11796. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  11797. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  11798. }
  11799. function closeDHCPStaticLeaseModal() {
  11800. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  11801. }
  11802. async function submitSaveDHCPStaticLease(e) {
  11803. e.preventDefault();
  11804. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  11805. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  11806. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  11807. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  11808. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  11809. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  11810. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  11811. try {
  11812. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  11813. method: 'POST',
  11814. headers: { 'Content-Type': 'application/json' },
  11815. body: JSON.stringify({
  11816. id,
  11817. mac_address: mac,
  11818. address: ip,
  11819. hostname,
  11820. server,
  11821. comment,
  11822. disabled
  11823. })
  11824. });
  11825. if (res.ok) {
  11826. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  11827. closeDHCPStaticLeaseModal();
  11828. loadDHCPServer(false);
  11829. fetchData(false);
  11830. } else {
  11831. const err = await res.text();
  11832. showToast('Error', err, 'error');
  11833. }
  11834. } catch (err) {
  11835. showToast('Error', err.message, 'error');
  11836. }
  11837. }
  11838. async function deleteDHCPStaticLease(id) {
  11839. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  11840. try {
  11841. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11842. if (res.ok) {
  11843. showToast('Deleted', 'Static lease removed', 'success');
  11844. loadDHCPServer(false);
  11845. fetchData(false);
  11846. }
  11847. } catch (err) {
  11848. showToast('Error', err.message, 'error');
  11849. }
  11850. }
  11851. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  11852. try {
  11853. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  11854. method: 'POST',
  11855. headers: { 'Content-Type': 'application/json' },
  11856. body: JSON.stringify({
  11857. mac_address: mac,
  11858. address: ip,
  11859. hostname,
  11860. comment: comment || 'Converted to static'
  11861. })
  11862. });
  11863. if (res.ok) {
  11864. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  11865. loadDHCPServer(false);
  11866. fetchData(false);
  11867. } else {
  11868. const err = await res.text();
  11869. showToast('Error', err, 'error');
  11870. }
  11871. } catch (err) {
  11872. showToast('Error', err.message, 'error');
  11873. }
  11874. }
  11875. // ==================== MODALS & ACTIONS: OPTIONS ====================
  11876. function openAddDHCPOptionModal() {
  11877. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  11878. document.getElementById('dhcp-option-modal-id').value = '';
  11879. document.getElementById('dhcp-option-modal-name').value = '';
  11880. document.getElementById('dhcp-option-modal-code').value = '';
  11881. document.getElementById('dhcp-option-modal-value').value = '';
  11882. document.getElementById('dhcp-option-modal-comment').value = '';
  11883. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11884. }
  11885. function openEditDHCPOptionModal(id) {
  11886. const o = (state.dhcpOptions || []).find(item => item.id === id);
  11887. if (!o) return;
  11888. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  11889. document.getElementById('dhcp-option-modal-id').value = o.id;
  11890. document.getElementById('dhcp-option-modal-name').value = o.name;
  11891. document.getElementById('dhcp-option-modal-code').value = o.code;
  11892. document.getElementById('dhcp-option-modal-value').value = o.value;
  11893. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  11894. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11895. }
  11896. function closeDHCPOptionModal() {
  11897. document.getElementById('dhcp-option-modal').classList.add('hidden');
  11898. }
  11899. async function submitSaveDHCPOption(e) {
  11900. e.preventDefault();
  11901. const id = document.getElementById('dhcp-option-modal-id').value;
  11902. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  11903. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  11904. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  11905. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  11906. try {
  11907. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  11908. method: 'POST',
  11909. headers: { 'Content-Type': 'application/json' },
  11910. body: JSON.stringify({ id, name, code, value, comment })
  11911. });
  11912. if (res.ok) {
  11913. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  11914. closeDHCPOptionModal();
  11915. loadDHCPServer(false);
  11916. fetchData(false);
  11917. } else {
  11918. const err = await res.text();
  11919. showToast('Error', err, 'error');
  11920. }
  11921. } catch (err) {
  11922. showToast('Error', err.message, 'error');
  11923. }
  11924. }
  11925. async function deleteDHCPOption(id, name) {
  11926. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  11927. try {
  11928. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11929. if (res.ok) {
  11930. showToast('Deleted', `Option ${name} removed`, 'success');
  11931. loadDHCPServer(false);
  11932. fetchData(false);
  11933. }
  11934. } catch (err) {
  11935. showToast('Error', err.message, 'error');
  11936. }
  11937. }
  11938. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  11939. function openDHCPServerSetupModal() {
  11940. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  11941. onDHCPWizardIfaceChange();
  11942. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  11943. }
  11944. function closeDHCPServerSetupModal() {
  11945. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  11946. }
  11947. function onDHCPWizardIfaceChange() {
  11948. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  11949. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  11950. let ip = '192.168.88.1';
  11951. let prefix = '24';
  11952. if (iface && iface.ip_address) {
  11953. const parts = iface.ip_address.split('/');
  11954. ip = parts[0];
  11955. if (parts.length > 1) prefix = parts[1];
  11956. }
  11957. // Calculate subnet base (e.g. 192.168.88.0/24)
  11958. const ipParts = ip.split('.');
  11959. if (ipParts.length === 4) {
  11960. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  11961. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  11962. document.getElementById('dhcp-wizard-space').value = baseSpace;
  11963. document.getElementById('dhcp-wizard-gateway').value = ip;
  11964. document.getElementById('dhcp-wizard-pool').value = pool;
  11965. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  11966. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  11967. }
  11968. }
  11969. async function submitDHCPServerSetupWizard(e) {
  11970. e.preventDefault();
  11971. const iface = document.getElementById('dhcp-wizard-iface').value;
  11972. const space = document.getElementById('dhcp-wizard-space').value.trim();
  11973. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  11974. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  11975. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  11976. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  11977. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  11978. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  11979. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11980. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11981. try {
  11982. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  11983. method: 'POST',
  11984. headers: { 'Content-Type': 'application/json' },
  11985. body: JSON.stringify({
  11986. interface: iface,
  11987. address_space: space,
  11988. gateway: gw,
  11989. address_pool: pool,
  11990. dns_servers: dnsServers,
  11991. lease_time: leaseTime,
  11992. ntp_servers: ntpServers,
  11993. next_server: tftp
  11994. })
  11995. });
  11996. if (res.ok) {
  11997. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  11998. closeDHCPServerSetupModal();
  11999. loadDHCPServer(false);
  12000. fetchData(false);
  12001. } else {
  12002. const err = await res.text();
  12003. showToast('Error', err, 'error');
  12004. }
  12005. } catch (err) {
  12006. showToast('Error', err.message, 'error');
  12007. }
  12008. }
  12009. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12010. const sel = document.getElementById(elemId);
  12011. if (!sel) return;
  12012. sel.innerHTML = '<option value="">Select interface...</option>';
  12013. const ifaces = state.interfaces || [];
  12014. ifaces.forEach(i => {
  12015. if (i.name === 'lo') return;
  12016. const opt = document.createElement('option');
  12017. opt.value = i.name;
  12018. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12019. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12020. if (i.name === selectedVal) opt.selected = true;
  12021. sel.appendChild(opt);
  12022. });
  12023. }
  12024. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12025. function initTableSorting() {
  12026. document.querySelectorAll('table').forEach(setupSortableTable);
  12027. }
  12028. function setupSortableTable(table) {
  12029. const thead = table.querySelector('thead');
  12030. const tbody = table.querySelector('tbody');
  12031. if (!thead || !tbody) return;
  12032. const headerRows = thead.querySelectorAll('tr');
  12033. if (headerRows.length === 0) return;
  12034. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12035. ths.forEach((th, colIdx) => {
  12036. if (th._sortBound) return;
  12037. th._sortBound = true;
  12038. const rawText = th.innerText.trim().toLowerCase();
  12039. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12040. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12041. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12042. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12043. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12044. return;
  12045. }
  12046. th.classList.add('table-sortable', 'group');
  12047. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12048. let icon = th.querySelector('.table-sort-icon');
  12049. if (!icon) {
  12050. icon = document.createElement('span');
  12051. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12052. icon.innerHTML = '⇅';
  12053. th.appendChild(icon);
  12054. }
  12055. th.addEventListener('click', (e) => {
  12056. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12057. handleHeaderClick(table, th, colIdx);
  12058. });
  12059. });
  12060. if (!tbody._sortObserved) {
  12061. tbody._sortObserved = true;
  12062. let sortDebounceTimer = null;
  12063. const observer = new MutationObserver((mutations) => {
  12064. if (tbody._isSorting) return;
  12065. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12066. if (!hasChildChanges) return;
  12067. clearTimeout(sortDebounceTimer);
  12068. sortDebounceTimer = setTimeout(() => {
  12069. if (tbody._isSorting) return;
  12070. if (table._activeSort && table._activeSort.dir !== 'none') {
  12071. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12072. } else {
  12073. tagOriginalRowOrder(tbody);
  12074. }
  12075. }, 10);
  12076. });
  12077. observer.observe(tbody, { childList: true });
  12078. }
  12079. tagOriginalRowOrder(tbody);
  12080. }
  12081. function tagOriginalRowOrder(tbody) {
  12082. let idx = 0;
  12083. Array.from(tbody.children).forEach(tr => {
  12084. if (!tr.querySelector('td[colspan]')) {
  12085. if (!tr.hasAttribute('data-orig-idx')) {
  12086. tr.setAttribute('data-orig-idx', idx++);
  12087. }
  12088. }
  12089. });
  12090. }
  12091. function handleHeaderClick(table, th, colIdx) {
  12092. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12093. let newDir = 'asc';
  12094. if (currentSort.colIdx === colIdx) {
  12095. if (currentSort.dir === 'asc') newDir = 'desc';
  12096. else if (currentSort.dir === 'desc') newDir = 'none';
  12097. else newDir = 'asc';
  12098. } else {
  12099. newDir = 'asc';
  12100. }
  12101. table._activeSort = { colIdx, dir: newDir };
  12102. updateHeaderIcons(table, colIdx, newDir);
  12103. applyTableSort(table, colIdx, newDir, true);
  12104. }
  12105. function updateHeaderIcons(table, activeColIdx, dir) {
  12106. const thead = table.querySelector('thead');
  12107. if (!thead) return;
  12108. const ths = thead.querySelectorAll('th');
  12109. ths.forEach((th, idx) => {
  12110. const icon = th.querySelector('.table-sort-icon');
  12111. if (!icon) return;
  12112. if (idx === activeColIdx && dir !== 'none') {
  12113. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12114. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12115. th.classList.add('table-sorted-active');
  12116. } else {
  12117. icon.innerHTML = '⇅';
  12118. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12119. th.classList.remove('table-sorted-active');
  12120. }
  12121. });
  12122. }
  12123. function applyTableSort(table, colIdx, dir, userInitiated) {
  12124. const tbody = table.querySelector('tbody');
  12125. if (!tbody || tbody.children.length <= 1) return;
  12126. tbody._isSorting = true;
  12127. tagOriginalRowOrder(tbody);
  12128. // Group parent rows and any attached drawer/sub-rows
  12129. const groups = [];
  12130. let currentGroup = null;
  12131. Array.from(tbody.children).forEach(tr => {
  12132. if (tr.querySelector('td[colspan]')) {
  12133. if (currentGroup) {
  12134. currentGroup.subRows.push(tr);
  12135. } else {
  12136. groups.push({ mainRow: tr, subRows: [] });
  12137. }
  12138. } else {
  12139. currentGroup = { mainRow: tr, subRows: [] };
  12140. groups.push(currentGroup);
  12141. }
  12142. });
  12143. if (dir === 'none') {
  12144. groups.sort((a, b) => {
  12145. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12146. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12147. return idxA - idxB;
  12148. });
  12149. } else {
  12150. groups.sort((a, b) => {
  12151. const cellA = a.mainRow.children[colIdx];
  12152. const cellB = b.mainRow.children[colIdx];
  12153. const res = compareTableCells(cellA, cellB);
  12154. return dir === 'asc' ? res : -res;
  12155. });
  12156. }
  12157. // Re-append rows in sorted order
  12158. groups.forEach(g => {
  12159. tbody.appendChild(g.mainRow);
  12160. g.subRows.forEach(sub => tbody.appendChild(sub));
  12161. });
  12162. tbody._isSorting = false;
  12163. }
  12164. function getCellRawText(cell) {
  12165. if (!cell) return '';
  12166. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12167. const input = cell.querySelector('input, select');
  12168. if (input) {
  12169. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12170. return input.value;
  12171. }
  12172. return cell.innerText.trim();
  12173. }
  12174. function parseTrafficToNumber(str) {
  12175. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12176. if (!m) return null;
  12177. const num = parseFloat(m[1].replace(/,/g, ''));
  12178. if (isNaN(num)) return null;
  12179. const unit = m[2].toUpperCase();
  12180. let mult = 1;
  12181. if (unit.startsWith('K')) mult = 1024;
  12182. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12183. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12184. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12185. return num * mult;
  12186. }
  12187. function parseIpToNumber(str) {
  12188. const clean = str.replace(/^[!~]/, '').trim();
  12189. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12190. if (!m) return null;
  12191. const o1 = parseInt(m[1], 10);
  12192. const o2 = parseInt(m[2], 10);
  12193. const o3 = parseInt(m[3], 10);
  12194. const o4 = parseInt(m[4], 10);
  12195. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12196. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12197. }
  12198. function parseCompoundPackets(str) {
  12199. const m = str.match(/^([\d,]+)p/);
  12200. if (!m) return null;
  12201. return parseInt(m[1].replace(/,/g, ''), 10);
  12202. }
  12203. function compareTableCells(cellA, cellB) {
  12204. const a = getCellRawText(cellA);
  12205. const b = getCellRawText(cellB);
  12206. if (a === '' && b !== '') return 1;
  12207. if (b === '' && a !== '') return -1;
  12208. if (a === b) return 0;
  12209. // 1. IP Addresses / CIDR
  12210. const ipA = parseIpToNumber(a);
  12211. const ipB = parseIpToNumber(b);
  12212. if (ipA !== null && ipB !== null) return ipA - ipB;
  12213. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12214. const pktA = parseCompoundPackets(a);
  12215. const pktB = parseCompoundPackets(b);
  12216. if (pktA !== null && pktB !== null) return pktA - pktB;
  12217. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12218. const trafA = parseTrafficToNumber(a);
  12219. const trafB = parseTrafficToNumber(b);
  12220. if (trafA !== null && trafB !== null) return trafA - trafB;
  12221. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12222. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12223. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12224. const numA = Number(cleanNumA);
  12225. const numB = Number(cleanNumB);
  12226. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12227. return numA - numB;
  12228. }
  12229. // 5. Natural case-insensitive string compare
  12230. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12231. }
  12232. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12233. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12234. const docTableObserver = new MutationObserver((mutations) => {
  12235. let needsInit = false;
  12236. for (const m of mutations) {
  12237. for (const node of m.addedNodes) {
  12238. if (node.nodeType === 1) {
  12239. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12240. needsInit = true;
  12241. break;
  12242. }
  12243. }
  12244. }
  12245. if (needsInit) break;
  12246. }
  12247. if (needsInit) {
  12248. initTableSorting();
  12249. }
  12250. });
  12251. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12252. }