app.js 661 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707
  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. initLiveTrafficStream();
  80. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  81. setInterval(() => {
  82. if (state.isPolling) {
  83. fetchData(false);
  84. }
  85. }, 5000);
  86. });
  87. let trafficEventSource = null;
  88. let trafficPollFallback = null;
  89. function initLiveTrafficStream() {
  90. if (trafficEventSource) {
  91. try { trafficEventSource.close(); } catch(e) {}
  92. trafficEventSource = null;
  93. }
  94. if (trafficPollFallback) {
  95. clearInterval(trafficPollFallback);
  96. trafficPollFallback = null;
  97. }
  98. if (window.EventSource) {
  99. try {
  100. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  101. trafficEventSource.onmessage = (event) => {
  102. try {
  103. const data = JSON.parse(event.data);
  104. updateLiveInterfaceTraffic(data);
  105. } catch (e) {
  106. console.error('Error parsing live traffic event:', e);
  107. }
  108. };
  109. trafficEventSource.onerror = () => {
  110. // Fallback polling if SSE disconnects
  111. if (!trafficPollFallback) {
  112. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  113. }
  114. };
  115. trafficEventSource.onopen = () => {
  116. if (trafficPollFallback) {
  117. clearInterval(trafficPollFallback);
  118. trafficPollFallback = null;
  119. }
  120. };
  121. return;
  122. } catch (e) {
  123. console.warn('EventSource failed, using 1s polling fallback:', e);
  124. }
  125. }
  126. // Fallback if EventSource is unavailable
  127. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  128. }
  129. async function pollLiveTrafficSnapshot() {
  130. try {
  131. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  132. if (res.ok) {
  133. const data = await res.json();
  134. updateLiveInterfaceTraffic(data);
  135. }
  136. } catch (e) {}
  137. }
  138. function updateLiveInterfaceTraffic(data) {
  139. if (!data || !data.interfaces) return;
  140. state.latestTraffic = data;
  141. // 1. Update Top & Dashboard Total Bandwidth Indicators
  142. const rxHuman = data.total_rx_human || '0 B/s';
  143. const txHuman = data.total_tx_human || '0 B/s';
  144. const statRx = document.getElementById('stat-traffic-rx');
  145. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  146. const statTx = document.getElementById('stat-traffic-tx');
  147. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  148. // 2. Update state.interfaces rates in-memory
  149. if (Array.isArray(state.interfaces)) {
  150. state.interfaces.forEach(i => {
  151. const live = data.interfaces[i.name];
  152. if (live) {
  153. i.rate = {
  154. rx_bytes_sec: live.rx_bytes_sec,
  155. tx_bytes_sec: live.tx_bytes_sec,
  156. rx_human: live.rx_human,
  157. tx_human: live.tx_human
  158. };
  159. i.stats = {
  160. rx_bytes: live.rx_bytes,
  161. tx_bytes: live.tx_bytes,
  162. rx_packets: live.rx_packets,
  163. tx_packets: live.tx_packets,
  164. rx_errors: live.rx_errors,
  165. tx_errors: live.tx_errors,
  166. rx_dropped: live.rx_dropped,
  167. tx_dropped: live.tx_dropped
  168. };
  169. }
  170. });
  171. }
  172. // 3. Update all live UI rate spans in-place (ZERO flicker)
  173. Object.keys(data.interfaces).forEach(name => {
  174. const live = data.interfaces[name];
  175. // Dashboard Port Matrix Card
  176. const cardRate = document.getElementById(`port-card-rate-${name}`);
  177. if (cardRate && cardRate.innerText !== live.rx_human) {
  178. cardRate.innerText = live.rx_human;
  179. }
  180. // Dashboard Quick Interfaces Table
  181. const quickRx = document.getElementById(`quick-rx-${name}`);
  182. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  183. const quickTx = document.getElementById(`quick-tx-${name}`);
  184. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  185. // Main Interfaces Tree Table
  186. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  187. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  188. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  189. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  190. // VLAN Sub-interfaces Table
  191. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  192. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  193. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  194. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  195. // VLAN Page Table
  196. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  197. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  198. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  199. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  200. });
  201. }
  202. // Navigation Handler
  203. function navigate(tabName) {
  204. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  205. navigate('bgp');
  206. return;
  207. }
  208. if (tabName === 'vlans') {
  209. navigate('interfaces');
  210. return;
  211. }
  212. state.activeTab = tabName;
  213. window.location.hash = tabName;
  214. // Update nav links styling
  215. document.querySelectorAll('.nav-link').forEach(link => {
  216. 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';
  217. });
  218. const activeNav = document.getElementById(`nav-${tabName}`);
  219. if (activeNav) {
  220. 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';
  221. }
  222. // Update page headers
  223. const titles = {
  224. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  225. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  226. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  227. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  228. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  229. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  230. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  231. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  232. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  233. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  234. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  235. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  236. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  237. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  238. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  239. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  240. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  241. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  242. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  243. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  244. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  245. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  246. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  247. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  248. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' }
  249. };
  250. const header = titles[tabName] || titles.dashboard;
  251. const pTitle = document.getElementById('page-title');
  252. if (pTitle) pTitle.innerText = header.title;
  253. const pSub = document.getElementById('page-subtitle');
  254. if (pSub) pSub.innerText = header.sub;
  255. // Toggle sections dynamically for all section elements
  256. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  257. if (el.id === `section-${tabName}`) {
  258. el.classList.remove('hidden');
  259. } else {
  260. el.classList.add('hidden');
  261. }
  262. });
  263. if (tabName === 'interfaces') {
  264. loadRoles();
  265. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  266. else switchIfaceSubTab('tree');
  267. }
  268. if (tabName === 'bridge') loadBridge();
  269. if (tabName === 'firewall') loadFirewall();
  270. if (tabName === 'routes') loadRoutes();
  271. if (tabName === 'bgp') {
  272. loadDynamicRouting();
  273. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  274. }
  275. if (tabName === 'ospf') {
  276. loadDynamicRouting();
  277. switchOspfTab(state.activeOspfTab || 'instances');
  278. }
  279. if (tabName === 'routing-filters') loadDynamicRouting();
  280. if (tabName === 'dynamic-routing') loadDynamicRouting();
  281. if (tabName === 'ppp') loadPPP();
  282. if (tabName === 'eoip') loadEoIP();
  283. if (tabName === 'aerotun') loadAeroTUN();
  284. if (tabName === 'persistence') loadDebianConfig();
  285. if (tabName === 'pppoe') loadPPPoE();
  286. if (tabName === 'wireguard') loadWireGuard();
  287. if (tabName === 'ipsec') loadIPSec();
  288. if (tabName === 'l2tp') loadL2TP();
  289. if (tabName === 'pptp') loadPPTP();
  290. if (tabName === 'tools') loadToolsView();
  291. if (tabName === 'dhcp-client') loadDHCPClients();
  292. if (tabName === 'dhcp-server') loadDHCPServer();
  293. if (tabName === 'vrrp') loadVRRP();
  294. if (tabName === 'bwtest') loadBwTestView();
  295. if (tabName === 'settings') loadSettingsData();
  296. setTimeout(initTableSorting, 50);
  297. }
  298. // Fetch all core system, network and VPN telemetry
  299. async function fetchData(isManual = false) {
  300. const spinner = document.getElementById('refresh-spinner');
  301. if (isManual && spinner) spinner.classList.add('animate-spin');
  302. try {
  303. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  304. fetch(`${API_BASE}/system/status`),
  305. fetch(`${API_BASE}/interfaces`),
  306. fetch(`${API_BASE}/vlans`),
  307. fetch(`${API_BASE}/vpn/status`),
  308. fetch(`${API_BASE}/firewall/summary`),
  309. fetch(`${API_BASE}/routing/dynamic/summary`),
  310. fetch(`${API_BASE}/bridge/summary`),
  311. fetch(`${API_BASE}/dhcp/clients/summary`),
  312. fetch(`${API_BASE}/dhcp/clients`),
  313. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  314. fetch(`${API_BASE}/roles`).catch(() => null)
  315. ]);
  316. if (rolesRes && rolesRes.ok) {
  317. state.roles = await rolesRes.json();
  318. const countEl = document.getElementById('badge-roles-count');
  319. if (countEl) countEl.innerText = (state.roles || []).length;
  320. }
  321. if (vrrpSumRes && vrrpSumRes.ok) {
  322. state.vrrpSummary = await vrrpSumRes.json();
  323. renderVRRPSummary();
  324. }
  325. if (dhcpSumRes && dhcpSumRes.ok) {
  326. state.dhcpSummary = await dhcpSumRes.json();
  327. const bDhcp = document.getElementById('badge-dhcp-client-count');
  328. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  329. }
  330. if (dhcpClientsRes && dhcpClientsRes.ok) {
  331. state.dhcpClients = await dhcpClientsRes.json();
  332. }
  333. if (brSummaryRes.ok) {
  334. state.bridgeSummary = await brSummaryRes.json();
  335. const bBridge = document.getElementById('badge-bridge-count');
  336. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  337. const sBr = document.getElementById('bridge-stat-bridges');
  338. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  339. const sPorts = document.getElementById('bridge-stat-ports');
  340. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  341. const sHosts = document.getElementById('bridge-stat-hosts');
  342. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  343. }
  344. if (statusRes.ok) state.systemStatus = await statusRes.json();
  345. if (ifacesRes.ok) {
  346. const ifacesData = await ifacesRes.json();
  347. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  348. state.interfaces = rawIfaces.filter(i => {
  349. if (!i.name) return false;
  350. if (i.name.startsWith('ep_')) return false;
  351. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  352. });
  353. try { populateToolsInterfaces(); } catch (e) {}
  354. }
  355. if (vlansRes.ok) {
  356. const vlansData = await vlansRes.json();
  357. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  358. }
  359. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  360. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  361. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  362. updateSystemMetrics();
  363. updateBadges();
  364. if (state.activeTab === 'dashboard') renderDashboard();
  365. if (state.activeTab === 'interfaces') {
  366. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  367. else renderInterfacesList();
  368. }
  369. if (state.activeTab === 'vlans') renderVlansList();
  370. if (state.activeTab === 'firewall') loadFirewall(false);
  371. if (state.activeTab === 'routes') loadRoutes(false);
  372. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  373. if (state.activeTab === 'ppp') loadPPP(false);
  374. if (state.activeTab === 'eoip') loadEoIP(false);
  375. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  376. if (state.activeTab === 'pppoe') loadPPPoE(false);
  377. if (state.activeTab === 'wireguard') loadWireGuard(false);
  378. if (state.activeTab === 'ipsec') loadIPSec(false);
  379. if (state.activeTab === 'l2tp') loadL2TP(false);
  380. if (state.activeTab === 'pptp') loadPPTP(false);
  381. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  382. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  383. if (state.activeTab === 'vrrp') loadVRRP(false);
  384. if (state.activeTab === 'settings') loadSettingsData(false);
  385. fetchBwTestServerStatus();
  386. } catch (err) {
  387. console.error('Failed to fetch router state:', err);
  388. } finally {
  389. if (isManual && spinner) {
  390. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  391. }
  392. }
  393. }
  394. // Update Top KPI and Sidebar Telemetry
  395. function updateSystemMetrics() {
  396. const s = state.systemStatus;
  397. const v = state.vpnStatus;
  398. if (!s) return;
  399. // Sidebar Host & Uptime
  400. const sideHost = document.getElementById('side-hostname');
  401. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  402. const sideUp = document.getElementById('side-uptime');
  403. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  404. const sideGw = document.getElementById('side-gateway-ip');
  405. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  406. // Compute CPU Metrics
  407. let cpuPct = 0;
  408. if (s.cpu_pct !== undefined) {
  409. cpuPct = s.cpu_pct;
  410. } else if (s.cpu_load && s.cpu_load.length > 0) {
  411. const cores = s.cpu_cores || 1;
  412. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  413. }
  414. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  415. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  416. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  417. // Sidebar CPU
  418. const sideCpuVal = document.getElementById('side-cpu-val');
  419. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  420. const sideCpuBar = document.getElementById('side-cpu-bar');
  421. if (sideCpuBar) {
  422. sideCpuBar.style.width = cpuWidth;
  423. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  424. }
  425. // Dashboard CPU Card
  426. const dashCpuVal = document.getElementById('dash-cpu-val');
  427. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  428. const dashCpuBar = document.getElementById('dash-cpu-bar');
  429. if (dashCpuBar) {
  430. dashCpuBar.style.width = cpuWidth;
  431. if (cpuPct > 85) {
  432. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  433. } else if (cpuPct > 65) {
  434. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  435. } else {
  436. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  437. }
  438. }
  439. const dashCpuCores = document.getElementById('dash-cpu-cores');
  440. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  441. const dashCpuLoad = document.getElementById('dash-cpu-load');
  442. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  443. const dashCpuStatus = document.getElementById('dash-cpu-status');
  444. if (dashCpuStatus) {
  445. if (cpuPct > 85) {
  446. dashCpuStatus.innerText = 'High';
  447. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  448. } else if (cpuPct > 65) {
  449. dashCpuStatus.innerText = 'Heavy';
  450. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  451. } else {
  452. dashCpuStatus.innerText = 'Normal';
  453. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  454. }
  455. }
  456. // Compute RAM Metrics
  457. const memPct = Math.round(s.mem_usage_pct || 0);
  458. const memPctStr = `${memPct}%`;
  459. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  460. const usedMB = s.mem_used_mb || 0;
  461. const totalMB = s.mem_total_mb || 0;
  462. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  463. function fmtMemMB(mb) {
  464. if (mb >= 1024) {
  465. return `${(mb / 1024).toFixed(1)} GB`;
  466. }
  467. return `${mb} MB`;
  468. }
  469. // Sidebar RAM
  470. const sideRamVal = document.getElementById('side-ram-val');
  471. if (sideRamVal) sideRamVal.innerText = memPctStr;
  472. const sideRamBar = document.getElementById('side-ram-bar');
  473. if (sideRamBar) sideRamBar.style.width = memWidth;
  474. // Dashboard RAM Card
  475. const dashRamVal = document.getElementById('dash-ram-val');
  476. if (dashRamVal) dashRamVal.innerText = memPctStr;
  477. const dashRamBar = document.getElementById('dash-ram-bar');
  478. if (dashRamBar) {
  479. dashRamBar.style.width = memWidth;
  480. if (memPct > 85) {
  481. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  482. } else if (memPct > 70) {
  483. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  484. } else {
  485. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  486. }
  487. }
  488. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  489. if (dashRamUsedTotal) {
  490. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  491. }
  492. const dashRamFree = document.getElementById('dash-ram-free');
  493. if (dashRamFree) {
  494. dashRamFree.innerText = fmtMemMB(freeMB);
  495. }
  496. const dashRamStatus = document.getElementById('dash-ram-status');
  497. if (dashRamStatus) {
  498. if (memPct > 85) {
  499. dashRamStatus.innerText = 'High';
  500. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  501. } else {
  502. dashRamStatus.innerText = 'Active';
  503. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  504. }
  505. }
  506. // Legacy Dashboard Stats (Safe checks)
  507. const elIfacesUp = document.getElementById('stat-ifaces-up');
  508. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  509. const elIfacesTot = document.getElementById('stat-ifaces-total');
  510. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  511. const elIfacesDown = document.getElementById('stat-ifaces-down');
  512. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  513. const elVlans = document.getElementById('stat-vlans-count');
  514. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  515. // VPN Status Indicators
  516. if (v) {
  517. const totalActive = v.total_active_tunnels || 0;
  518. const statVpnActive = document.getElementById('stat-vpn-active');
  519. if (statVpnActive) statVpnActive.innerText = totalActive;
  520. const tunnelsDot = document.getElementById('tunnels-dot');
  521. const tunnelsLabel = document.getElementById('tunnels-label');
  522. if (tunnelsDot && tunnelsLabel) {
  523. if (totalActive > 0) {
  524. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  525. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  526. } else {
  527. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  528. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  529. }
  530. }
  531. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  532. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  533. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  534. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  535. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  536. }
  537. // Total Live Bandwidth Rate
  538. let totalRx = 0;
  539. let totalTx = 0;
  540. (state.interfaces || []).forEach(i => {
  541. if (i.rate) {
  542. totalRx += i.rate.rx_bytes_sec || 0;
  543. totalTx += i.rate.tx_bytes_sec || 0;
  544. }
  545. });
  546. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  547. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  548. }
  549. function setDotBadge(id, active) {
  550. const el = document.getElementById(id);
  551. if (!el) return;
  552. if (active) {
  553. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  554. } else {
  555. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  556. }
  557. }
  558. function updateBadges() {
  559. const bIfaces = document.getElementById('badge-ifaces-count');
  560. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  561. const bVlans = document.getElementById('badge-vlans-count');
  562. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  563. if (state.fwSummary) {
  564. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  565. const badgeFw = document.getElementById('badge-firewall-count');
  566. if (badgeFw) badgeFw.innerText = totalFwRules;
  567. }
  568. if (state.vpnStatus) {
  569. const v = state.vpnStatus;
  570. const bEoIP = document.getElementById('badge-eoip-count');
  571. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  572. const bAero = document.getElementById('badge-aerotun-count');
  573. if (bAero) bAero.innerText = v.total_aerotun || 0;
  574. const bPPPSess = document.getElementById('badge-ppp-sessions');
  575. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  576. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  577. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  578. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  579. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  580. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  581. }
  582. if (state.dynSummary) {
  583. const d = state.dynSummary;
  584. setDotBadge('badge-bgp-dot', d.bgp_running);
  585. setDotBadge('badge-ospf-dot', d.ospf_running);
  586. const bBgp = document.getElementById('badge-bgp-count');
  587. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  588. const bOspf = document.getElementById('badge-ospf-count');
  589. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  590. const bFilters = document.getElementById('badge-filters-count');
  591. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  592. }
  593. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  594. if (bDhcpServer) {
  595. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  596. }
  597. }
  598. // Render Dashboard View
  599. function renderDashboard() {
  600. const matrix = document.getElementById('port-matrix');
  601. if (!matrix) return;
  602. const ifaces = state.interfaces || [];
  603. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  604. if (matrix.dataset.sig === sig) {
  605. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  606. }
  607. matrix.dataset.sig = sig;
  608. matrix.innerHTML = '';
  609. (state.interfaces || []).forEach(iface => {
  610. const isUp = iface.state === 'UP';
  611. const isVlan = iface.is_vlan;
  612. const portCard = document.createElement('div');
  613. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  614. isUp
  615. ? (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')
  616. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  617. }`;
  618. portCard.onclick = () => openIfaceModal(iface.name);
  619. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  620. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  621. portCard.innerHTML = `
  622. <div class="flex items-center justify-between mb-2">
  623. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  624. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  625. </div>
  626. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  627. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  628. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  629. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  630. </div>
  631. `;
  632. matrix.appendChild(portCard);
  633. });
  634. const ifaceTbody = document.getElementById('quick-interfaces-table');
  635. if (ifaceTbody) {
  636. ifaceTbody.innerHTML = '';
  637. (state.interfaces || []).forEach(i => {
  638. const isUp = i.state === 'UP';
  639. const tr = document.createElement('tr');
  640. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  641. tr.onclick = () => openIfaceModal(i.name);
  642. const rxStr = i.rate?.rx_human || '0 B/s';
  643. const txStr = i.rate?.tx_human || '0 B/s';
  644. tr.innerHTML = `
  645. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  646. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  647. <span>${i.name}</span>
  648. </td>
  649. <td class="py-2.5 text-slate-300 font-sans">
  650. ${getRoleBadge(i.role || 'LAN')}
  651. </td>
  652. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  653. <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>
  654. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  655. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  656. </td>
  657. <td class="py-2.5 text-right font-sans font-semibold">
  658. <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>
  659. </td>
  660. `;
  661. ifaceTbody.appendChild(tr);
  662. });
  663. }
  664. const vlanTbody = document.getElementById('quick-vlans-table');
  665. if (vlanTbody) {
  666. vlanTbody.innerHTML = '';
  667. }
  668. }
  669. // Expand / Collapse Handlers
  670. function toggleExpand(parentName) {
  671. if (state.expandedParents.has(parentName)) {
  672. state.expandedParents.delete(parentName);
  673. } else {
  674. state.expandedParents.add(parentName);
  675. }
  676. renderInterfacesList();
  677. }
  678. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  679. function supportsVLAN(iface) {
  680. if (!iface) return false;
  681. if (iface.is_vlan) return false;
  682. const name = (iface.name || '').toLowerCase();
  683. const type = (iface.type || '').toLowerCase();
  684. const role = (iface.role || '').toLowerCase();
  685. // Exclude loopback
  686. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  687. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  688. if (type === 'wireguard' || name.startsWith('wg')) return false;
  689. // Exclude PPP / PPPoE
  690. if (type === 'ppp' || name.startsWith('ppp')) return false;
  691. // Exclude other Layer 3 tunnels and dummy devices
  692. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  693. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  694. return false;
  695. }
  696. // If name already contains a dot, it's already a sub-interface
  697. if (name.includes('.')) return false;
  698. return true;
  699. }
  700. // Expand / Collapse Handlers
  701. function toggleExpand(parentName) {
  702. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  703. if (childVlans.length === 0) {
  704. // Cannot expand an interface with no VLANs
  705. state.expandedParents.delete(parentName);
  706. return;
  707. }
  708. if (state.expandedParents.has(parentName)) {
  709. state.expandedParents.delete(parentName);
  710. } else {
  711. state.expandedParents.add(parentName);
  712. }
  713. renderInterfacesList();
  714. }
  715. function expandAllIfaces(expand) {
  716. if (expand) {
  717. (state.interfaces || []).forEach(i => {
  718. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  719. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  720. });
  721. } else {
  722. state.expandedParents.clear();
  723. }
  724. renderInterfacesList();
  725. }
  726. // =========================================================================
  727. // INTERFACE ROLE TAGS MANAGEMENT
  728. // =========================================================================
  729. const ROLE_COLORS = {
  730. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  731. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  732. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  733. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  734. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  735. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  736. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  737. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  738. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  739. };
  740. function getRoleBadge(roleName) {
  741. const name = roleName || 'LAN';
  742. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  743. const colorKey = (role?.color || 'blue').toLowerCase();
  744. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  745. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  746. }
  747. function switchIfaceSubTab(subTab) {
  748. state.activeIfaceSubTab = subTab;
  749. const treeTab = document.getElementById('ifaces-subtab-tree');
  750. const rolesTab = document.getElementById('ifaces-subtab-roles');
  751. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  752. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  753. if (subTab === 'roles') {
  754. treeTab?.classList.add('hidden');
  755. rolesTab?.classList.remove('hidden');
  756. if (btnRoles) {
  757. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  758. }
  759. if (btnTree) {
  760. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  761. }
  762. loadRoles();
  763. } else {
  764. rolesTab?.classList.add('hidden');
  765. treeTab?.classList.remove('hidden');
  766. if (btnTree) {
  767. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  768. }
  769. if (btnRoles) {
  770. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  771. }
  772. renderInterfacesList();
  773. }
  774. }
  775. async function loadRoles() {
  776. try {
  777. const res = await fetch(`${API_BASE}/roles`);
  778. if (res.ok) {
  779. state.roles = await res.json();
  780. const countEl = document.getElementById('badge-roles-count');
  781. if (countEl) countEl.innerText = (state.roles || []).length;
  782. renderRolesTable();
  783. populateRoleSelects();
  784. }
  785. } catch (err) {
  786. console.error('Failed to load role tags:', err);
  787. }
  788. }
  789. function renderRolesTable() {
  790. const tbody = document.getElementById('roles-table-body');
  791. const empty = document.getElementById('roles-empty-state');
  792. if (!tbody) return;
  793. const roles = state.roles || [];
  794. if (roles.length === 0) {
  795. tbody.innerHTML = '';
  796. empty?.classList.remove('hidden');
  797. return;
  798. }
  799. empty?.classList.add('hidden');
  800. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  801. if (tbody.dataset.sig === sig) return;
  802. tbody.dataset.sig = sig;
  803. tbody.innerHTML = roles.map(r => {
  804. const colorKey = (r.color || 'blue').toLowerCase();
  805. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  806. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  807. const ifacesChips = ifaces.length > 0
  808. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  809. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  810. return `
  811. <tr class="hover:bg-slate-800/40 transition">
  812. <td class="py-3 px-4">
  813. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  814. ${escapeHtml(r.name)}
  815. </span>
  816. </td>
  817. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  818. <span>${escapeHtml(r.name)}</span>
  819. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  820. </td>
  821. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  822. <span class="inline-flex items-center gap-1.5">
  823. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  824. <span>${escapeHtml(r.color || 'blue')}</span>
  825. </span>
  826. </td>
  827. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  828. <td class="py-3 px-4 font-sans">
  829. <div class="flex flex-wrap items-center">
  830. ${ifacesChips}
  831. </div>
  832. </td>
  833. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  834. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  835. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  836. Edit
  837. </button>
  838. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  839. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  840. Delete
  841. </button>
  842. </td>
  843. </tr>
  844. `;
  845. }).join('');
  846. }
  847. function openRoleModal(id = null) {
  848. const modal = document.getElementById('role-modal');
  849. if (!modal) return;
  850. const idInput = document.getElementById('role-modal-id');
  851. const nameInput = document.getElementById('role-modal-name');
  852. const colorSelect = document.getElementById('role-modal-color');
  853. const descInput = document.getElementById('role-modal-desc');
  854. const title = document.getElementById('role-modal-title');
  855. if (id) {
  856. const role = (state.roles || []).find(r => r.id === id);
  857. if (role) {
  858. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  859. if (idInput) idInput.value = role.id;
  860. if (nameInput) nameInput.value = role.name;
  861. if (colorSelect) colorSelect.value = role.color || 'blue';
  862. if (descInput) descInput.value = role.description || '';
  863. }
  864. } else {
  865. if (title) title.innerText = 'Add Role Tag';
  866. if (idInput) idInput.value = '';
  867. if (nameInput) nameInput.value = '';
  868. if (colorSelect) colorSelect.value = 'blue';
  869. if (descInput) descInput.value = '';
  870. }
  871. updateRoleModalPreview();
  872. modal.classList.remove('hidden');
  873. }
  874. function closeRoleModal() {
  875. const modal = document.getElementById('role-modal');
  876. if (modal) modal.classList.add('hidden');
  877. }
  878. function updateRoleModalPreview() {
  879. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  880. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  881. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  882. const preview = document.getElementById('role-modal-preview');
  883. if (preview) {
  884. preview.innerText = name;
  885. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  886. }
  887. }
  888. async function submitSaveRole(e) {
  889. e.preventDefault();
  890. const id = document.getElementById('role-modal-id')?.value;
  891. const name = document.getElementById('role-modal-name')?.value.trim();
  892. const color = document.getElementById('role-modal-color')?.value;
  893. const desc = document.getElementById('role-modal-desc')?.value.trim();
  894. if (!name) return;
  895. try {
  896. const payload = { id, name, color, description: desc };
  897. const method = id ? 'PUT' : 'POST';
  898. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  899. const res = await fetch(url, {
  900. method,
  901. headers: { 'Content-Type': 'application/json' },
  902. body: JSON.stringify(payload)
  903. });
  904. if (res.ok) {
  905. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  906. closeRoleModal();
  907. await loadRoles();
  908. fetchData(false);
  909. } else {
  910. const err = await res.json();
  911. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  912. }
  913. } catch (err) {
  914. showToast('Error', err.message, 'error');
  915. }
  916. }
  917. async function deleteRoleTag(id, name) {
  918. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  919. try {
  920. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  921. method: 'DELETE'
  922. });
  923. if (res.ok) {
  924. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  925. await loadRoles();
  926. fetchData(false);
  927. } else {
  928. const err = await res.json();
  929. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  930. }
  931. } catch (err) {
  932. showToast('Error', err.message, 'error');
  933. }
  934. }
  935. function populateRoleSelects(selectedRole = '') {
  936. const ifaceSelect = document.getElementById('modal-iface-role');
  937. const vlanSelect = document.getElementById('vlan-role');
  938. const roles = state.roles || [];
  939. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  940. if (ifaceSelect) {
  941. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  942. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  943. ifaceSelect.innerHTML = optionsHtml;
  944. ifaceSelect.dataset.optionsSig = optionsHtml;
  945. }
  946. if (currentVal) ifaceSelect.value = currentVal;
  947. }
  948. if (vlanSelect) {
  949. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  950. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  951. vlanSelect.innerHTML = optionsHtml;
  952. vlanSelect.dataset.optionsSig = optionsHtml;
  953. }
  954. if (currentVal) vlanSelect.value = currentVal;
  955. }
  956. }
  957. // Filter and Render Hierarchical Interfaces List
  958. function filterIfaces(filter) {
  959. state.ifaceFilter = filter || 'all';
  960. renderInterfacesList();
  961. }
  962. function renderInterfacesList() {
  963. const tbody = document.getElementById('interfaces-tree-tbody');
  964. const emptyState = document.getElementById('interfaces-empty-state');
  965. const summary = document.getElementById('ifaces-list-summary');
  966. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  967. const allIfaces = state.interfaces || [];
  968. const allVlans = state.vlans || [];
  969. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  970. const filteredParents = parentIfaces.filter(parent => {
  971. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  972. if (query) {
  973. const matchName = parent.name.toLowerCase().includes(query);
  974. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  975. const matchRole = (parent.role || '').toLowerCase().includes(query);
  976. const matchType = (parent.type || '').toLowerCase().includes(query);
  977. const matchVlan = childVlans.some(v =>
  978. v.name.toLowerCase().includes(query) ||
  979. String(v.vlan_id).includes(query) ||
  980. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  981. (v.description || '').toLowerCase().includes(query)
  982. );
  983. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  984. }
  985. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  986. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  987. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  988. return true;
  989. });
  990. if (summary) {
  991. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  992. }
  993. if (filteredParents.length === 0) {
  994. emptyState?.classList.remove('hidden');
  995. tbody.innerHTML = '';
  996. return;
  997. }
  998. emptyState?.classList.add('hidden');
  999. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1000. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1001. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}`;
  1002. }).join(';');
  1003. if (tbody.dataset.sig === sig) {
  1004. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1005. }
  1006. tbody.dataset.sig = sig;
  1007. tbody.innerHTML = '';
  1008. filteredParents.forEach(parent => {
  1009. const isUp = parent.state === 'UP';
  1010. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1011. const hasVlans = childVlans.length > 0;
  1012. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1013. const canHaveVlan = supportsVLAN(parent);
  1014. const parentRow = document.createElement('tr');
  1015. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1016. parentRow.innerHTML = `
  1017. <td class="py-3 px-3 text-center">
  1018. ${hasVlans ? `
  1019. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1020. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1021. <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">
  1022. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1023. </svg>
  1024. </button>
  1025. ` : `
  1026. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1027. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1028. </div>
  1029. `}
  1030. </td>
  1031. <td class="py-3 px-4">
  1032. <div class="flex items-center space-x-2.5">
  1033. <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">
  1034. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1035. </div>
  1036. <div>
  1037. <div class="flex items-center gap-2">
  1038. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1039. <span>${parent.name}</span>
  1040. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1041. </span>
  1042. ${hasVlans ? `
  1043. <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>
  1044. ` : `
  1045. <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>
  1046. `}
  1047. </div>
  1048. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1049. </div>
  1050. </div>
  1051. </td>
  1052. <td class="py-3 px-4 font-sans">
  1053. <div class="flex items-center gap-1.5">
  1054. ${getRoleBadge(parent.role || 'LAN')}
  1055. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1056. </div>
  1057. </td>
  1058. <td class="py-3 px-4">
  1059. ${parent.ipv4 && parent.ipv4.length > 0
  1060. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1061. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1062. }
  1063. ${(() => {
  1064. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1065. if (!c) return '';
  1066. 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');
  1067. 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>`;
  1068. })()}
  1069. </td>
  1070. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1071. <div>${parent.mac || 'N/A'}</div>
  1072. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1073. </td>
  1074. <td class="py-3 px-4 text-[11px]">
  1075. <div class="flex items-center space-x-2">
  1076. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1077. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1078. </div>
  1079. </td>
  1080. <td class="py-3 px-4 font-sans">
  1081. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1082. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1083. 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'
  1084. }" title="Click to toggle link status">
  1085. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1086. <span>${parent.state}</span>
  1087. </button>
  1088. </td>
  1089. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1090. ${(() => {
  1091. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1092. if (c) {
  1093. 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>`;
  1094. }
  1095. 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>`;
  1096. })()}
  1097. ${canHaveVlan ? `
  1098. <button onclick="openVlanModal('${parent.name}')"
  1099. 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">
  1100. + Add VLAN
  1101. </button>
  1102. ` : ''}
  1103. <button onclick="openIfaceModal('${parent.name}')"
  1104. 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">
  1105. Configure
  1106. </button>
  1107. </td>
  1108. `;
  1109. tbody.appendChild(parentRow);
  1110. if (isExpanded) {
  1111. const drawerRow = document.createElement('tr');
  1112. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1113. const drawerCell = document.createElement('td');
  1114. drawerCell.colSpan = 8;
  1115. drawerCell.className = 'p-0';
  1116. drawerCell.innerHTML = `
  1117. <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">
  1118. <div class="flex items-center justify-between mb-3">
  1119. <div class="flex items-center space-x-3">
  1120. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1121. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1122. </span>
  1123. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1124. ${childVlans.length} Attached
  1125. </span>
  1126. </div>
  1127. <button onclick="openVlanModal('${parent.name}')"
  1128. 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">
  1129. <span>+ Create VLAN on ${parent.name}</span>
  1130. </button>
  1131. </div>
  1132. ${childVlans.length === 0 ? `
  1133. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1134. <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>
  1135. <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">
  1136. <span>+ Create Your First VLAN on ${parent.name}</span>
  1137. </button>
  1138. </div>
  1139. ` : `
  1140. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1141. <table class="w-full text-left text-xs font-mono">
  1142. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1143. <tr>
  1144. <th class="py-2.5 px-4">VLAN ID</th>
  1145. <th class="py-2.5 px-4">Interface Device</th>
  1146. <th class="py-2.5 px-4">Subnet Gateway</th>
  1147. <th class="py-2.5 px-4">Role / Alias</th>
  1148. <th class="py-2.5 px-4">MTU</th>
  1149. <th class="py-2.5 px-4">Throughput</th>
  1150. <th class="py-2.5 px-4">Status</th>
  1151. <th class="py-2.5 px-4 text-right">Actions</th>
  1152. </tr>
  1153. </thead>
  1154. <tbody class="divide-y divide-slate-800/70">
  1155. ${childVlans.map(v => {
  1156. const isVlanUp = v.state === 'UP';
  1157. return `
  1158. <tr class="hover:bg-slate-800/40 transition">
  1159. <td class="py-2.5 px-4">
  1160. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1161. VLAN ${v.vlan_id}
  1162. </span>
  1163. </td>
  1164. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1165. <span class="text-cyan-500">└─</span>
  1166. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1167. <span>${v.name}</span>
  1168. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1169. </span>
  1170. </td>
  1171. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1172. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1173. ${(() => {
  1174. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1175. if (!c) return '';
  1176. 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';
  1177. 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>`;
  1178. })()}
  1179. </td>
  1180. <td class="py-2.5 px-4 font-sans text-slate-300">
  1181. <div class="flex items-center gap-1.5">
  1182. ${getRoleBadge(v.role || 'LAN')}
  1183. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1184. </div>
  1185. </td>
  1186. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1187. <td class="py-2.5 px-4 text-[11px]">
  1188. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1189. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1190. </td>
  1191. <td class="py-2.5 px-4 font-sans">
  1192. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1193. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1194. 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'
  1195. }">
  1196. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1197. <span>${v.state}</span>
  1198. </button>
  1199. </td>
  1200. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1201. ${(() => {
  1202. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1203. if (c) {
  1204. 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>`;
  1205. }
  1206. 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>`;
  1207. })()}
  1208. <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>
  1209. <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>
  1210. </td>
  1211. </tr>
  1212. `;
  1213. }).join('')}
  1214. </tbody>
  1215. </table>
  1216. </div>
  1217. `}
  1218. </div>
  1219. `;
  1220. drawerRow.appendChild(drawerCell);
  1221. tbody.appendChild(drawerRow);
  1222. }
  1223. });
  1224. }
  1225. // Render VLANs Dedicated View
  1226. function renderVlansList() {
  1227. const tbody = document.getElementById('vlans-table-body');
  1228. if (!tbody) return;
  1229. const emptyState = document.getElementById('vlans-empty-state');
  1230. const countBadge = document.getElementById('vlans-table-count');
  1231. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1232. const allVlans = state.vlans || [];
  1233. if (countBadge) countBadge.innerText = allVlans.length;
  1234. const filtered = allVlans.filter(v => {
  1235. if (!query) return true;
  1236. return v.name.toLowerCase().includes(query) ||
  1237. String(v.vlan_id).includes(query) ||
  1238. (v.description || '').toLowerCase().includes(query) ||
  1239. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1240. });
  1241. if (allVlans.length === 0) {
  1242. emptyState.classList.remove('hidden');
  1243. tbody.innerHTML = '';
  1244. return;
  1245. }
  1246. emptyState.classList.add('hidden');
  1247. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1248. if (tbody.dataset.sig === sig) return;
  1249. tbody.dataset.sig = sig;
  1250. tbody.innerHTML = '';
  1251. filtered.forEach(v => {
  1252. const isUp = v.state === 'UP';
  1253. const tr = document.createElement('tr');
  1254. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1255. tr.innerHTML = `
  1256. <td class="py-3 px-4">
  1257. <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">
  1258. VLAN ${v.vlan_id}
  1259. </span>
  1260. </td>
  1261. <td class="py-3 px-4 font-bold text-white">
  1262. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1263. <span>${v.name}</span>
  1264. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1265. </span>
  1266. </td>
  1267. <td class="py-3 px-4 text-slate-300">
  1268. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1269. </td>
  1270. <td class="py-3 px-4 text-emerald-400 font-medium">
  1271. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1272. </td>
  1273. <td class="py-3 px-4 text-slate-300 font-sans">
  1274. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1275. </td>
  1276. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1277. <td class="py-3 px-4 font-sans">
  1278. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1279. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1280. 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'
  1281. }">
  1282. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1283. <span>${v.state}</span>
  1284. </button>
  1285. </td>
  1286. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1287. <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>
  1288. <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>
  1289. </td>
  1290. `;
  1291. tbody.appendChild(tr);
  1292. });
  1293. }
  1294. // Toggle interface UP / DOWN
  1295. async function toggleInterfaceState(name, newState) {
  1296. try {
  1297. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1298. method: 'POST',
  1299. headers: { 'Content-Type': 'application/json' },
  1300. body: JSON.stringify({ state: newState })
  1301. });
  1302. const data = await res.json();
  1303. if (res.ok) {
  1304. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1305. fetchData(false);
  1306. } else {
  1307. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1308. }
  1309. } catch (err) {
  1310. showToast('Error', err.message, 'error');
  1311. }
  1312. }
  1313. // ---------------- MikroTik Flag & Utilities ----------------
  1314. function renderMikroTikFlag(running, disabled) {
  1315. if (running) {
  1316. 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>`;
  1317. }
  1318. if (disabled) {
  1319. 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>`;
  1320. }
  1321. 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>`;
  1322. }
  1323. function copyToClipboard(text, label = 'Text') {
  1324. navigator.clipboard.writeText(text).then(() => {
  1325. showToast('Copied', `${label} copied to clipboard`, 'success');
  1326. }).catch(() => {
  1327. prompt('Copy value:', text);
  1328. });
  1329. }
  1330. // ======================== PPP Profiles Shared Helper ========================
  1331. async function fetchPPPProfilesList() {
  1332. try {
  1333. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1334. if (res.ok) {
  1335. state.pppProfiles = await res.json();
  1336. }
  1337. } catch (err) {
  1338. console.error('Failed to load PPP profiles:', err);
  1339. }
  1340. }
  1341. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1342. const sel = document.getElementById(selectId);
  1343. if (!sel) return;
  1344. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1345. { name: 'default', use_encryption: 'no' },
  1346. { name: 'default-encryption', use_encryption: 'required' }
  1347. ];
  1348. sel.innerHTML = '';
  1349. profiles.forEach(p => {
  1350. const opt = document.createElement('option');
  1351. opt.value = p.name;
  1352. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1353. opt.innerText = `${p.name}${encBadge}`;
  1354. sel.appendChild(opt);
  1355. });
  1356. if (selectedVal) {
  1357. sel.value = selectedVal;
  1358. } else {
  1359. sel.value = defaultVal;
  1360. }
  1361. if (!sel.value && sel.options.length > 0) {
  1362. sel.selectedIndex = 0;
  1363. }
  1364. }
  1365. // ======================== PPPoE Multi-Instance ========================
  1366. async function loadPPPoE(populateInputs = true) {
  1367. try {
  1368. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1369. await fetchPPPProfilesList();
  1370. }
  1371. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1372. const list = await res.json();
  1373. state.pppoeList = Array.isArray(list) ? list : [];
  1374. const badge = document.getElementById('pppoe-count-badge');
  1375. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1376. const tbody = document.getElementById('pppoe-table-body');
  1377. const empty = document.getElementById('pppoe-empty');
  1378. if (!tbody) return;
  1379. tbody.innerHTML = '';
  1380. if (state.pppoeList.length === 0) {
  1381. if (empty) empty.classList.remove('hidden');
  1382. } else {
  1383. if (empty) empty.classList.add('hidden');
  1384. state.pppoeList.forEach(inst => {
  1385. const tr = document.createElement('tr');
  1386. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1387. tr.innerHTML = `
  1388. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1389. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1390. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1391. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1392. <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>
  1393. <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>
  1394. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1395. <td class="py-2.5 px-3 text-center">
  1396. <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'}">
  1397. ${inst.default_route ? 'Yes' : 'No'}
  1398. </span>
  1399. </td>
  1400. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1401. ${inst.running ? `
  1402. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1403. ` : `
  1404. <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>
  1405. `}
  1406. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1407. ${inst.disabled ? 'Enable' : 'Disable'}
  1408. </button>
  1409. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1410. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1411. </td>
  1412. `;
  1413. tbody.appendChild(tr);
  1414. });
  1415. }
  1416. } catch (err) {
  1417. console.error('Failed to load PPPoE:', err);
  1418. }
  1419. }
  1420. function openAddPPPoEModal() {
  1421. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1422. document.getElementById('pppoe-modal-edit-orig').value = '';
  1423. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1424. document.getElementById('pppoe-modal-name').readOnly = false;
  1425. document.getElementById('pppoe-modal-user').value = '';
  1426. document.getElementById('pppoe-modal-pass').value = '';
  1427. document.getElementById('pppoe-modal-service').value = '';
  1428. document.getElementById('pppoe-modal-mtu').value = '1492';
  1429. document.getElementById('pppoe-modal-defroute').checked = true;
  1430. document.getElementById('pppoe-modal-reconnect').checked = true;
  1431. document.getElementById('pppoe-modal-disabled').checked = false;
  1432. // Populate profiles
  1433. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1434. // Populate interfaces
  1435. const sel = document.getElementById('pppoe-modal-iface');
  1436. sel.innerHTML = '';
  1437. (state.interfaces || []).forEach(i => {
  1438. if (i.name === 'lo') return;
  1439. const opt = document.createElement('option');
  1440. opt.value = i.name;
  1441. opt.innerText = `${i.name} (${i.role || i.type})`;
  1442. sel.appendChild(opt);
  1443. });
  1444. document.getElementById('pppoe-modal').classList.remove('hidden');
  1445. }
  1446. function openEditPPPoEModal(name) {
  1447. const inst = (state.pppoeList || []).find(i => i.name === name);
  1448. if (!inst) return;
  1449. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1450. document.getElementById('pppoe-modal-edit-orig').value = name;
  1451. document.getElementById('pppoe-modal-name').value = inst.name;
  1452. document.getElementById('pppoe-modal-name').readOnly = true;
  1453. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1454. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1455. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1456. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1457. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1458. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1459. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1460. // Populate profiles
  1461. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1462. const sel = document.getElementById('pppoe-modal-iface');
  1463. sel.innerHTML = '';
  1464. (state.interfaces || []).forEach(i => {
  1465. if (i.name === 'lo') return;
  1466. const opt = document.createElement('option');
  1467. opt.value = i.name;
  1468. opt.innerText = `${i.name} (${i.role || i.type})`;
  1469. if (i.name === inst.interface) opt.selected = true;
  1470. sel.appendChild(opt);
  1471. });
  1472. document.getElementById('pppoe-modal').classList.remove('hidden');
  1473. }
  1474. function closePPPoEModal() {
  1475. document.getElementById('pppoe-modal').classList.add('hidden');
  1476. }
  1477. async function submitSavePPPoE(e) {
  1478. e.preventDefault();
  1479. const name = document.getElementById('pppoe-modal-name').value.trim();
  1480. const iface = document.getElementById('pppoe-modal-iface').value;
  1481. const user = document.getElementById('pppoe-modal-user').value.trim();
  1482. const pass = document.getElementById('pppoe-modal-pass').value;
  1483. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1484. const service = document.getElementById('pppoe-modal-service').value.trim();
  1485. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1486. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1487. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1488. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1489. try {
  1490. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1491. method: 'POST',
  1492. headers: { 'Content-Type': 'application/json' },
  1493. body: JSON.stringify({
  1494. name,
  1495. interface: iface,
  1496. username: user,
  1497. password: pass,
  1498. profile: profile,
  1499. service_name: service,
  1500. mtu,
  1501. default_route: defRoute,
  1502. auto_reconnect: reconnect,
  1503. disabled
  1504. })
  1505. });
  1506. if (res.ok) {
  1507. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1508. closePPPoEModal();
  1509. loadPPPoE(false);
  1510. fetchData(false);
  1511. } else {
  1512. const err = await res.json();
  1513. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1514. }
  1515. } catch (err) {
  1516. showToast('Error', err.message, 'error');
  1517. }
  1518. }
  1519. async function connectPPPoEInstance(name) {
  1520. try {
  1521. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1522. if (res.ok) {
  1523. showToast('Connecting', `Dialing ${name}...`, 'info');
  1524. setTimeout(() => loadPPPoE(false), 2000);
  1525. }
  1526. } catch (err) {
  1527. showToast('Error', err.message, 'error');
  1528. }
  1529. }
  1530. async function disconnectPPPoEInstance(name) {
  1531. try {
  1532. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1533. if (res.ok) {
  1534. showToast('Disconnected', `${name} session terminated`, 'info');
  1535. setTimeout(() => loadPPPoE(false), 1000);
  1536. }
  1537. } catch (err) {
  1538. showToast('Error', err.message, 'error');
  1539. }
  1540. }
  1541. async function togglePPPoEState(name, enable) {
  1542. try {
  1543. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1544. method: 'POST',
  1545. headers: { 'Content-Type': 'application/json' },
  1546. body: JSON.stringify({ enabled: enable })
  1547. });
  1548. if (res.ok) {
  1549. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1550. loadPPPoE(false);
  1551. }
  1552. } catch (err) {
  1553. showToast('Error', err.message, 'error');
  1554. }
  1555. }
  1556. async function deletePPPoEInstance(name) {
  1557. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1558. try {
  1559. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1560. if (res.ok) {
  1561. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1562. loadPPPoE(false);
  1563. fetchData(false);
  1564. }
  1565. } catch (err) {
  1566. showToast('Error', err.message, 'error');
  1567. }
  1568. }
  1569. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1570. state.wgSubTab = 'ifaces';
  1571. function switchWGSubTab(tab) {
  1572. state.wgSubTab = tab;
  1573. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1574. const peersPanel = document.getElementById('wg-subtab-peers');
  1575. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1576. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1577. if (tab === 'ifaces') {
  1578. ifacesPanel?.classList.remove('hidden');
  1579. peersPanel?.classList.add('hidden');
  1580. 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';
  1581. 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';
  1582. } else {
  1583. ifacesPanel?.classList.add('hidden');
  1584. peersPanel?.classList.remove('hidden');
  1585. 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';
  1586. 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';
  1587. renderWGPeers();
  1588. }
  1589. }
  1590. async function loadWireGuard(populateInputs = true) {
  1591. try {
  1592. const [ifacesRes, peersRes] = await Promise.all([
  1593. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1594. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1595. ]);
  1596. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1597. const peers = peersRes.ok ? await peersRes.json() : [];
  1598. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1599. state.wgPeers = Array.isArray(peers) ? peers : [];
  1600. // Badges
  1601. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1602. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1603. const peersCountBadge = document.getElementById('wg-peers-count');
  1604. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1605. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1606. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1607. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1608. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1609. // Render Interfaces
  1610. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1611. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1612. if (ifacesTbody) {
  1613. ifacesTbody.innerHTML = '';
  1614. if (state.wgInterfaces.length === 0) {
  1615. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1616. } else {
  1617. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1618. state.wgInterfaces.forEach(iface => {
  1619. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1620. const tr = document.createElement('tr');
  1621. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1622. tr.innerHTML = `
  1623. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1624. <td class="py-2.5 px-3">
  1625. <div class="flex items-center gap-1.5">
  1626. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1627. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1628. </div>
  1629. </td>
  1630. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1631. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1632. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1633. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1634. ${(iface.public_key || '').substring(0, 10)}... 📋
  1635. </span>
  1636. </td>
  1637. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1638. <td class="py-2.5 px-3 text-center">
  1639. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1640. </td>
  1641. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1642. ${iface.running ? `
  1643. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1644. ` : `
  1645. <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>
  1646. `}
  1647. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1648. ${iface.disabled ? 'Enable' : 'Disable'}
  1649. </button>
  1650. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1651. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1652. </td>
  1653. `;
  1654. ifacesTbody.appendChild(tr);
  1655. });
  1656. }
  1657. }
  1658. // Populate filter dropdown in peers tab
  1659. const filterSel = document.getElementById('wg-peers-filter-iface');
  1660. if (filterSel) {
  1661. const currentVal = filterSel.value;
  1662. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1663. state.wgInterfaces.forEach(i => {
  1664. const opt = document.createElement('option');
  1665. opt.value = i.name;
  1666. opt.innerText = i.name;
  1667. if (i.name === currentVal) opt.selected = true;
  1668. filterSel.appendChild(opt);
  1669. });
  1670. }
  1671. renderWGPeers();
  1672. } catch (err) {
  1673. console.error('Failed to load WireGuard:', err);
  1674. }
  1675. }
  1676. function formatWGPeerEndpoint(address, port) {
  1677. if (!address || address === '(none)') return '--';
  1678. let addr = address.trim();
  1679. let p = port || 0;
  1680. while (addr.includes(':') && !addr.startsWith('[')) {
  1681. const lastColon = addr.lastIndexOf(':');
  1682. const maybePort = addr.substring(lastColon + 1);
  1683. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1684. if (!p) p = parseInt(maybePort, 10);
  1685. addr = addr.substring(0, lastColon);
  1686. } else {
  1687. break;
  1688. }
  1689. }
  1690. return p ? `${addr}:${p}` : addr;
  1691. }
  1692. function renderWGPeers() {
  1693. const filterSel = document.getElementById('wg-peers-filter-iface');
  1694. const selectedIface = filterSel ? filterSel.value : '';
  1695. const tbody = document.getElementById('wg-peers-table-body');
  1696. const empty = document.getElementById('wg-peers-empty');
  1697. if (!tbody) return;
  1698. tbody.innerHTML = '';
  1699. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1700. if (filtered.length === 0) {
  1701. if (empty) empty.classList.remove('hidden');
  1702. } else {
  1703. if (empty) empty.classList.add('hidden');
  1704. filtered.forEach(p => {
  1705. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1706. const tr = document.createElement('tr');
  1707. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1708. tr.innerHTML = `
  1709. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1710. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1711. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1712. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1713. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1714. ${(p.public_key || '').substring(0, 10)}... 📋
  1715. </span>
  1716. </td>
  1717. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1718. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1719. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1720. <td class="py-2.5 px-3 font-mono text-[11px]">
  1721. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1722. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1723. </td>
  1724. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1725. <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">
  1726. ${p.disabled ? 'Enable' : 'Disable'}
  1727. </button>
  1728. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1729. <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>
  1730. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1731. </td>
  1732. `;
  1733. tbody.appendChild(tr);
  1734. });
  1735. }
  1736. }
  1737. function openAddWGInterfaceModal() {
  1738. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1739. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1740. const nameEl = document.getElementById('wg-iface-modal-name');
  1741. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1742. nameEl.readOnly = false;
  1743. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1744. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1745. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1746. document.getElementById('wg-iface-modal-comment').value = '';
  1747. document.getElementById('wg-iface-modal-pubkey').value = '';
  1748. document.getElementById('wg-iface-modal-privkey').value = '';
  1749. document.getElementById('wg-iface-modal-disabled').checked = false;
  1750. generateWGInterfaceKeys();
  1751. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1752. }
  1753. function openEditWGInterfaceModal(name) {
  1754. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1755. if (!iface) return;
  1756. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1757. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1758. const nameEl = document.getElementById('wg-iface-modal-name');
  1759. nameEl.value = iface.name;
  1760. nameEl.readOnly = false; // ALLOW RENAMING
  1761. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1762. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1763. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1764. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1765. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1766. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1767. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1768. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1769. }
  1770. function closeAddWGInterfaceModal() {
  1771. document.getElementById('wg-iface-modal').classList.add('hidden');
  1772. }
  1773. async function generateWGInterfaceKeys() {
  1774. try {
  1775. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1776. const keys = await res.json();
  1777. if (res.ok) {
  1778. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1779. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1780. }
  1781. } catch (err) {
  1782. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1783. }
  1784. }
  1785. async function onWGInterfacePrivKeyInput() {
  1786. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1787. if (!privKey) return;
  1788. try {
  1789. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1790. method: 'POST',
  1791. headers: { 'Content-Type': 'application/json' },
  1792. body: JSON.stringify({ private_key: privKey })
  1793. });
  1794. if (res.ok) {
  1795. const data = await res.json();
  1796. if (data.public_key) {
  1797. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1798. }
  1799. }
  1800. } catch (err) {
  1801. // Ignore while typing
  1802. }
  1803. }
  1804. function toggleWGPrivKeyVisibility() {
  1805. const el = document.getElementById('wg-iface-modal-privkey');
  1806. const btn = document.getElementById('btn-toggle-wg-privkey');
  1807. if (el.type === 'password') {
  1808. el.type = 'text';
  1809. btn.innerText = '🙈 Hide';
  1810. } else {
  1811. el.type = 'password';
  1812. btn.innerText = '👁️ Show';
  1813. }
  1814. }
  1815. function copyWGInterfacePubKey() {
  1816. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1817. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1818. }
  1819. async function submitSaveWGInterface(e) {
  1820. e.preventDefault();
  1821. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1822. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1823. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1824. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1825. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1826. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1827. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1828. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1829. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1830. try {
  1831. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1832. method: 'POST',
  1833. headers: { 'Content-Type': 'application/json' },
  1834. body: JSON.stringify({
  1835. orig_name: origName,
  1836. name,
  1837. listen_port: port,
  1838. address: addr,
  1839. mtu,
  1840. comment,
  1841. public_key: pub,
  1842. private_key: priv,
  1843. disabled
  1844. })
  1845. });
  1846. const data = await res.json();
  1847. if (res.ok) {
  1848. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1849. closeAddWGInterfaceModal();
  1850. loadWireGuard(false);
  1851. fetchData(false);
  1852. } else {
  1853. showToast('Error', data.error || 'Failed to save interface', 'error');
  1854. }
  1855. } catch (err) {
  1856. showToast('Error', err.message, 'error');
  1857. }
  1858. }
  1859. async function startWGInterface(name) {
  1860. try {
  1861. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1862. if (res.ok) {
  1863. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1864. loadWireGuard(false);
  1865. fetchData(false);
  1866. }
  1867. } catch (err) {
  1868. showToast('Error', err.message, 'error');
  1869. }
  1870. }
  1871. async function stopWGInterface(name) {
  1872. try {
  1873. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1874. if (res.ok) {
  1875. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1876. loadWireGuard(false);
  1877. fetchData(false);
  1878. }
  1879. } catch (err) {
  1880. showToast('Error', err.message, 'error');
  1881. }
  1882. }
  1883. async function toggleWGInterfaceState(name, enable) {
  1884. try {
  1885. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1886. method: 'POST',
  1887. headers: { 'Content-Type': 'application/json' },
  1888. body: JSON.stringify({ enabled: enable })
  1889. });
  1890. if (res.ok) {
  1891. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1892. loadWireGuard(false);
  1893. fetchData(false);
  1894. }
  1895. } catch (err) {
  1896. showToast('Error', err.message, 'error');
  1897. }
  1898. }
  1899. async function deleteWGInterface(name) {
  1900. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1901. try {
  1902. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1903. if (res.ok) {
  1904. showToast('Deleted', `Interface ${name} removed`, 'success');
  1905. loadWireGuard(false);
  1906. fetchData(false);
  1907. }
  1908. } catch (err) {
  1909. showToast('Error', err.message, 'error');
  1910. }
  1911. }
  1912. function populateWGPeerIfaceSelect(selectedIface = '') {
  1913. const sel = document.getElementById('wg-peer-modal-iface');
  1914. if (!sel) return;
  1915. sel.innerHTML = '';
  1916. (state.wgInterfaces || []).forEach(i => {
  1917. const opt = document.createElement('option');
  1918. opt.value = i.name;
  1919. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1920. if (i.name === selectedIface) opt.selected = true;
  1921. sel.appendChild(opt);
  1922. });
  1923. }
  1924. function openAddWGPeerModal() {
  1925. if ((state.wgInterfaces || []).length === 0) {
  1926. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1927. openAddWGInterfaceModal();
  1928. return;
  1929. }
  1930. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1931. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1932. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1933. populateWGPeerIfaceSelect();
  1934. document.getElementById('wg-peer-modal-name').value = '';
  1935. document.getElementById('wg-peer-modal-pubkey').value = '';
  1936. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1937. document.getElementById('wg-peer-modal-endpoint').value = '';
  1938. document.getElementById('wg-peer-modal-port').value = '';
  1939. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1940. document.getElementById('wg-peer-modal-preshared').value = '';
  1941. document.getElementById('wg-peer-modal-disabled').checked = false;
  1942. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1943. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1944. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1945. }
  1946. function openEditWGPeerModal(ifaceName, pubKey) {
  1947. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1948. if (!peer) {
  1949. showToast('Not Found', 'Peer not found', 'warning');
  1950. return;
  1951. }
  1952. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1953. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1954. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1955. populateWGPeerIfaceSelect(peer.interface);
  1956. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1957. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1958. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1959. let epHost = (peer.endpoint_address || '').trim();
  1960. let epPort = peer.endpoint_port || '';
  1961. while (epHost.includes(':') && !epHost.startsWith('[')) {
  1962. const lastColon = epHost.lastIndexOf(':');
  1963. const maybePort = epHost.substring(lastColon + 1);
  1964. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1965. if (!epPort) epPort = parseInt(maybePort, 10);
  1966. epHost = epHost.substring(0, lastColon);
  1967. } else {
  1968. break;
  1969. }
  1970. }
  1971. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  1972. document.getElementById('wg-peer-modal-port').value = epPort;
  1973. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1974. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1975. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1976. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1977. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1978. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1979. }
  1980. function closeAddWGPeerModal() {
  1981. document.getElementById('wg-peer-modal').classList.add('hidden');
  1982. }
  1983. async function generatePeerKeypairHelper() {
  1984. try {
  1985. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1986. const keys = await res.json();
  1987. if (res.ok) {
  1988. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1989. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1990. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1991. checkWGPeerKeyValidity();
  1992. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1993. }
  1994. } catch (err) {
  1995. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1996. }
  1997. }
  1998. function copyGeneratedPeerPrivKey() {
  1999. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2000. if (priv) copyToClipboard(priv, 'Client Private Key');
  2001. }
  2002. async function generatePeerPSK() {
  2003. try {
  2004. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2005. const keys = await res.json();
  2006. if (res.ok && keys.private_key) {
  2007. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2008. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2009. }
  2010. } catch (err) {
  2011. showToast('Error', err.message, 'error');
  2012. }
  2013. }
  2014. function checkWGPeerKeyValidity() {
  2015. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2016. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2017. const warningEl = document.getElementById('wg-peer-key-warning');
  2018. if (!warningEl) return;
  2019. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2020. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2021. warningEl.classList.remove('hidden');
  2022. } else {
  2023. warningEl.classList.add('hidden');
  2024. }
  2025. }
  2026. async function submitSaveWGPeer(e) {
  2027. e.preventDefault();
  2028. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2029. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2030. const iface = document.getElementById('wg-peer-modal-iface').value;
  2031. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2032. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2033. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2034. .split(',')
  2035. .map(s => s.trim())
  2036. .filter(s => s.length > 0);
  2037. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2038. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2039. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2040. const lastColon = epHost.lastIndexOf(':');
  2041. const maybePort = epHost.substring(lastColon + 1);
  2042. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2043. if (!epPort) epPort = parseInt(maybePort, 10);
  2044. epHost = epHost.substring(0, lastColon);
  2045. } else {
  2046. break;
  2047. }
  2048. }
  2049. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2050. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2051. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2052. // Validation
  2053. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2054. if (targetIface && targetIface.public_key === pub) {
  2055. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2056. return;
  2057. }
  2058. try {
  2059. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2060. method: 'POST',
  2061. headers: { 'Content-Type': 'application/json' },
  2062. body: JSON.stringify({
  2063. orig_interface: origIface,
  2064. orig_public_key: origPubKey,
  2065. interface: iface,
  2066. name,
  2067. public_key: pub,
  2068. allowed_ips: allowed,
  2069. endpoint_address: epHost,
  2070. endpoint_port: epPort,
  2071. persistent_keepalive: keepalive,
  2072. preshared_key: psk,
  2073. disabled
  2074. })
  2075. });
  2076. const data = await res.json();
  2077. if (res.ok) {
  2078. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2079. closeAddWGPeerModal();
  2080. loadWireGuard(false);
  2081. } else {
  2082. showToast('Error', data.error || 'Failed to save peer', 'error');
  2083. }
  2084. } catch (err) {
  2085. showToast('Error', err.message, 'error');
  2086. }
  2087. }
  2088. async function toggleWGPeerState(iface, pubkey, enable) {
  2089. try {
  2090. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2091. method: 'POST',
  2092. headers: { 'Content-Type': 'application/json' },
  2093. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2094. });
  2095. const data = await res.json();
  2096. if (res.ok) {
  2097. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2098. loadWireGuard(false);
  2099. } else {
  2100. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2101. }
  2102. } catch (err) {
  2103. showToast('Error', err.message, 'error');
  2104. }
  2105. }
  2106. async function deleteWGPeer(iface, pubkey) {
  2107. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2108. try {
  2109. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2110. method: 'POST',
  2111. headers: { 'Content-Type': 'application/json' },
  2112. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2113. });
  2114. const data = await res.json();
  2115. if (res.ok) {
  2116. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2117. loadWireGuard(false);
  2118. } else {
  2119. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2120. }
  2121. } catch (err) {
  2122. showToast('Error', err.message, 'error');
  2123. }
  2124. }
  2125. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2126. function switchIpsecModalTab(tab) {
  2127. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2128. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2129. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2130. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2131. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2132. if (tab === 'p1') {
  2133. if (p1Tab) {
  2134. 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';
  2135. }
  2136. if (p2Tab) {
  2137. 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';
  2138. }
  2139. if (p1Content) p1Content.classList.remove('hidden');
  2140. if (p2Content) p2Content.classList.add('hidden');
  2141. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2142. } else {
  2143. if (p1Tab) {
  2144. 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';
  2145. }
  2146. if (p2Tab) {
  2147. 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';
  2148. }
  2149. if (p1Content) p1Content.classList.add('hidden');
  2150. if (p2Content) p2Content.classList.remove('hidden');
  2151. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2152. }
  2153. }
  2154. function toggleIpsecPhaseStep() {
  2155. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2156. if (p1Content && !p1Content.classList.contains('hidden')) {
  2157. switchIpsecModalTab('p2');
  2158. } else {
  2159. switchIpsecModalTab('p1');
  2160. }
  2161. }
  2162. function toggleIpsecPskVisibility() {
  2163. const pskInput = document.getElementById('ipsec-modal-psk');
  2164. if (!pskInput) return;
  2165. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2166. }
  2167. function addIpsecLocalSubnet(val = '') {
  2168. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2169. if (!container) return;
  2170. const row = document.createElement('div');
  2171. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2172. row.innerHTML = `
  2173. <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">
  2174. <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>
  2175. `;
  2176. container.appendChild(row);
  2177. }
  2178. function addIpsecRemoteSubnet(val = '') {
  2179. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2180. if (!container) return;
  2181. const row = document.createElement('div');
  2182. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2183. row.innerHTML = `
  2184. <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">
  2185. <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>
  2186. `;
  2187. container.appendChild(row);
  2188. }
  2189. function updateIpsecEspProposalFromPFS(val) {
  2190. const prop = document.getElementById('ipsec-modal-espprop');
  2191. if (!prop) return;
  2192. if (val === 'none') {
  2193. prop.value = 'aes256-sha256,aes128-sha256,default';
  2194. } else {
  2195. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2196. }
  2197. }
  2198. function updateIpsecIkeProposalFromDH(dh) {
  2199. const el = document.getElementById('ipsec-modal-ikeprop');
  2200. if (el) {
  2201. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2202. }
  2203. }
  2204. function safeSetVal(id, val) {
  2205. const el = document.getElementById(id);
  2206. if (el) el.value = val;
  2207. }
  2208. function safeSetChecked(id, val) {
  2209. const el = document.getElementById(id);
  2210. if (el) el.checked = !!val;
  2211. }
  2212. function safeGetVal(id, def = '') {
  2213. const el = document.getElementById(id);
  2214. return el ? el.value : def;
  2215. }
  2216. async function loadIPSec(populateInputs = true) {
  2217. try {
  2218. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2219. const list = await res.json();
  2220. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2221. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2222. const badge = document.getElementById('ipsec-sas-badge');
  2223. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2224. const tbody = document.getElementById('ipsec-table-body');
  2225. const empty = document.getElementById('ipsec-empty');
  2226. if (!tbody) return;
  2227. tbody.innerHTML = '';
  2228. if (state.ipsecTunnels.length === 0) {
  2229. if (empty) empty.classList.remove('hidden');
  2230. } else {
  2231. if (empty) empty.classList.add('hidden');
  2232. state.ipsecTunnels.forEach(c => {
  2233. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2234. const tr = document.createElement('tr');
  2235. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2236. // Local subnets tags
  2237. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2238. 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('');
  2239. // Remote subnets tags
  2240. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2241. 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('');
  2242. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2243. const p2Name = c.phase2_name || `${c.name}_p2`;
  2244. tr.innerHTML = `
  2245. <td class="py-2.5 px-3 text-center">
  2246. ${isEstablished ? `
  2247. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2248. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2249. <span>UP</span>
  2250. </span>
  2251. ` : (c.disabled ? `
  2252. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2253. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2254. <span>DOWN</span>
  2255. </span>
  2256. ` : `
  2257. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2258. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2259. <span>IDLE</span>
  2260. </span>
  2261. `)}
  2262. </td>
  2263. <td class="py-2.5 px-4 font-bold text-white">
  2264. <div class="flex items-center gap-2">
  2265. <span class="text-amber-400">🛡</span>
  2266. <div>
  2267. <div>${escapeHtml(c.name)}</div>
  2268. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2269. </div>
  2270. </div>
  2271. </td>
  2272. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2273. <td class="py-2.5 px-4 font-sans">
  2274. <div class="flex items-center gap-1.5">
  2275. <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>
  2276. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2277. </div>
  2278. </td>
  2279. <td class="py-2.5 px-4">
  2280. <div class="space-y-1">
  2281. <div class="flex items-center flex-wrap gap-1">
  2282. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2283. ${localBadges}
  2284. </div>
  2285. <div class="flex items-center flex-wrap gap-1">
  2286. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2287. ${remoteBadges}
  2288. </div>
  2289. </div>
  2290. </td>
  2291. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2292. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2293. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2294. </div>
  2295. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2296. </td>
  2297. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2298. ${isEstablished ? `
  2299. <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>
  2300. ` : `
  2301. <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>
  2302. `}
  2303. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2304. ${c.disabled ? 'Enable' : 'Disable'}
  2305. </button>
  2306. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2307. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2308. </td>
  2309. `;
  2310. tbody.appendChild(tr);
  2311. });
  2312. }
  2313. } catch (err) {
  2314. console.error('Failed to load IPSec:', err);
  2315. }
  2316. }
  2317. function openAddIPSecModal() {
  2318. const modal = document.getElementById('ipsec-modal');
  2319. if (!modal) return;
  2320. const title = document.getElementById('ipsec-modal-title');
  2321. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2322. // Phase 1 Fields
  2323. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2324. const nameEl = document.getElementById('ipsec-modal-name');
  2325. if (nameEl) nameEl.readOnly = false;
  2326. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2327. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2328. safeSetVal('ipsec-modal-remotegw', '');
  2329. safeSetVal('ipsec-modal-localaddrs', '');
  2330. safeSetVal('ipsec-modal-comments', '');
  2331. safeSetVal('ipsec-modal-psk', '');
  2332. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2333. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2334. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2335. safeSetVal('ipsec-modal-localid', '');
  2336. safeSetVal('ipsec-modal-remoteid', '');
  2337. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2338. // Phase 2 Fields
  2339. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2340. safeSetVal('ipsec-modal-espkeylife', '28800');
  2341. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2342. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2343. safeSetChecked('ipsec-modal-autostart', true);
  2344. safeSetChecked('ipsec-modal-disabled', false);
  2345. // Clear & Populate default dynamic subnets
  2346. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2347. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2348. if (localContainer) {
  2349. localContainer.innerHTML = '';
  2350. addIpsecLocalSubnet('192.168.10.0/24');
  2351. }
  2352. if (remoteContainer) {
  2353. remoteContainer.innerHTML = '';
  2354. addIpsecRemoteSubnet('192.168.20.0/24');
  2355. }
  2356. switchIpsecModalTab('p1');
  2357. modal.classList.remove('hidden');
  2358. }
  2359. function openEditIPSecModal(name) {
  2360. const modal = document.getElementById('ipsec-modal');
  2361. if (!modal) return;
  2362. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2363. if (!conn) return;
  2364. const title = document.getElementById('ipsec-modal-title');
  2365. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2366. // Phase 1 Fields
  2367. safeSetVal('ipsec-modal-name', conn.name);
  2368. const nameEl = document.getElementById('ipsec-modal-name');
  2369. if (nameEl) nameEl.readOnly = true;
  2370. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2371. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2372. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2373. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2374. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2375. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2376. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2377. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2378. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2379. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2380. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2381. // Phase 2 Fields
  2382. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2383. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2384. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2385. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2386. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2387. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2388. // Populate dynamic subnets
  2389. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2390. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2391. if (localContainer) {
  2392. localContainer.innerHTML = '';
  2393. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2394. locals.forEach(s => addIpsecLocalSubnet(s));
  2395. }
  2396. if (remoteContainer) {
  2397. remoteContainer.innerHTML = '';
  2398. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2399. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2400. }
  2401. switchIpsecModalTab('p1');
  2402. modal.classList.remove('hidden');
  2403. }
  2404. function closeAddIPSecModal() {
  2405. const modal = document.getElementById('ipsec-modal');
  2406. if (modal) modal.classList.add('hidden');
  2407. }
  2408. async function submitSaveIPSec(e) {
  2409. if (e) e.preventDefault();
  2410. const name = safeGetVal('ipsec-modal-name').trim();
  2411. if (!name) {
  2412. showToast('Error', 'Tunnel name is required', 'error');
  2413. return;
  2414. }
  2415. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2416. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2417. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2418. const comments = safeGetVal('ipsec-modal-comments').trim();
  2419. const psk = safeGetVal('ipsec-modal-psk');
  2420. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2421. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2422. const localId = safeGetVal('ipsec-modal-localid').trim();
  2423. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2424. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2425. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2426. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2427. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2428. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2429. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2430. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2431. // Scrape dynamic local and remote subnets
  2432. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2433. const localSubnets = [];
  2434. localInputs.forEach(inp => {
  2435. const v = inp.value.trim();
  2436. if (v) localSubnets.push(v);
  2437. });
  2438. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2439. const remoteSubnets = [];
  2440. remoteInputs.forEach(inp => {
  2441. const v = inp.value.trim();
  2442. if (v) remoteSubnets.push(v);
  2443. });
  2444. try {
  2445. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2446. method: 'POST',
  2447. headers: { 'Content-Type': 'application/json' },
  2448. body: JSON.stringify({
  2449. name,
  2450. comment: comments,
  2451. ike_version: ikeVersion,
  2452. local_addrs: localAddrs,
  2453. remote_addrs: remotegw,
  2454. preshared_key: psk,
  2455. ike_proposals: ikeProposals,
  2456. ike_keylife: ikeKeylife,
  2457. local_id: localId,
  2458. remote_id: remoteId,
  2459. dpd: dpd,
  2460. phase2_name: phase2Name,
  2461. esp_proposals: espProposals,
  2462. esp_keylife: espKeylife,
  2463. pfs_group: pfsGroup,
  2464. pfs: pfsGroup !== 'none',
  2465. local_subnets: localSubnets,
  2466. remote_subnets: remoteSubnets,
  2467. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2468. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2469. auto_start: autostart,
  2470. disabled
  2471. })
  2472. });
  2473. if (res.ok) {
  2474. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2475. closeAddIPSecModal();
  2476. loadIPSec(false);
  2477. } else {
  2478. const err = await res.json();
  2479. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2480. }
  2481. } catch (err) {
  2482. showToast('Error', err.message, 'error');
  2483. }
  2484. }
  2485. async function startIPSecTunnel(name) {
  2486. try {
  2487. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2488. if (res.ok) {
  2489. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2490. setTimeout(() => loadIPSec(false), 2000);
  2491. }
  2492. } catch (err) {
  2493. showToast('Error', err.message, 'error');
  2494. }
  2495. }
  2496. async function stopIPSecTunnel(name) {
  2497. try {
  2498. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2499. if (res.ok) {
  2500. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2501. loadIPSec(false);
  2502. }
  2503. } catch (err) {
  2504. showToast('Error', err.message, 'error');
  2505. }
  2506. }
  2507. async function toggleIPSecState(name, enable) {
  2508. try {
  2509. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2510. method: 'POST',
  2511. headers: { 'Content-Type': 'application/json' },
  2512. body: JSON.stringify({ enabled: enable })
  2513. });
  2514. if (res.ok) {
  2515. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2516. loadIPSec(false);
  2517. }
  2518. } catch (err) {
  2519. showToast('Error', err.message, 'error');
  2520. }
  2521. }
  2522. async function deleteIPSecConn(name) {
  2523. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2524. try {
  2525. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2526. if (res.ok) {
  2527. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2528. loadIPSec(false);
  2529. fetchData(false);
  2530. }
  2531. } catch (err) {
  2532. showToast('Error', err.message, 'error');
  2533. }
  2534. }
  2535. // ======================== L2TP Multi-Instance ========================
  2536. async function loadL2TP(populateInputs = true) {
  2537. try {
  2538. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2539. await fetchPPPProfilesList();
  2540. }
  2541. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2542. const list = await res.json();
  2543. state.l2tpList = Array.isArray(list) ? list : [];
  2544. const badge = document.getElementById('l2tp-count-badge');
  2545. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2546. const tbody = document.getElementById('l2tp-table-body');
  2547. const empty = document.getElementById('l2tp-empty');
  2548. if (!tbody) return;
  2549. tbody.innerHTML = '';
  2550. if (state.l2tpList.length === 0) {
  2551. if (empty) empty.classList.remove('hidden');
  2552. } else {
  2553. if (empty) empty.classList.add('hidden');
  2554. state.l2tpList.forEach(inst => {
  2555. const tr = document.createElement('tr');
  2556. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2557. tr.innerHTML = `
  2558. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2559. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2560. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2561. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2562. <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>
  2563. <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>
  2564. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2565. <td class="py-2.5 px-3 text-center">
  2566. <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'}">
  2567. ${inst.default_route ? 'Yes' : 'No'}
  2568. </span>
  2569. </td>
  2570. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2571. ${inst.running ? `
  2572. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2573. ` : `
  2574. <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>
  2575. `}
  2576. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2577. ${inst.disabled ? 'Enable' : 'Disable'}
  2578. </button>
  2579. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2580. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2581. </td>
  2582. `;
  2583. tbody.appendChild(tr);
  2584. });
  2585. }
  2586. } catch (err) {
  2587. console.error('Failed to load L2TP:', err);
  2588. }
  2589. }
  2590. async function openAddL2TPModal() {
  2591. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2592. await fetchPPPProfilesList();
  2593. }
  2594. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2595. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2596. document.getElementById('l2tp-modal-name').readOnly = false;
  2597. document.getElementById('l2tp-modal-server').value = '';
  2598. document.getElementById('l2tp-modal-user').value = '';
  2599. document.getElementById('l2tp-modal-pass').value = '';
  2600. document.getElementById('l2tp-modal-ipsec').value = '';
  2601. document.getElementById('l2tp-modal-defroute').checked = true;
  2602. document.getElementById('l2tp-modal-disabled').checked = false;
  2603. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2604. document.getElementById('l2tp-modal').classList.remove('hidden');
  2605. }
  2606. async function openEditL2TPModal(name) {
  2607. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2608. await fetchPPPProfilesList();
  2609. }
  2610. const inst = (state.l2tpList || []).find(i => i.name === name);
  2611. if (!inst) return;
  2612. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2613. document.getElementById('l2tp-modal-name').value = inst.name;
  2614. document.getElementById('l2tp-modal-name').readOnly = true;
  2615. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2616. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2617. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2618. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2619. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2620. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2621. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2622. document.getElementById('l2tp-modal').classList.remove('hidden');
  2623. }
  2624. function closeL2TPModal() {
  2625. document.getElementById('l2tp-modal').classList.add('hidden');
  2626. }
  2627. async function submitSaveL2TP(e) {
  2628. e.preventDefault();
  2629. const name = document.getElementById('l2tp-modal-name').value.trim();
  2630. const server = document.getElementById('l2tp-modal-server').value.trim();
  2631. const user = document.getElementById('l2tp-modal-user').value.trim();
  2632. const pass = document.getElementById('l2tp-modal-pass').value;
  2633. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2634. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2635. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2636. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2637. try {
  2638. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2639. method: 'POST',
  2640. headers: { 'Content-Type': 'application/json' },
  2641. body: JSON.stringify({
  2642. name,
  2643. connect_to: server,
  2644. username: user,
  2645. password: pass,
  2646. profile: profile,
  2647. ipsec_secret: ipsec,
  2648. default_route: defRoute,
  2649. disabled
  2650. })
  2651. });
  2652. if (res.ok) {
  2653. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2654. closeL2TPModal();
  2655. loadL2TP(false);
  2656. fetchData(false);
  2657. }
  2658. } catch (err) {
  2659. showToast('Error', err.message, 'error');
  2660. }
  2661. }
  2662. async function connectL2TPInstance(name) {
  2663. try {
  2664. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2665. if (res.ok) {
  2666. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2667. setTimeout(() => loadL2TP(false), 2000);
  2668. }
  2669. } catch (err) {
  2670. showToast('Error', err.message, 'error');
  2671. }
  2672. }
  2673. async function disconnectL2TPInstance(name) {
  2674. try {
  2675. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2676. if (res.ok) {
  2677. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2678. loadL2TP(false);
  2679. }
  2680. } catch (err) {
  2681. showToast('Error', err.message, 'error');
  2682. }
  2683. }
  2684. async function toggleL2TPState(name, enable) {
  2685. try {
  2686. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2687. method: 'POST',
  2688. headers: { 'Content-Type': 'application/json' },
  2689. body: JSON.stringify({ enabled: enable })
  2690. });
  2691. if (res.ok) {
  2692. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2693. loadL2TP(false);
  2694. }
  2695. } catch (err) {
  2696. showToast('Error', err.message, 'error');
  2697. }
  2698. }
  2699. async function deleteL2TPInstance(name) {
  2700. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2701. try {
  2702. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2703. if (res.ok) {
  2704. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2705. loadL2TP(false);
  2706. fetchData(false);
  2707. }
  2708. } catch (err) {
  2709. showToast('Error', err.message, 'error');
  2710. }
  2711. }
  2712. // ======================== PPTP Multi-Instance ========================
  2713. async function loadPPTP(populateInputs = true) {
  2714. try {
  2715. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2716. await fetchPPPProfilesList();
  2717. }
  2718. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2719. const list = await res.json();
  2720. state.pptpList = Array.isArray(list) ? list : [];
  2721. const badge = document.getElementById('pptp-count-badge');
  2722. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2723. const tbody = document.getElementById('pptp-table-body');
  2724. const empty = document.getElementById('pptp-empty');
  2725. if (!tbody) return;
  2726. tbody.innerHTML = '';
  2727. if (state.pptpList.length === 0) {
  2728. if (empty) empty.classList.remove('hidden');
  2729. } else {
  2730. if (empty) empty.classList.add('hidden');
  2731. state.pptpList.forEach(inst => {
  2732. const tr = document.createElement('tr');
  2733. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2734. tr.innerHTML = `
  2735. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2736. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2737. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2738. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2739. <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>
  2740. <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>
  2741. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2742. <td class="py-2.5 px-3 text-center">
  2743. <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'}">
  2744. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2745. </span>
  2746. </td>
  2747. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2748. ${inst.running ? `
  2749. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2750. ` : `
  2751. <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>
  2752. `}
  2753. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2754. ${inst.disabled ? 'Enable' : 'Disable'}
  2755. </button>
  2756. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2757. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2758. </td>
  2759. `;
  2760. tbody.appendChild(tr);
  2761. });
  2762. }
  2763. } catch (err) {
  2764. console.error('Failed to load PPTP:', err);
  2765. }
  2766. }
  2767. async function openAddPPTPModal() {
  2768. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2769. await fetchPPPProfilesList();
  2770. }
  2771. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2772. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2773. document.getElementById('pptp-modal-name').readOnly = false;
  2774. document.getElementById('pptp-modal-server').value = '';
  2775. document.getElementById('pptp-modal-user').value = '';
  2776. document.getElementById('pptp-modal-pass').value = '';
  2777. document.getElementById('pptp-modal-mppe').checked = true;
  2778. document.getElementById('pptp-modal-defroute').checked = true;
  2779. document.getElementById('pptp-modal-disabled').checked = false;
  2780. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2781. document.getElementById('pptp-modal').classList.remove('hidden');
  2782. }
  2783. async function openEditPPTPModal(name) {
  2784. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2785. await fetchPPPProfilesList();
  2786. }
  2787. const inst = (state.pptpList || []).find(i => i.name === name);
  2788. if (!inst) return;
  2789. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2790. document.getElementById('pptp-modal-name').value = inst.name;
  2791. document.getElementById('pptp-modal-name').readOnly = true;
  2792. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2793. document.getElementById('pptp-modal-user').value = inst.username || '';
  2794. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2795. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2796. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2797. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2798. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2799. document.getElementById('pptp-modal').classList.remove('hidden');
  2800. }
  2801. function closePPTPModal() {
  2802. document.getElementById('pptp-modal').classList.add('hidden');
  2803. }
  2804. async function submitSavePPTP(e) {
  2805. e.preventDefault();
  2806. const name = document.getElementById('pptp-modal-name').value.trim();
  2807. const server = document.getElementById('pptp-modal-server').value.trim();
  2808. const user = document.getElementById('pptp-modal-user').value.trim();
  2809. const pass = document.getElementById('pptp-modal-pass').value;
  2810. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2811. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2812. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2813. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2814. try {
  2815. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2816. method: 'POST',
  2817. headers: { 'Content-Type': 'application/json' },
  2818. body: JSON.stringify({
  2819. name,
  2820. connect_to: server,
  2821. username: user,
  2822. password: pass,
  2823. profile: profile,
  2824. require_mppe: mppe,
  2825. default_route: defRoute,
  2826. auto_reconnect: true,
  2827. disabled
  2828. })
  2829. });
  2830. if (res.ok) {
  2831. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2832. closePPTPModal();
  2833. loadPPTP(false);
  2834. fetchData(false);
  2835. }
  2836. } catch (err) {
  2837. showToast('Error', err.message, 'error');
  2838. }
  2839. }
  2840. async function connectPPTPInstance(name) {
  2841. try {
  2842. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2843. if (res.ok) {
  2844. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2845. setTimeout(() => loadPPTP(false), 2000);
  2846. }
  2847. } catch (err) {
  2848. showToast('Error', err.message, 'error');
  2849. }
  2850. }
  2851. async function disconnectPPTPInstance(name) {
  2852. try {
  2853. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2854. if (res.ok) {
  2855. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2856. loadPPTP(false);
  2857. }
  2858. } catch (err) {
  2859. showToast('Error', err.message, 'error');
  2860. }
  2861. }
  2862. async function togglePPTPState(name, enable) {
  2863. try {
  2864. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2865. method: 'POST',
  2866. headers: { 'Content-Type': 'application/json' },
  2867. body: JSON.stringify({ enabled: enable })
  2868. });
  2869. if (res.ok) {
  2870. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2871. loadPPTP(false);
  2872. }
  2873. } catch (err) {
  2874. showToast('Error', err.message, 'error');
  2875. }
  2876. }
  2877. async function deletePPTPInstance(name) {
  2878. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2879. try {
  2880. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2881. if (res.ok) {
  2882. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2883. loadPPTP(false);
  2884. fetchData(false);
  2885. }
  2886. } catch (err) {
  2887. showToast('Error', err.message, 'error');
  2888. }
  2889. }
  2890. // ---------------- Modal & Helper Functions ----------------
  2891. function openVlanModal(defaultParent = '') {
  2892. const select = document.getElementById('vlan-parent');
  2893. select.innerHTML = '';
  2894. const allIfaces = state.interfaces || [];
  2895. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2896. if (eligible.length === 0) {
  2897. const opt = document.createElement('option');
  2898. opt.value = '';
  2899. opt.innerText = 'No VLAN-capable interfaces available';
  2900. select.appendChild(opt);
  2901. } else {
  2902. eligible.forEach(i => {
  2903. const opt = document.createElement('option');
  2904. opt.value = i.name;
  2905. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2906. if (i.name === defaultParent) opt.selected = true;
  2907. select.appendChild(opt);
  2908. });
  2909. }
  2910. document.getElementById('vlan-id').value = '';
  2911. document.getElementById('vlan-name').value = '';
  2912. document.getElementById('vlan-ip').value = '';
  2913. document.getElementById('vlan-desc').value = '';
  2914. populateRoleSelects('LAN');
  2915. autoSuggestVlanName();
  2916. document.getElementById('vlan-modal').classList.remove('hidden');
  2917. }
  2918. function closeVlanModal() {
  2919. document.getElementById('vlan-modal').classList.add('hidden');
  2920. }
  2921. function autoSuggestVlanName() {
  2922. const parent = document.getElementById('vlan-parent').value;
  2923. if (!parent) return;
  2924. const id = document.getElementById('vlan-id').value;
  2925. const nameInput = document.getElementById('vlan-name');
  2926. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2927. }
  2928. function setSubnetPreset(cidr) {
  2929. const ipInput = document.getElementById('vlan-ip');
  2930. const id = document.getElementById('vlan-id').value || '10';
  2931. ipInput.value = `192.168.${id}.1${cidr}`;
  2932. }
  2933. async function submitCreateVlan(e) {
  2934. e.preventDefault();
  2935. const btn = document.getElementById('vlan-submit-btn');
  2936. btn.disabled = true;
  2937. btn.innerText = 'Creating...';
  2938. const parent = document.getElementById('vlan-parent').value;
  2939. if (!parent) {
  2940. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2941. btn.disabled = false;
  2942. btn.innerText = 'Create VLAN';
  2943. return;
  2944. }
  2945. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2946. const name = document.getElementById('vlan-name').value.trim();
  2947. const ip = document.getElementById('vlan-ip').value.trim();
  2948. const role = document.getElementById('vlan-role').value;
  2949. const desc = document.getElementById('vlan-desc').value.trim();
  2950. try {
  2951. const res = await fetch(`${API_BASE}/vlans`, {
  2952. method: 'POST',
  2953. headers: { 'Content-Type': 'application/json' },
  2954. body: JSON.stringify({
  2955. parent_name: parent,
  2956. vlan_id: id,
  2957. name: name,
  2958. ip_address: ip,
  2959. role: role,
  2960. description: desc,
  2961. mtu: 1500,
  2962. auto_up: true
  2963. })
  2964. });
  2965. const data = await res.json();
  2966. if (res.ok) {
  2967. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2968. state.expandedParents.add(parent);
  2969. closeVlanModal();
  2970. await fetchData(true);
  2971. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2972. } else {
  2973. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2974. }
  2975. } catch (err) {
  2976. showToast('Error', err.message, 'error');
  2977. } finally {
  2978. btn.disabled = false;
  2979. btn.innerText = 'Create VLAN';
  2980. }
  2981. }
  2982. async function confirmDeleteVlan(name) {
  2983. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2984. try {
  2985. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2986. if (res.ok) {
  2987. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2988. closeIfaceModal();
  2989. fetchData(true);
  2990. }
  2991. } catch (err) {
  2992. showToast('Error', err.message, 'error');
  2993. }
  2994. }
  2995. function openIfaceModal(name) {
  2996. const iface = (state.interfaces || []).find(i => i.name === name);
  2997. if (!iface) return;
  2998. state.currentModalIface = iface.name;
  2999. document.getElementById('modal-iface-name').innerText = iface.name;
  3000. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3001. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3002. populateRoleSelects(iface.role || 'LAN');
  3003. document.getElementById('modal-iface-desc').value = iface.description || '';
  3004. const nameInput = document.getElementById('modal-iface-new-name');
  3005. const renameBtn = document.getElementById('modal-btn-rename');
  3006. const renameHelp = document.getElementById('modal-iface-rename-help');
  3007. if (nameInput) {
  3008. nameInput.value = iface.name;
  3009. if (iface.name === 'lo' || iface.type === 'loopback') {
  3010. nameInput.disabled = true;
  3011. if (renameBtn) renameBtn.disabled = true;
  3012. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3013. } else {
  3014. nameInput.disabled = false;
  3015. if (renameBtn) renameBtn.disabled = false;
  3016. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3017. }
  3018. }
  3019. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3020. if (iface.is_vlan) {
  3021. delBtn.classList.remove('hidden');
  3022. } else {
  3023. delBtn.classList.add('hidden');
  3024. }
  3025. renderModalIPs(iface);
  3026. document.getElementById('iface-modal').classList.remove('hidden');
  3027. }
  3028. function renderModalIPs(iface) {
  3029. const container = document.getElementById('modal-ip-list');
  3030. container.innerHTML = '';
  3031. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3032. if (addrs.length === 0) {
  3033. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3034. return;
  3035. }
  3036. addrs.forEach(addr => {
  3037. const row = document.createElement('div');
  3038. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3039. row.innerHTML = `
  3040. <span class="text-white">${addr}</span>
  3041. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3042. `;
  3043. container.appendChild(row);
  3044. });
  3045. }
  3046. function closeIfaceModal() {
  3047. document.getElementById('iface-modal').classList.add('hidden');
  3048. state.currentModalIface = null;
  3049. }
  3050. async function setIfaceState(name, newState) {
  3051. const target = name || state.currentModalIface;
  3052. if (!target) return;
  3053. await toggleInterfaceState(target, newState);
  3054. const updated = (state.interfaces || []).find(i => i.name === target);
  3055. if (updated) openIfaceModal(target);
  3056. }
  3057. async function applyMTU() {
  3058. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3059. try {
  3060. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3061. method: 'POST',
  3062. headers: { 'Content-Type': 'application/json' },
  3063. body: JSON.stringify({ mtu })
  3064. });
  3065. if (res.ok) {
  3066. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3067. fetchData(false);
  3068. }
  3069. } catch (err) {
  3070. showToast('Error', err.message, 'error');
  3071. }
  3072. }
  3073. async function addInterfaceIP() {
  3074. const ip = document.getElementById('modal-new-ip').value.trim();
  3075. if (!ip) return;
  3076. try {
  3077. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3078. method: 'POST',
  3079. headers: { 'Content-Type': 'application/json' },
  3080. body: JSON.stringify({ ip })
  3081. });
  3082. if (res.ok) {
  3083. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3084. document.getElementById('modal-new-ip').value = '';
  3085. await fetchData(false);
  3086. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3087. if (iface) renderModalIPs(iface);
  3088. } else {
  3089. const err = await res.json();
  3090. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3091. }
  3092. } catch (err) {
  3093. showToast('Error', err.message, 'error');
  3094. }
  3095. }
  3096. async function removeInterfaceIP(ip) {
  3097. if (!confirm(`Remove IP ${ip}?`)) return;
  3098. try {
  3099. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3100. method: 'DELETE',
  3101. headers: { 'Content-Type': 'application/json' },
  3102. body: JSON.stringify({ ip })
  3103. });
  3104. if (res.ok) {
  3105. showToast('IP Removed', `Removed ${ip}`, 'success');
  3106. await fetchData(false);
  3107. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3108. if (iface) renderModalIPs(iface);
  3109. }
  3110. } catch (err) {
  3111. showToast('Error', err.message, 'error');
  3112. }
  3113. }
  3114. async function renameInterface() {
  3115. const oldName = state.currentModalIface;
  3116. const newNameInput = document.getElementById('modal-iface-new-name');
  3117. const newName = (newNameInput?.value || '').trim();
  3118. if (!oldName) return;
  3119. if (!newName) {
  3120. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3121. return;
  3122. }
  3123. if (newName === oldName) {
  3124. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3125. return;
  3126. }
  3127. if (newName.length > 15) {
  3128. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3129. return;
  3130. }
  3131. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3132. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3133. return;
  3134. }
  3135. const renameBtn = document.getElementById('modal-btn-rename');
  3136. if (renameBtn) {
  3137. renameBtn.disabled = true;
  3138. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3139. }
  3140. try {
  3141. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3142. method: 'POST',
  3143. headers: { 'Content-Type': 'application/json' },
  3144. body: JSON.stringify({ new_name: newName })
  3145. });
  3146. const data = await res.json();
  3147. if (!res.ok) {
  3148. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3149. return;
  3150. }
  3151. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3152. state.currentModalIface = newName;
  3153. document.getElementById('modal-iface-name').innerText = newName;
  3154. // Refresh application state
  3155. await fetchData(false);
  3156. const updated = (state.interfaces || []).find(i => i.name === newName);
  3157. if (updated) {
  3158. openIfaceModal(newName);
  3159. } else {
  3160. closeIfaceModal();
  3161. }
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. } finally {
  3165. if (renameBtn) {
  3166. renameBtn.disabled = false;
  3167. renameBtn.innerHTML = `
  3168. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3169. <span>Rename</span>
  3170. `;
  3171. }
  3172. }
  3173. }
  3174. async function saveInterfaceMetadata() {
  3175. const oldName = state.currentModalIface;
  3176. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3177. const role = document.getElementById('modal-iface-role').value;
  3178. const desc = document.getElementById('modal-iface-desc').value.trim();
  3179. let targetName = oldName;
  3180. // If user changed the name before clicking Save Changes, execute rename first
  3181. if (newName && newName !== oldName && oldName !== 'lo') {
  3182. try {
  3183. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3184. method: 'POST',
  3185. headers: { 'Content-Type': 'application/json' },
  3186. body: JSON.stringify({ new_name: newName })
  3187. });
  3188. const data = await renameRes.json();
  3189. if (!renameRes.ok) {
  3190. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3191. return;
  3192. }
  3193. targetName = newName;
  3194. state.currentModalIface = newName;
  3195. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3196. } catch (err) {
  3197. showToast('Error', err.message, 'error');
  3198. return;
  3199. }
  3200. }
  3201. try {
  3202. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3203. method: 'POST',
  3204. headers: { 'Content-Type': 'application/json' },
  3205. body: JSON.stringify({ role, description: desc })
  3206. });
  3207. if (res.ok) {
  3208. showToast('Saved', 'Interface configuration updated', 'success');
  3209. closeIfaceModal();
  3210. fetchData(false);
  3211. } else {
  3212. const err = await res.json();
  3213. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3214. }
  3215. } catch (err) {
  3216. showToast('Error', err.message, 'error');
  3217. }
  3218. }
  3219. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3220. state.fwSubTab = 'filter';
  3221. state.routesSubTab = 'routes';
  3222. function renderRuleFlag(disabled, hasComment) {
  3223. let flags = '';
  3224. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3225. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3226. return flags || '<span class="text-slate-600">-</span>';
  3227. }
  3228. function renderActionBadge(action) {
  3229. const act = (action || '').toLowerCase();
  3230. let color = 'bg-slate-800 text-slate-300';
  3231. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3232. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3233. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3234. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3235. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3236. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3237. }
  3238. function switchFWSubTab(tab) {
  3239. state.fwSubTab = tab;
  3240. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3241. tabs.forEach(t => {
  3242. const panel = document.getElementById(`fw-subtab-${t}`);
  3243. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3244. if (panel) {
  3245. if (t === tab) panel.classList.remove('hidden');
  3246. else panel.classList.add('hidden');
  3247. }
  3248. if (btn) {
  3249. if (t === tab) {
  3250. 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';
  3251. } else {
  3252. 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';
  3253. }
  3254. }
  3255. });
  3256. const addBtn = document.getElementById('fw-primary-add-btn');
  3257. if (addBtn) {
  3258. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3259. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3260. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3261. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3262. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3263. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3264. }
  3265. if (tab === 'geo') loadGeoIP();
  3266. if (tab === 'connections') loadConnections();
  3267. setTimeout(initTableSorting, 50);
  3268. }
  3269. function openCurrentFWModal() {
  3270. if (state.fwSubTab === 'filter') openAddFilterModal();
  3271. else if (state.fwSubTab === 'nat') openAddNATModal();
  3272. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3273. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3274. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3275. else if (state.fwSubTab === 'connections') loadConnections();
  3276. }
  3277. async function loadFirewall(populateDropdowns = true) {
  3278. try {
  3279. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3280. fetch(`${API_BASE}/firewall/summary`),
  3281. fetch(`${API_BASE}/firewall/filter`),
  3282. fetch(`${API_BASE}/firewall/nat`),
  3283. fetch(`${API_BASE}/firewall/mangle`),
  3284. fetch(`${API_BASE}/firewall/address-lists`),
  3285. fetch(`${API_BASE}/firewall/geoip/status`),
  3286. fetch(`${API_BASE}/firewall/geoip/countries`)
  3287. ]);
  3288. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3289. if (filterRes.ok) state.filterRules = await filterRes.json();
  3290. if (natRes.ok) state.natRules = await natRes.json();
  3291. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3292. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3293. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3294. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3295. // Badges
  3296. const bFilter = document.getElementById('fw-badge-filter');
  3297. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3298. const bNat = document.getElementById('fw-badge-nat');
  3299. if (bNat) bNat.innerText = (state.natRules || []).length;
  3300. const bMangle = document.getElementById('fw-badge-mangle');
  3301. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3302. const bAddr = document.getElementById('fw-badge-addrlist');
  3303. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3304. const bGeo = document.getElementById('fw-badge-geo');
  3305. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3306. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3307. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3308. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3309. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3310. const tbodyFilter = document.getElementById('filter-rules-table-body');
  3311. if (tbodyFilter && (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter)) {
  3312. tbodyFilter.dataset.sig = sigFilter;
  3313. renderFilterRules();
  3314. }
  3315. const tbodyNat = document.getElementById('nat-rules-table-body');
  3316. if (tbodyNat && (populateDropdowns || tbodyNat.dataset.sig !== sigNat)) {
  3317. tbodyNat.dataset.sig = sigNat;
  3318. renderNATRules();
  3319. }
  3320. const tbodyMangle = document.getElementById('mangle-rules-table-body');
  3321. if (tbodyMangle && (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle)) {
  3322. tbodyMangle.dataset.sig = sigMangle;
  3323. renderMangleRules();
  3324. }
  3325. const tbodyAddr = document.getElementById('addr-list-table-body');
  3326. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3327. tbodyAddr.dataset.sig = sigAddr;
  3328. renderAddressLists();
  3329. }
  3330. renderGeoCountries();
  3331. if (state.fwSubTab === 'connections') {
  3332. loadConnections();
  3333. }
  3334. } catch (err) {
  3335. console.error('Failed to load firewall:', err);
  3336. }
  3337. }
  3338. // ----------------- Filter Rules -----------------
  3339. function renderFilterRules() {
  3340. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3341. const tbody = document.getElementById('filter-table-body');
  3342. const empty = document.getElementById('filter-empty');
  3343. if (!tbody) return;
  3344. tbody.innerHTML = '';
  3345. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3346. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3347. if (rules.length === 0) {
  3348. empty?.classList.remove('hidden');
  3349. return;
  3350. }
  3351. empty?.classList.add('hidden');
  3352. rules.forEach((r, idx) => {
  3353. const tr = document.createElement('tr');
  3354. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3355. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3356. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3357. let actionExtra = '';
  3358. if (r.action === 'reject') {
  3359. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3360. } else if (r.action === 'jump') {
  3361. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3362. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3363. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3364. } else if (r.action === 'log' && r.log_prefix) {
  3365. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3366. }
  3367. tr.innerHTML = `
  3368. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3369. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3370. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3371. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3372. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3373. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3374. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3375. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3376. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3377. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3378. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3379. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3380. </td>
  3381. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3382. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3383. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3384. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3385. <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>
  3386. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3387. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3388. </td>
  3389. `;
  3390. tbody.appendChild(tr);
  3391. });
  3392. }
  3393. function formatTarget(addr, list, geo) {
  3394. const parts = [];
  3395. if (addr) parts.push(`<span>${addr}</span>`);
  3396. if (list) {
  3397. const inv = list.startsWith('!') ? '!' : '';
  3398. const clean = list.replace(/^!/, '');
  3399. 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>`);
  3400. }
  3401. if (geo) {
  3402. const inv = geo.startsWith('!') ? '!' : '';
  3403. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3404. 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>`);
  3405. }
  3406. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3407. return parts.join(' ');
  3408. }
  3409. function populateInterfaceSelect(selectId, currentVal = '') {
  3410. const sel = document.getElementById(selectId);
  3411. if (!sel) return;
  3412. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3413. (state.interfaces || []).forEach(i => {
  3414. const opt = document.createElement('option');
  3415. opt.value = i.name;
  3416. opt.innerText = `${i.name} (${i.role || i.type})`;
  3417. if (i.name === currentVal) opt.selected = true;
  3418. sel.appendChild(opt);
  3419. });
  3420. }
  3421. function populateAddressListSelect(selectId, currentVal = '') {
  3422. const sel = document.getElementById(selectId);
  3423. if (!sel) return;
  3424. sel.innerHTML = '<option value="">(None)</option>';
  3425. const cleanVal = (currentVal || '').replace(/^!/, '');
  3426. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3427. customNames.forEach(name => {
  3428. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3429. const opt = document.createElement('option');
  3430. opt.value = name;
  3431. opt.innerText = `${name} (${count} entries)`;
  3432. if (name === cleanVal) opt.selected = true;
  3433. sel.appendChild(opt);
  3434. });
  3435. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3436. const opt = document.createElement('option');
  3437. opt.value = cleanVal;
  3438. opt.innerText = cleanVal;
  3439. opt.selected = true;
  3440. sel.appendChild(opt);
  3441. }
  3442. populateCommonAddrListDatalist();
  3443. }
  3444. function populateCommonAddrListDatalist() {
  3445. const dl = document.getElementById('fw-addrlist-datalist');
  3446. if (!dl) return;
  3447. dl.innerHTML = '';
  3448. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3449. names.forEach(name => {
  3450. const opt = document.createElement('option');
  3451. opt.value = name;
  3452. dl.appendChild(opt);
  3453. });
  3454. }
  3455. function populateGeoIPSelect(selectId, currentVal = '') {
  3456. const sel = document.getElementById(selectId);
  3457. if (!sel) return;
  3458. sel.innerHTML = '<option value="">(None)</option>';
  3459. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3460. // Presets optgroup
  3461. const grpPresets = document.createElement('optgroup');
  3462. grpPresets.label = '⚡ Regional Presets';
  3463. const presets = [
  3464. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3465. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3466. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3467. ];
  3468. presets.forEach(p => {
  3469. const opt = document.createElement('option');
  3470. opt.value = p.code;
  3471. opt.innerText = p.label;
  3472. if (p.code === cleanVal) opt.selected = true;
  3473. grpPresets.appendChild(opt);
  3474. });
  3475. sel.appendChild(grpPresets);
  3476. // All Countries optgroup
  3477. const grpCountries = document.createElement('optgroup');
  3478. grpCountries.label = '🌍 All Countries';
  3479. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3480. countries.forEach(c => {
  3481. const opt = document.createElement('option');
  3482. opt.value = c.code;
  3483. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3484. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3485. if (c.code === cleanVal) opt.selected = true;
  3486. grpCountries.appendChild(opt);
  3487. });
  3488. sel.appendChild(grpCountries);
  3489. }
  3490. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3491. function switchFwRuleTab(tab) {
  3492. state.activeFwRuleTab = tab;
  3493. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3494. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3495. btn.classList.add('text-slate-400', 'border-transparent');
  3496. });
  3497. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3498. if (activeBtn) {
  3499. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3500. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3501. }
  3502. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3503. const activePane = document.getElementById(`fw-pane-${tab}`);
  3504. if (activePane) activePane.classList.remove('hidden');
  3505. if (tab === 'statistics') {
  3506. startFwStatPolling();
  3507. } else {
  3508. stopFwStatPolling();
  3509. }
  3510. }
  3511. function toggleFwField(fieldKey, expand) {
  3512. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3513. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3514. if (!plusBtn || !fieldBox) return;
  3515. if (expand) {
  3516. plusBtn.classList.add('hidden');
  3517. fieldBox.classList.remove('hidden');
  3518. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3519. if (valInput) valInput.focus();
  3520. } else {
  3521. fieldBox.classList.add('hidden');
  3522. plusBtn.classList.remove('hidden');
  3523. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3524. if (valInput) {
  3525. if (valInput.tagName === 'SELECT') {
  3526. valInput.selectedIndex = 0;
  3527. } else {
  3528. valInput.value = '';
  3529. }
  3530. }
  3531. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3532. if (invInput) invInput.checked = false;
  3533. if (fieldKey === 'cs') {
  3534. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3535. const el = document.getElementById(id);
  3536. if (el) el.checked = false;
  3537. });
  3538. }
  3539. if (fieldKey === 'natstate') {
  3540. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3541. const el = document.getElementById(id);
  3542. if (el) el.checked = false;
  3543. });
  3544. }
  3545. if (fieldKey === 'days') {
  3546. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3547. const el = document.getElementById(`fw-day-${d}`);
  3548. if (el) el.checked = true;
  3549. });
  3550. }
  3551. }
  3552. }
  3553. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3554. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3555. toggleFwField(fieldKey, true);
  3556. let strVal = String(value);
  3557. if (hasInvert) {
  3558. const inv = strVal.startsWith('!');
  3559. if (inv) strVal = strVal.slice(1);
  3560. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3561. if (invEl) invEl.checked = inv;
  3562. }
  3563. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3564. if (valEl) valEl.value = strVal;
  3565. } else {
  3566. toggleFwField(fieldKey, false);
  3567. }
  3568. }
  3569. function getFwFieldVal(fieldKey, hasInvert = false) {
  3570. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3571. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3572. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3573. let v = valEl ? valEl.value.trim() : '';
  3574. if (!v) return '';
  3575. if (hasInvert) {
  3576. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3577. if (invEl && invEl.checked) {
  3578. v = '!' + v.replace(/^!/, '');
  3579. }
  3580. }
  3581. return v;
  3582. }
  3583. function toggleMaximizeFilterModal() {
  3584. const win = document.getElementById('filter-modal-window');
  3585. if (!win) return;
  3586. if (win.classList.contains('max-w-[720px]')) {
  3587. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3588. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3589. } else {
  3590. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3591. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3592. }
  3593. }
  3594. function openAddFilterModal() {
  3595. switchFwRuleTab('general');
  3596. const badge = document.getElementById('fw-modal-badge');
  3597. if (badge) badge.innerText = 'New...';
  3598. document.getElementById('filter-modal-id').value = '';
  3599. document.getElementById('filter-modal-enabled').checked = true;
  3600. document.getElementById('filter-modal-comment').value = '';
  3601. document.getElementById('filter-modal-chain').value = 'forward';
  3602. document.getElementById('filter-modal-action').value = 'accept';
  3603. document.getElementById('filter-modal-log').checked = false;
  3604. populateInterfaceSelect('fw-val-iniface');
  3605. populateInterfaceSelect('fw-val-outiface');
  3606. populateAddressListSelect('fw-val-srclist');
  3607. populateAddressListSelect('fw-val-dstlist');
  3608. populateGeoIPSelect('fw-val-srcgeo');
  3609. populateGeoIPSelect('fw-val-dstgeo');
  3610. const allFieldKeys = [
  3611. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3612. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3613. 'routingmark', 'conntype', 'cs', 'natstate',
  3614. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3615. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3616. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3617. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3618. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3619. ];
  3620. allFieldKeys.forEach(k => toggleFwField(k, false));
  3621. resetCurrentRuleCounters();
  3622. toggleFilterActionFields();
  3623. document.getElementById('filter-modal').classList.remove('hidden');
  3624. }
  3625. function openEditFilterModal(id) {
  3626. const r = (state.filterRules || []).find(rule => rule.id === id);
  3627. if (!r) return;
  3628. switchFwRuleTab('general');
  3629. const badge = document.getElementById('fw-modal-badge');
  3630. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3631. document.getElementById('filter-modal-id').value = r.id;
  3632. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3633. document.getElementById('filter-modal-comment').value = r.comment || '';
  3634. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3635. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3636. document.getElementById('filter-modal-log').checked = !!r.log;
  3637. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3638. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3639. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3640. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3641. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3642. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3643. setFwFieldVal('src', r.src_address, true);
  3644. setFwFieldVal('dst', r.dst_address, true);
  3645. setFwFieldVal('srclist', r.src_address_list, true);
  3646. setFwFieldVal('dstlist', r.dst_address_list, true);
  3647. setFwFieldVal('srcgeo', r.src_geoip, true);
  3648. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3649. if (r.protocol && r.protocol !== 'all') {
  3650. setFwFieldVal('proto', r.protocol, true);
  3651. } else {
  3652. toggleFwField('proto', false);
  3653. }
  3654. setFwFieldVal('sport', r.src_port, true);
  3655. setFwFieldVal('dport', r.dst_port, true);
  3656. setFwFieldVal('anyport', r.any_port, true);
  3657. setFwFieldVal('iniface', r.in_interface, true);
  3658. setFwFieldVal('outiface', r.out_interface, true);
  3659. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3660. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3661. setFwFieldVal('pktmark', r.packet_mark, true);
  3662. setFwFieldVal('connmark', r.connection_mark, true);
  3663. setFwFieldVal('routingmark', r.routing_mark, true);
  3664. setFwFieldVal('conntype', r.connection_type, false);
  3665. const states = r.connection_state || [];
  3666. if (states.length > 0) {
  3667. toggleFwField('cs', true);
  3668. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3669. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3670. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3671. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3672. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3673. } else {
  3674. toggleFwField('cs', false);
  3675. }
  3676. const natStates = r.connection_nat_state || [];
  3677. if (natStates.length > 0) {
  3678. toggleFwField('natstate', true);
  3679. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3680. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3681. } else {
  3682. toggleFwField('natstate', false);
  3683. }
  3684. // Advanced tab fields
  3685. setFwFieldVal('layer7', r.layer7_protocol, false);
  3686. setFwFieldVal('content', r.content, false);
  3687. setFwFieldVal('connbytes', r.connection_bytes, false);
  3688. setFwFieldVal('connrate', r.connection_rate, false);
  3689. setFwFieldVal('pcc', r.pcc, false);
  3690. setFwFieldVal('srcmac', r.src_mac_address, true);
  3691. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3692. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3693. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3694. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3695. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3696. setFwFieldVal('tlshost', r.tls_host, false);
  3697. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3698. setFwFieldVal('priority', r.priority, false);
  3699. setFwFieldVal('dscp', r.dscp, false);
  3700. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3701. if (r.tos) {
  3702. const tosEl = document.getElementById('fw-val-tos');
  3703. if (tosEl) tosEl.value = r.tos;
  3704. }
  3705. setFwFieldVal('pktsize', r.packet_size, false);
  3706. setFwFieldVal('random', r.random, false);
  3707. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3708. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3709. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3710. setFwFieldVal('ttl', r.ttl, false);
  3711. // Extra tab fields
  3712. setFwFieldVal('time', r.time, false);
  3713. if (r.days) {
  3714. toggleFwField('days', true);
  3715. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3716. const chk = document.getElementById(`fw-day-${d}`);
  3717. if (chk) chk.checked = r.days.includes(d);
  3718. });
  3719. } else {
  3720. toggleFwField('days', false);
  3721. }
  3722. setFwFieldVal('limit', r.limit, false);
  3723. setFwFieldVal('dstlimit', r.dst_limit, false);
  3724. setFwFieldVal('psd', r.psd, false);
  3725. // Action fields
  3726. if (r.reject_with) {
  3727. const rwEl = document.getElementById('filter-modal-rejectwith');
  3728. if (rwEl) rwEl.value = r.reject_with;
  3729. }
  3730. if (r.jump_target) {
  3731. const jtEl = document.getElementById('filter-modal-jumptarget');
  3732. if (jtEl) jtEl.value = r.jump_target;
  3733. }
  3734. if (r.address_list) {
  3735. const alEl = document.getElementById('filter-modal-action-addrlist');
  3736. if (alEl) alEl.value = r.address_list;
  3737. }
  3738. if (r.address_list_timeout) {
  3739. const toEl = document.getElementById('filter-modal-action-timeout');
  3740. if (toEl) toEl.value = r.address_list_timeout;
  3741. }
  3742. setFwFieldVal('logprefix', r.log_prefix, false);
  3743. // Statistics
  3744. const bEl = document.getElementById('fw-stat-bytes');
  3745. const pEl = document.getElementById('fw-stat-packets');
  3746. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3747. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3748. state.fwLastBytes = r.bytes || 0;
  3749. state.fwLastPackets = r.packets || 0;
  3750. state.fwLastTimestamp = Date.now();
  3751. state.fwStatRateHistory = new Array(30).fill(0);
  3752. state.fwStatPktHistory = new Array(30).fill(0);
  3753. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3754. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3755. toggleFilterActionFields();
  3756. document.getElementById('filter-modal').classList.remove('hidden');
  3757. }
  3758. function closeFilterModal() {
  3759. stopFwStatPolling();
  3760. document.getElementById('filter-modal').classList.add('hidden');
  3761. }
  3762. function toggleFilterActionFields() {
  3763. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3764. const rejectBox = document.getElementById('filter-action-reject-box');
  3765. const jumpBox = document.getElementById('filter-action-jump-box');
  3766. const addrBox = document.getElementById('filter-action-addrlist-box');
  3767. if (rejectBox) {
  3768. if (act === 'reject') rejectBox.classList.remove('hidden');
  3769. else rejectBox.classList.add('hidden');
  3770. }
  3771. if (jumpBox) {
  3772. if (act === 'jump') jumpBox.classList.remove('hidden');
  3773. else jumpBox.classList.add('hidden');
  3774. }
  3775. if (addrBox) {
  3776. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3777. addrBox.classList.remove('hidden');
  3778. } else {
  3779. addrBox.classList.add('hidden');
  3780. }
  3781. }
  3782. if (act === 'log') {
  3783. const logEl = document.getElementById('filter-modal-log');
  3784. if (logEl) logEl.checked = true;
  3785. toggleFwField('logprefix', true);
  3786. }
  3787. }
  3788. function toggleFwLogPrefix() {
  3789. const isLog = document.getElementById('filter-modal-log')?.checked;
  3790. toggleFwField('logprefix', !!isLog);
  3791. }
  3792. function copyFilterRule() {
  3793. document.getElementById('filter-modal-id').value = '';
  3794. const badge = document.getElementById('fw-modal-badge');
  3795. if (badge) badge.innerText = 'New...';
  3796. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3797. }
  3798. function resetCurrentRuleCounters() {
  3799. state.fwStatRateHistory = new Array(30).fill(0);
  3800. state.fwStatPktHistory = new Array(30).fill(0);
  3801. state.fwLastBytes = 0;
  3802. state.fwLastPackets = 0;
  3803. state.fwLastTimestamp = Date.now();
  3804. const bEl = document.getElementById('fw-stat-bytes');
  3805. const pEl = document.getElementById('fw-stat-packets');
  3806. const rEl = document.getElementById('fw-stat-rate');
  3807. const prEl = document.getElementById('fw-stat-pktrate');
  3808. if (bEl) bEl.value = '0 B';
  3809. if (pEl) pEl.value = '0';
  3810. if (rEl) rEl.value = '0 bps';
  3811. if (prEl) prEl.value = '0 p/s';
  3812. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3813. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3814. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3815. }
  3816. async function resetAllFwCounters() {
  3817. try {
  3818. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3819. if (res.ok) {
  3820. resetCurrentRuleCounters();
  3821. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3822. loadFirewall(false);
  3823. }
  3824. } catch (err) {
  3825. showToast('Error', err.message, 'error');
  3826. }
  3827. }
  3828. async function applyFilterRule(closeAfter = false) {
  3829. const id = document.getElementById('filter-modal-id').value;
  3830. const chain = document.getElementById('filter-modal-chain').value;
  3831. const action = document.getElementById('filter-modal-action').value;
  3832. const comment = document.getElementById('filter-modal-comment').value.trim();
  3833. const enabled = document.getElementById('filter-modal-enabled').checked;
  3834. const src = getFwFieldVal('src', true);
  3835. const dst = getFwFieldVal('dst', true);
  3836. const srclist = getFwFieldVal('srclist', true);
  3837. const dstlist = getFwFieldVal('dstlist', true);
  3838. const srcgeo = getFwFieldVal('srcgeo', true);
  3839. const dstgeo = getFwFieldVal('dstgeo', true);
  3840. const proto = getFwFieldVal('proto', true);
  3841. const sport = getFwFieldVal('sport', true);
  3842. const dport = getFwFieldVal('dport', true);
  3843. const anyport = getFwFieldVal('anyport', true);
  3844. const iniface = getFwFieldVal('iniface', true);
  3845. const outiface = getFwFieldVal('outiface', true);
  3846. const inifacelist = getFwFieldVal('inifacelist', true);
  3847. const outifacelist = getFwFieldVal('outifacelist', true);
  3848. const pktmark = getFwFieldVal('pktmark', true);
  3849. const connmark = getFwFieldVal('connmark', true);
  3850. const routingmark = getFwFieldVal('routingmark', true);
  3851. const conntype = getFwFieldVal('conntype', false);
  3852. const states = [];
  3853. const csBox = document.getElementById('fw-field-cs');
  3854. if (csBox && !csBox.classList.contains('hidden')) {
  3855. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3856. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3857. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3858. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3859. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3860. }
  3861. const natStates = [];
  3862. const natBox = document.getElementById('fw-field-natstate');
  3863. if (natBox && !natBox.classList.contains('hidden')) {
  3864. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3865. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3866. }
  3867. const payload = {
  3868. id,
  3869. chain,
  3870. action,
  3871. protocol: proto || 'all',
  3872. src_address: src,
  3873. dst_address: dst,
  3874. src_port: sport,
  3875. dst_port: dport,
  3876. any_port: anyport,
  3877. in_interface: iniface,
  3878. out_interface: outiface,
  3879. in_interface_list: inifacelist,
  3880. out_interface_list: outifacelist,
  3881. packet_mark: pktmark,
  3882. connection_mark: connmark,
  3883. routing_mark: routingmark,
  3884. connection_type: conntype,
  3885. connection_state: states,
  3886. connection_nat_state: natStates,
  3887. src_address_list: srclist,
  3888. dst_address_list: dstlist,
  3889. src_geoip: srcgeo,
  3890. dst_geoip: dstgeo,
  3891. comment,
  3892. disabled: !enabled,
  3893. // Advanced tab
  3894. layer7_protocol: getFwFieldVal('layer7', false),
  3895. content: getFwFieldVal('content', false),
  3896. connection_bytes: getFwFieldVal('connbytes', false),
  3897. connection_rate: getFwFieldVal('connrate', false),
  3898. pcc: getFwFieldVal('pcc', false),
  3899. src_mac_address: getFwFieldVal('srcmac', true),
  3900. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3901. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3902. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3903. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3904. ipsec_policy: getFwFieldVal('ipsec', false),
  3905. tls_host: getFwFieldVal('tlshost', false),
  3906. ingress_priority: getFwFieldVal('ingresspriority', false),
  3907. priority: getFwFieldVal('priority', false),
  3908. dscp: getFwFieldVal('dscp', false),
  3909. tcp_mss: getFwFieldVal('tcpmss', false),
  3910. tos: document.getElementById('fw-val-tos')?.value || '',
  3911. packet_size: getFwFieldVal('pktsize', false),
  3912. random: getFwFieldVal('random', false),
  3913. tcp_flags: getFwFieldVal('tcpflags', false),
  3914. icmp_options: getFwFieldVal('icmpoptions', false),
  3915. ipv4_options: getFwFieldVal('ipv4options', false),
  3916. ttl: getFwFieldVal('ttl', false),
  3917. // Extra tab
  3918. time: getFwFieldVal('time', false),
  3919. limit: getFwFieldVal('limit', false),
  3920. dst_limit: getFwFieldVal('dstlimit', false),
  3921. psd: getFwFieldVal('psd', false),
  3922. // Action tab
  3923. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3924. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3925. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3926. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3927. log: document.getElementById('filter-modal-log')?.checked || false,
  3928. log_prefix: getFwFieldVal('logprefix', false)
  3929. };
  3930. try {
  3931. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3932. method: 'POST',
  3933. headers: { 'Content-Type': 'application/json' },
  3934. body: JSON.stringify(payload)
  3935. });
  3936. if (res.ok) {
  3937. const data = await res.json();
  3938. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3939. loadFirewall(false);
  3940. if (closeAfter) {
  3941. closeFilterModal();
  3942. } else {
  3943. if (data.id) {
  3944. document.getElementById('filter-modal-id').value = data.id;
  3945. const badge = document.getElementById('fw-modal-badge');
  3946. if (badge) badge.innerText = `#${data.id}`;
  3947. }
  3948. }
  3949. } else {
  3950. const err = await res.json();
  3951. showToast('Error', err.message || 'Failed to save rule', 'error');
  3952. }
  3953. } catch (err) {
  3954. showToast('Error', err.message, 'error');
  3955. }
  3956. }
  3957. function submitSaveFilterRule(e) {
  3958. if (e && e.preventDefault) e.preventDefault();
  3959. return applyFilterRule(true);
  3960. }
  3961. function startFwStatPolling() {
  3962. stopFwStatPolling();
  3963. pollRuleStats();
  3964. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3965. }
  3966. function stopFwStatPolling() {
  3967. if (state.fwStatInterval) {
  3968. clearInterval(state.fwStatInterval);
  3969. state.fwStatInterval = null;
  3970. }
  3971. }
  3972. async function pollRuleStats() {
  3973. const id = document.getElementById('filter-modal-id')?.value;
  3974. if (!id) {
  3975. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3976. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3977. return;
  3978. }
  3979. try {
  3980. const res = await fetch(`${API_BASE}/firewall/filter`);
  3981. if (!res.ok) return;
  3982. const rules = await res.json();
  3983. const r = rules.find(x => x.id === id);
  3984. if (!r) return;
  3985. const now = Date.now();
  3986. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3987. state.fwLastTimestamp = now;
  3988. const curBytes = r.bytes || 0;
  3989. const curPackets = r.packets || 0;
  3990. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3991. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3992. state.fwLastBytes = curBytes;
  3993. state.fwLastPackets = curPackets;
  3994. const rateBps = Math.round((deltaBytes * 8) / dt);
  3995. const ratePkt = Math.round(deltaPkts / dt);
  3996. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3997. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3998. state.fwStatRateHistory.push(rateBps);
  3999. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4000. state.fwStatPktHistory.push(ratePkt);
  4001. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4002. const bEl = document.getElementById('fw-stat-bytes');
  4003. const pEl = document.getElementById('fw-stat-packets');
  4004. const rEl = document.getElementById('fw-stat-rate');
  4005. const prEl = document.getElementById('fw-stat-pktrate');
  4006. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4007. if (pEl) pEl.value = curPackets.toLocaleString();
  4008. if (rEl) rEl.value = formatBps(rateBps);
  4009. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4010. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4011. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4012. } catch (e) {
  4013. console.error('Error polling rule stats', e);
  4014. }
  4015. }
  4016. function formatBps(bps) {
  4017. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4018. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4019. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4020. return bps + ' bps';
  4021. }
  4022. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4023. const svg = document.getElementById(svgId);
  4024. if (!svg) return;
  4025. const w = 500;
  4026. const h = 100;
  4027. const paddingRight = 45;
  4028. const graphWidth = w - paddingRight;
  4029. const maxVal = Math.max(5, ...dataArray);
  4030. const currentVal = dataArray[dataArray.length - 1] || 0;
  4031. const leg = document.getElementById(legendId);
  4032. if (leg) {
  4033. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4034. }
  4035. let gridLines = '';
  4036. for (let i = 0; i <= 5; i++) {
  4037. const y = 8 + (i * (h - 18) / 5);
  4038. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4039. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4040. gridLines += `
  4041. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4042. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4043. `;
  4044. }
  4045. const step = graphWidth / (dataArray.length - 1);
  4046. const points = dataArray.map((val, idx) => {
  4047. const x = idx * step;
  4048. const y = (h - 10) - (val / maxVal) * (h - 20);
  4049. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4050. });
  4051. const polylineStr = points.join(' ');
  4052. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4053. svg.innerHTML = `
  4054. ${gridLines}
  4055. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4056. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4057. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4058. `;
  4059. }
  4060. async function moveFilterRule(id, dir) {
  4061. try {
  4062. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4063. method: 'POST',
  4064. headers: { 'Content-Type': 'application/json' },
  4065. body: JSON.stringify({ direction: dir })
  4066. });
  4067. if (res.ok) loadFirewall(false);
  4068. } catch (err) {
  4069. showToast('Error', err.message, 'error');
  4070. }
  4071. }
  4072. async function toggleFilterRuleState(id, disabled) {
  4073. try {
  4074. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4075. method: 'POST',
  4076. headers: { 'Content-Type': 'application/json' },
  4077. body: JSON.stringify({ disabled })
  4078. });
  4079. if (res.ok) loadFirewall(false);
  4080. } catch (err) {
  4081. showToast('Error', err.message, 'error');
  4082. }
  4083. }
  4084. async function deleteFilterRule(id) {
  4085. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4086. try {
  4087. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4088. if (res.ok) {
  4089. showToast('Deleted', 'Filter rule removed', 'success');
  4090. loadFirewall(false);
  4091. }
  4092. } catch (err) {
  4093. showToast('Error', err.message, 'error');
  4094. }
  4095. }
  4096. // ----------------- NAT Rules -----------------
  4097. function renderNATRules() {
  4098. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4099. const tbody = document.getElementById('nat-table-body');
  4100. const empty = document.getElementById('nat-empty');
  4101. if (!tbody) return;
  4102. tbody.innerHTML = '';
  4103. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4104. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4105. if (rules.length === 0) {
  4106. empty?.classList.remove('hidden');
  4107. return;
  4108. }
  4109. empty?.classList.add('hidden');
  4110. rules.forEach((r, idx) => {
  4111. const tr = document.createElement('tr');
  4112. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4113. let toTarget = '-';
  4114. if (r.action === 'jump') {
  4115. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4116. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4117. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4118. } else if (r.action === 'redirect') {
  4119. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4120. } else if (r.action === 'masquerade') {
  4121. 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>`;
  4122. } else if (r.action === 'log') {
  4123. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4124. } else {
  4125. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4126. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4127. }
  4128. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  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-amber-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 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4136. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4137. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4138. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4139. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4140. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4141. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4142. </td>
  4143. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4144. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4145. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4146. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4147. <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>
  4148. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4149. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4150. </td>
  4151. `;
  4152. tbody.appendChild(tr);
  4153. });
  4154. }
  4155. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4156. function switchNATRuleTab(tab) {
  4157. state.activeNATRuleTab = tab;
  4158. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4159. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4160. btn.classList.add('text-slate-400', 'border-transparent');
  4161. });
  4162. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4163. if (activeBtn) {
  4164. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4165. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4166. }
  4167. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4168. const activePane = document.getElementById(`nat-pane-${tab}`);
  4169. if (activePane) activePane.classList.remove('hidden');
  4170. if (tab === 'statistics') {
  4171. startNATStatPolling();
  4172. } else {
  4173. stopNATStatPolling();
  4174. }
  4175. }
  4176. function toggleNATField(fieldKey, expand) {
  4177. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4178. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4179. if (!plusBtn || !fieldBox) return;
  4180. if (expand) {
  4181. plusBtn.classList.add('hidden');
  4182. fieldBox.classList.remove('hidden');
  4183. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4184. if (valInput) valInput.focus();
  4185. } else {
  4186. fieldBox.classList.add('hidden');
  4187. plusBtn.classList.remove('hidden');
  4188. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4189. if (valInput) {
  4190. if (valInput.tagName === 'SELECT') {
  4191. valInput.selectedIndex = 0;
  4192. } else {
  4193. valInput.value = '';
  4194. }
  4195. }
  4196. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4197. if (invInput) invInput.checked = false;
  4198. if (fieldKey === 'days') {
  4199. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4200. const el = document.getElementById(`nat-day-${d}`);
  4201. if (el) el.checked = true;
  4202. });
  4203. }
  4204. }
  4205. }
  4206. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4207. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4208. toggleNATField(fieldKey, true);
  4209. let strVal = String(value);
  4210. if (hasInvert) {
  4211. const inv = strVal.startsWith('!');
  4212. if (inv) strVal = strVal.slice(1);
  4213. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4214. if (invEl) invEl.checked = inv;
  4215. }
  4216. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4217. if (valEl) valEl.value = strVal;
  4218. } else {
  4219. toggleNATField(fieldKey, false);
  4220. }
  4221. }
  4222. function getNATFieldVal(fieldKey, hasInvert = false) {
  4223. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4224. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4225. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4226. let v = valEl ? valEl.value.trim() : '';
  4227. if (!v) return '';
  4228. if (hasInvert) {
  4229. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4230. if (invEl && invEl.checked) {
  4231. v = '!' + v.replace(/^!/, '');
  4232. }
  4233. }
  4234. return v;
  4235. }
  4236. function toggleMaximizeNATModal() {
  4237. const win = document.getElementById('nat-modal-window');
  4238. if (!win) return;
  4239. if (win.classList.contains('max-w-[720px]')) {
  4240. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4241. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4242. } else {
  4243. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4244. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4245. }
  4246. }
  4247. function handleNATChainChange() {
  4248. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4249. const actSel = document.getElementById('nat-modal-action');
  4250. if (actSel) {
  4251. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4252. actSel.value = 'masquerade';
  4253. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4254. actSel.value = 'dst-nat';
  4255. }
  4256. }
  4257. toggleNATActionFields();
  4258. }
  4259. function toggleNATActionFields() {
  4260. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4261. const rowAddr = document.getElementById('nat-row-toaddr');
  4262. const rowPort = document.getElementById('nat-row-toport');
  4263. const jumpBox = document.getElementById('nat-action-jump-box');
  4264. const addrBox = document.getElementById('nat-action-addrlist-box');
  4265. // Hide all dynamic rows first
  4266. if (rowAddr) rowAddr.classList.add('hidden');
  4267. if (rowPort) rowPort.classList.add('hidden');
  4268. if (jumpBox) jumpBox.classList.add('hidden');
  4269. if (addrBox) addrBox.classList.add('hidden');
  4270. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4271. if (rowAddr) rowAddr.classList.remove('hidden');
  4272. if (rowPort) rowPort.classList.remove('hidden');
  4273. } else if (act === 'redirect' || act === 'masquerade') {
  4274. if (rowPort) rowPort.classList.remove('hidden');
  4275. } else if (act === 'jump') {
  4276. if (jumpBox) jumpBox.classList.remove('hidden');
  4277. } else if (act.includes('address-list') || act.includes('address list')) {
  4278. if (addrBox) addrBox.classList.remove('hidden');
  4279. }
  4280. if (act === 'log') {
  4281. const logEl = document.getElementById('nat-modal-log');
  4282. if (logEl) logEl.checked = true;
  4283. toggleNATField('logprefix', true);
  4284. }
  4285. }
  4286. function toggleNATLogPrefix() {
  4287. const isLog = document.getElementById('nat-modal-log')?.checked;
  4288. toggleNATField('logprefix', !!isLog);
  4289. }
  4290. function openAddNATModal() {
  4291. switchNATRuleTab('general');
  4292. const badge = document.getElementById('nat-modal-badge');
  4293. if (badge) badge.innerText = 'New...';
  4294. document.getElementById('nat-modal-id').value = '';
  4295. document.getElementById('nat-modal-enabled').checked = true;
  4296. document.getElementById('nat-modal-comment').value = '';
  4297. document.getElementById('nat-modal-chain').value = 'srcnat';
  4298. document.getElementById('nat-modal-action').value = 'masquerade';
  4299. document.getElementById('nat-modal-toaddr').value = '';
  4300. document.getElementById('nat-modal-toport').value = '';
  4301. document.getElementById('nat-modal-log').checked = false;
  4302. populateInterfaceSelect('nat-val-iniface');
  4303. populateInterfaceSelect('nat-val-outiface');
  4304. populateAddressListSelect('nat-val-srclist');
  4305. populateAddressListSelect('nat-val-dstlist');
  4306. populateGeoIPSelect('nat-val-srcgeo');
  4307. populateGeoIPSelect('nat-val-dstgeo');
  4308. const allFieldKeys = [
  4309. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4310. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4311. 'routingmark', 'conntype',
  4312. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4313. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4314. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4315. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4316. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4317. ];
  4318. allFieldKeys.forEach(k => toggleNATField(k, false));
  4319. resetCurrentNATRuleCounters();
  4320. toggleNATActionFields();
  4321. document.getElementById('nat-modal').classList.remove('hidden');
  4322. }
  4323. function openEditNATModal(id) {
  4324. const r = (state.natRules || []).find(rule => rule.id === id);
  4325. if (!r) return;
  4326. switchNATRuleTab('general');
  4327. const badge = document.getElementById('nat-modal-badge');
  4328. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4329. document.getElementById('nat-modal-id').value = r.id;
  4330. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4331. document.getElementById('nat-modal-comment').value = r.comment || '';
  4332. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4333. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4334. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4335. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4336. document.getElementById('nat-modal-log').checked = !!r.log;
  4337. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4338. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4339. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4340. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4341. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4342. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4343. setNATFieldVal('src', r.src_address, true);
  4344. setNATFieldVal('dst', r.dst_address, true);
  4345. setNATFieldVal('srclist', r.src_address_list, true);
  4346. setNATFieldVal('dstlist', r.dst_address_list, true);
  4347. setNATFieldVal('srcgeo', r.src_geoip, true);
  4348. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4349. if (r.protocol && r.protocol !== 'all') {
  4350. setNATFieldVal('proto', r.protocol, true);
  4351. } else {
  4352. toggleNATField('proto', false);
  4353. }
  4354. setNATFieldVal('sport', r.src_port, true);
  4355. setNATFieldVal('dport', r.dst_port, true);
  4356. setNATFieldVal('anyport', r.any_port, true);
  4357. setNATFieldVal('iniface', r.in_interface, true);
  4358. setNATFieldVal('outiface', r.out_interface, true);
  4359. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4360. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4361. setNATFieldVal('pktmark', r.packet_mark, true);
  4362. setNATFieldVal('connmark', r.connection_mark, true);
  4363. setNATFieldVal('routingmark', r.routing_mark, true);
  4364. setNATFieldVal('conntype', r.connection_type, false);
  4365. // Advanced tab fields
  4366. setNATFieldVal('layer7', r.layer7_protocol, false);
  4367. setNATFieldVal('content', r.content, false);
  4368. setNATFieldVal('connbytes', r.connection_bytes, false);
  4369. setNATFieldVal('connrate', r.connection_rate, false);
  4370. setNATFieldVal('pcc', r.pcc, false);
  4371. setNATFieldVal('srcmac', r.src_mac_address, true);
  4372. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4373. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4374. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4375. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4376. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4377. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4378. setNATFieldVal('priority', r.priority, false);
  4379. setNATFieldVal('dscp', r.dscp, false);
  4380. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4381. if (r.tos) {
  4382. const tosEl = document.getElementById('nat-val-tos');
  4383. if (tosEl) tosEl.value = r.tos;
  4384. }
  4385. setNATFieldVal('pktsize', r.packet_size, false);
  4386. setNATFieldVal('random', r.random, false);
  4387. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4388. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4389. setNATFieldVal('ttl', r.ttl, false);
  4390. // Extra tab fields
  4391. setNATFieldVal('time', r.time, false);
  4392. if (r.days) {
  4393. toggleNATField('days', true);
  4394. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4395. const chk = document.getElementById(`nat-day-${d}`);
  4396. if (chk) chk.checked = r.days.includes(d);
  4397. });
  4398. } else {
  4399. toggleNATField('days', false);
  4400. }
  4401. setNATFieldVal('limit', r.limit, false);
  4402. setNATFieldVal('dstlimit', r.dst_limit, false);
  4403. setNATFieldVal('psd', r.psd, false);
  4404. // Action fields
  4405. if (r.jump_target) {
  4406. const jtEl = document.getElementById('nat-modal-jumptarget');
  4407. if (jtEl) jtEl.value = r.jump_target;
  4408. }
  4409. if (r.address_list) {
  4410. const alEl = document.getElementById('nat-modal-action-addrlist');
  4411. if (alEl) alEl.value = r.address_list;
  4412. }
  4413. if (r.address_list_timeout) {
  4414. const toEl = document.getElementById('nat-modal-action-timeout');
  4415. if (toEl) toEl.value = r.address_list_timeout;
  4416. }
  4417. setNATFieldVal('logprefix', r.log_prefix, false);
  4418. // Statistics
  4419. const bEl = document.getElementById('nat-stat-bytes');
  4420. const pEl = document.getElementById('nat-stat-packets');
  4421. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4422. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4423. state.natLastBytes = r.bytes || 0;
  4424. state.natLastPackets = r.packets || 0;
  4425. state.natLastTimestamp = Date.now();
  4426. state.natStatRateHistory = new Array(30).fill(0);
  4427. state.natStatPktHistory = new Array(30).fill(0);
  4428. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4429. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4430. toggleNATActionFields();
  4431. document.getElementById('nat-modal').classList.remove('hidden');
  4432. }
  4433. function closeNATModal() {
  4434. stopNATStatPolling();
  4435. document.getElementById('nat-modal').classList.add('hidden');
  4436. }
  4437. function copyNATRule() {
  4438. document.getElementById('nat-modal-id').value = '';
  4439. const badge = document.getElementById('nat-modal-badge');
  4440. if (badge) badge.innerText = 'New...';
  4441. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4442. }
  4443. function resetCurrentNATRuleCounters() {
  4444. state.natStatRateHistory = new Array(30).fill(0);
  4445. state.natStatPktHistory = new Array(30).fill(0);
  4446. state.natLastBytes = 0;
  4447. state.natLastPackets = 0;
  4448. state.natLastTimestamp = Date.now();
  4449. const bEl = document.getElementById('nat-stat-bytes');
  4450. const pEl = document.getElementById('nat-stat-packets');
  4451. const rEl = document.getElementById('nat-stat-rate');
  4452. const prEl = document.getElementById('nat-stat-pktrate');
  4453. if (bEl) bEl.value = '0 B';
  4454. if (pEl) pEl.value = '0';
  4455. if (rEl) rEl.value = '0 bps';
  4456. if (prEl) prEl.value = '0 p/s';
  4457. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4458. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4459. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4460. }
  4461. async function applyNATRule(closeAfter = false) {
  4462. const id = document.getElementById('nat-modal-id').value;
  4463. const chain = document.getElementById('nat-modal-chain').value;
  4464. const action = document.getElementById('nat-modal-action').value;
  4465. const comment = document.getElementById('nat-modal-comment').value.trim();
  4466. const enabled = document.getElementById('nat-modal-enabled').checked;
  4467. const src = getNATFieldVal('src', true);
  4468. const dst = getNATFieldVal('dst', true);
  4469. const srclist = getNATFieldVal('srclist', true);
  4470. const dstlist = getNATFieldVal('dstlist', true);
  4471. const srcgeo = getNATFieldVal('srcgeo', true);
  4472. const dstgeo = getNATFieldVal('dstgeo', true);
  4473. const proto = getNATFieldVal('proto', true);
  4474. const sport = getNATFieldVal('sport', true);
  4475. const dport = getNATFieldVal('dport', true);
  4476. const anyport = getNATFieldVal('anyport', true);
  4477. const iniface = getNATFieldVal('iniface', true);
  4478. const outiface = getNATFieldVal('outiface', true);
  4479. const inifacelist = getNATFieldVal('inifacelist', true);
  4480. const outifacelist = getNATFieldVal('outifacelist', true);
  4481. const pktmark = getNATFieldVal('pktmark', true);
  4482. const connmark = getNATFieldVal('connmark', true);
  4483. const routingmark = getNATFieldVal('routingmark', true);
  4484. const conntype = getNATFieldVal('conntype', false);
  4485. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4486. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4487. const payload = {
  4488. id,
  4489. chain,
  4490. action,
  4491. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4492. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4493. protocol: proto || 'all',
  4494. src_address: src,
  4495. dst_address: dst,
  4496. src_port: sport,
  4497. dst_port: dport,
  4498. any_port: anyport,
  4499. in_interface: iniface,
  4500. out_interface: outiface,
  4501. in_interface_list: inifacelist,
  4502. out_interface_list: outifacelist,
  4503. packet_mark: pktmark,
  4504. connection_mark: connmark,
  4505. routing_mark: routingmark,
  4506. connection_type: conntype,
  4507. src_address_list: srclist,
  4508. dst_address_list: dstlist,
  4509. src_geoip: srcgeo,
  4510. dst_geoip: dstgeo,
  4511. comment,
  4512. disabled: !enabled,
  4513. // Advanced tab
  4514. layer7_protocol: getNATFieldVal('layer7', false),
  4515. content: getNATFieldVal('content', false),
  4516. connection_bytes: getNATFieldVal('connbytes', false),
  4517. connection_rate: getNATFieldVal('connrate', false),
  4518. pcc: getNATFieldVal('pcc', false),
  4519. src_mac_address: getNATFieldVal('srcmac', true),
  4520. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4521. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4522. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4523. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4524. ipsec_policy: getNATFieldVal('ipsec', false),
  4525. ingress_priority: getNATFieldVal('ingresspriority', false),
  4526. priority: getNATFieldVal('priority', false),
  4527. dscp: getNATFieldVal('dscp', false),
  4528. tcp_mss: getNATFieldVal('tcpmss', false),
  4529. tos: document.getElementById('nat-val-tos')?.value || '',
  4530. packet_size: getNATFieldVal('pktsize', false),
  4531. random: getNATFieldVal('random', false),
  4532. icmp_options: getNATFieldVal('icmpoptions', false),
  4533. ipv4_options: getNATFieldVal('ipv4options', false),
  4534. ttl: getNATFieldVal('ttl', false),
  4535. // Extra tab
  4536. time: getNATFieldVal('time', false),
  4537. limit: getNATFieldVal('limit', false),
  4538. dst_limit: getNATFieldVal('dstlimit', false),
  4539. psd: getNATFieldVal('psd', false),
  4540. // Action tab
  4541. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4542. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4543. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4544. log: document.getElementById('nat-modal-log')?.checked || false,
  4545. log_prefix: getNATFieldVal('logprefix', false)
  4546. };
  4547. try {
  4548. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4549. method: 'POST',
  4550. headers: { 'Content-Type': 'application/json' },
  4551. body: JSON.stringify(payload)
  4552. });
  4553. if (res.ok) {
  4554. const data = await res.json();
  4555. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4556. loadFirewall(false);
  4557. if (closeAfter) {
  4558. closeNATModal();
  4559. } else {
  4560. if (data.id) {
  4561. document.getElementById('nat-modal-id').value = data.id;
  4562. const badge = document.getElementById('nat-modal-badge');
  4563. if (badge) badge.innerText = `#${data.id}`;
  4564. }
  4565. }
  4566. } else {
  4567. const err = await res.json();
  4568. showToast('Error', err.message || 'Failed to save rule', 'error');
  4569. }
  4570. } catch (err) {
  4571. showToast('Error', err.message, 'error');
  4572. }
  4573. }
  4574. function submitSaveNATRule(e) {
  4575. if (e && e.preventDefault) e.preventDefault();
  4576. return applyNATRule(true);
  4577. }
  4578. function startNATStatPolling() {
  4579. stopNATStatPolling();
  4580. pollNATRuleStats();
  4581. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4582. }
  4583. function stopNATStatPolling() {
  4584. if (state.natStatInterval) {
  4585. clearInterval(state.natStatInterval);
  4586. state.natStatInterval = null;
  4587. }
  4588. }
  4589. async function pollNATRuleStats() {
  4590. const id = document.getElementById('nat-modal-id')?.value;
  4591. if (!id) {
  4592. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4593. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4594. return;
  4595. }
  4596. try {
  4597. const res = await fetch(`${API_BASE}/firewall/nat`);
  4598. if (!res.ok) return;
  4599. const rules = await res.json();
  4600. const r = rules.find(x => x.id === id);
  4601. if (!r) return;
  4602. const now = Date.now();
  4603. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4604. state.natLastTimestamp = now;
  4605. const curBytes = r.bytes || 0;
  4606. const curPackets = r.packets || 0;
  4607. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4608. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4609. state.natLastBytes = curBytes;
  4610. state.natLastPackets = curPackets;
  4611. const rateBps = Math.round((deltaBytes * 8) / dt);
  4612. const ratePkt = Math.round(deltaPkts / dt);
  4613. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4614. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4615. state.natStatRateHistory.push(rateBps);
  4616. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4617. state.natStatPktHistory.push(ratePkt);
  4618. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4619. const bEl = document.getElementById('nat-stat-bytes');
  4620. const pEl = document.getElementById('nat-stat-packets');
  4621. const rEl = document.getElementById('nat-stat-rate');
  4622. const prEl = document.getElementById('nat-stat-pktrate');
  4623. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4624. if (pEl) pEl.value = curPackets.toLocaleString();
  4625. if (rEl) rEl.value = formatBps(rateBps);
  4626. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4627. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4628. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4629. } catch (e) {
  4630. console.error('Error polling NAT rule stats', e);
  4631. }
  4632. }
  4633. async function moveNATRule(id, dir) {
  4634. try {
  4635. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4636. method: 'POST',
  4637. headers: { 'Content-Type': 'application/json' },
  4638. body: JSON.stringify({ direction: dir })
  4639. });
  4640. if (res.ok) loadFirewall(false);
  4641. } catch (err) {
  4642. showToast('Error', err.message, 'error');
  4643. }
  4644. }
  4645. async function toggleNATRuleState(id, disabled) {
  4646. try {
  4647. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4648. method: 'POST',
  4649. headers: { 'Content-Type': 'application/json' },
  4650. body: JSON.stringify({ disabled })
  4651. });
  4652. if (res.ok) loadFirewall(false);
  4653. } catch (err) {
  4654. showToast('Error', err.message, 'error');
  4655. }
  4656. }
  4657. async function deleteNATRule(id) {
  4658. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4659. try {
  4660. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4661. if (res.ok) {
  4662. showToast('Deleted', 'NAT rule removed', 'success');
  4663. loadFirewall(false);
  4664. }
  4665. } catch (err) {
  4666. showToast('Error', err.message, 'error');
  4667. }
  4668. }
  4669. // ----------------- Mangle Rules -----------------
  4670. function renderMangleRules() {
  4671. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4672. const tbody = document.getElementById('mangle-table-body');
  4673. const empty = document.getElementById('mangle-empty');
  4674. if (!tbody) return;
  4675. tbody.innerHTML = '';
  4676. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4677. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4678. if (rules.length === 0) {
  4679. empty?.classList.remove('hidden');
  4680. return;
  4681. }
  4682. empty?.classList.add('hidden');
  4683. rules.forEach((r, idx) => {
  4684. const tr = document.createElement('tr');
  4685. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4686. let markVal = '<span class="text-slate-500">-</span>';
  4687. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4688. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4689. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4690. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4691. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4692. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4693. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4694. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4695. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4696. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4697. 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>`;
  4698. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4699. tr.innerHTML = `
  4700. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4701. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4702. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4703. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4704. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4705. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4706. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4707. <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>
  4708. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4709. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4710. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4711. </td>
  4712. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4713. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4714. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4715. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4716. <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>
  4717. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4718. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4719. </td>
  4720. `;
  4721. tbody.appendChild(tr);
  4722. });
  4723. }
  4724. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4725. function switchMangleRuleTab(tab) {
  4726. state.activeMangleRuleTab = tab;
  4727. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4728. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4729. btn.classList.add('text-slate-400', 'border-transparent');
  4730. });
  4731. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4732. if (activeBtn) {
  4733. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4734. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4735. }
  4736. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4737. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4738. if (activePane) activePane.classList.remove('hidden');
  4739. if (tab === 'statistics') {
  4740. startMangleStatPolling();
  4741. } else {
  4742. stopMangleStatPolling();
  4743. }
  4744. }
  4745. function toggleMangleField(fieldKey, expand) {
  4746. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4747. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4748. if (!plusBtn || !fieldBox) return;
  4749. if (expand) {
  4750. plusBtn.classList.add('hidden');
  4751. fieldBox.classList.remove('hidden');
  4752. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4753. if (valInput) valInput.focus();
  4754. } else {
  4755. fieldBox.classList.add('hidden');
  4756. plusBtn.classList.remove('hidden');
  4757. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4758. if (valInput) {
  4759. if (valInput.tagName === 'SELECT') {
  4760. valInput.selectedIndex = 0;
  4761. } else {
  4762. valInput.value = '';
  4763. }
  4764. }
  4765. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4766. if (invInput) invInput.checked = false;
  4767. if (fieldKey === 'cs') {
  4768. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4769. const el = document.getElementById(id);
  4770. if (el) el.checked = false;
  4771. });
  4772. }
  4773. if (fieldKey === 'natstate') {
  4774. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4775. const el = document.getElementById(id);
  4776. if (el) el.checked = false;
  4777. });
  4778. }
  4779. }
  4780. }
  4781. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4782. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4783. toggleMangleField(fieldKey, true);
  4784. let strVal = String(value);
  4785. if (hasInvert) {
  4786. const inv = strVal.startsWith('!');
  4787. if (inv) strVal = strVal.slice(1);
  4788. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4789. if (invEl) invEl.checked = inv;
  4790. }
  4791. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4792. if (valEl) valEl.value = strVal;
  4793. } else {
  4794. toggleMangleField(fieldKey, false);
  4795. }
  4796. }
  4797. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4798. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4799. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4800. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4801. let v = valEl ? valEl.value.trim() : '';
  4802. if (!v) return '';
  4803. if (hasInvert) {
  4804. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4805. if (invEl && invEl.checked) {
  4806. v = '!' + v.replace(/^!/, '');
  4807. }
  4808. }
  4809. return v;
  4810. }
  4811. function toggleMaximizeMangleModal() {
  4812. const win = document.getElementById('mangle-modal-window');
  4813. if (!win) return;
  4814. if (win.classList.contains('max-w-[720px]')) {
  4815. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4816. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4817. } else {
  4818. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4819. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4820. }
  4821. }
  4822. function toggleMangleActionFields() {
  4823. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4824. // Hide all dynamic rows first
  4825. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4826. const el = document.getElementById(`mangle-row-${id}`);
  4827. if (el) el.classList.add('hidden');
  4828. });
  4829. const jumpBox = document.getElementById('mangle-action-jump-box');
  4830. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4831. if (jumpBox) jumpBox.classList.add('hidden');
  4832. if (addrBox) addrBox.classList.add('hidden');
  4833. // Activate matching rows
  4834. if (act === 'mark-connection') {
  4835. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4836. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4837. } else if (act === 'mark-routing') {
  4838. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4839. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4840. } else if (act === 'mark-packet') {
  4841. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4842. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4843. } else if (act === 'change-mss') {
  4844. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4845. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4846. } else if (act === 'change-dscp') {
  4847. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4848. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4849. } else if (act === 'change-ttl') {
  4850. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4851. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4852. } else if (act === 'set-priority') {
  4853. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4854. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4855. } else if (act === 'route') {
  4856. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4857. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4858. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4859. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4860. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4861. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4862. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4863. } else if (act === 'jump') {
  4864. if (jumpBox) jumpBox.classList.remove('hidden');
  4865. } else if (act.includes('address-list') || act.includes('address list')) {
  4866. if (addrBox) addrBox.classList.remove('hidden');
  4867. }
  4868. if (act === 'log') {
  4869. const logEl = document.getElementById('mangle-modal-log');
  4870. if (logEl) logEl.checked = true;
  4871. toggleMangleField('logprefix', true);
  4872. }
  4873. }
  4874. function toggleMangleLogPrefix() {
  4875. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4876. toggleMangleField('logprefix', !!isLog);
  4877. }
  4878. const allMangleFieldKeys = [
  4879. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4880. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4881. 'routingmark', 'conntype', 'cs', 'natstate',
  4882. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4883. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4884. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4885. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4886. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4887. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4888. ];
  4889. function openAddMangleModal() {
  4890. switchMangleRuleTab('general');
  4891. const badge = document.getElementById('mangle-modal-badge');
  4892. if (badge) badge.innerText = 'New...';
  4893. document.getElementById('mangle-modal-id').value = '';
  4894. document.getElementById('mangle-modal-enabled').checked = true;
  4895. document.getElementById('mangle-modal-comment').value = '';
  4896. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4897. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4898. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4899. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4900. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4901. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4902. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4903. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4904. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4905. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4906. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4907. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4908. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4909. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4910. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4911. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4912. populateInterfaceSelect('mangle-val-iniface');
  4913. populateInterfaceSelect('mangle-val-outiface');
  4914. populateAddressListSelect('mangle-val-srclist');
  4915. populateAddressListSelect('mangle-val-dstlist');
  4916. populateGeoIPSelect('mangle-val-srcgeo');
  4917. populateGeoIPSelect('mangle-val-dstgeo');
  4918. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4919. resetCurrentMangleRuleCounters();
  4920. toggleMangleActionFields();
  4921. document.getElementById('mangle-modal').classList.remove('hidden');
  4922. }
  4923. function openEditMangleModal(id) {
  4924. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4925. if (!r) return;
  4926. switchMangleRuleTab('general');
  4927. const badge = document.getElementById('mangle-modal-badge');
  4928. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4929. document.getElementById('mangle-modal-id').value = r.id;
  4930. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4931. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4932. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4933. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4934. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4935. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4936. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4937. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4938. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4939. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4940. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4941. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4942. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4943. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4944. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4945. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4946. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4947. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4948. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4949. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4950. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4951. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4952. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4953. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4954. setMangleFieldVal('src', r.src_address, true);
  4955. setMangleFieldVal('dst', r.dst_address, true);
  4956. setMangleFieldVal('srclist', r.src_address_list, true);
  4957. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4958. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4959. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4960. if (r.protocol && r.protocol !== 'all') {
  4961. setMangleFieldVal('proto', r.protocol, true);
  4962. } else {
  4963. toggleMangleField('proto', false);
  4964. }
  4965. setMangleFieldVal('sport', r.src_port, true);
  4966. setMangleFieldVal('dport', r.dst_port, true);
  4967. setMangleFieldVal('anyport', r.any_port, true);
  4968. setMangleFieldVal('iniface', r.in_interface, true);
  4969. setMangleFieldVal('outiface', r.out_interface, true);
  4970. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4971. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4972. setMangleFieldVal('pktmark', r.packet_mark, true);
  4973. setMangleFieldVal('connmark', r.connection_mark, true);
  4974. setMangleFieldVal('routingmark', r.routing_mark, true);
  4975. setMangleFieldVal('conntype', r.connection_type, false);
  4976. // Connection State
  4977. const states = r.connection_state || [];
  4978. if (states.length > 0) {
  4979. toggleMangleField('cs', true);
  4980. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4981. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4982. if (el) el.checked = states.includes(s);
  4983. });
  4984. } else {
  4985. toggleMangleField('cs', false);
  4986. }
  4987. // Connection NAT State
  4988. const natStates = r.connection_nat_state || [];
  4989. if (natStates.length > 0) {
  4990. toggleMangleField('natstate', true);
  4991. ['srcnat', 'dstnat'].forEach(s => {
  4992. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4993. if (el) el.checked = natStates.includes(s);
  4994. });
  4995. } else {
  4996. toggleMangleField('natstate', false);
  4997. }
  4998. // Advanced tab fields
  4999. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5000. setMangleFieldVal('content', r.content, false);
  5001. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5002. setMangleFieldVal('connrate', r.connection_rate, false);
  5003. setMangleFieldVal('pcc', r.pcc, false);
  5004. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5005. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5006. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5007. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5008. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5009. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5010. setMangleFieldVal('tlshost', r.tls_host, false);
  5011. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5012. setMangleFieldVal('priority', r.priority, false);
  5013. setMangleFieldVal('dscp', r.dscp, false);
  5014. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5015. if (r.tos) {
  5016. const tosEl = document.getElementById('mangle-val-tos');
  5017. if (tosEl) tosEl.value = r.tos;
  5018. }
  5019. setMangleFieldVal('pktsize', r.packet_size, false);
  5020. setMangleFieldVal('random', r.random, false);
  5021. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5022. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5023. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5024. setMangleFieldVal('ttl', r.ttl, false);
  5025. // Extra tab fields
  5026. setMangleFieldVal('nth', r.nth, false);
  5027. setMangleFieldVal('connlimit', r.connection_limit, false);
  5028. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5029. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5030. setMangleFieldVal('hotspot', r.hotspot, false);
  5031. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5032. setMangleFieldVal('limit', r.limit, false);
  5033. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5034. setMangleFieldVal('time', r.time, false);
  5035. setMangleFieldVal('psd', r.psd, false);
  5036. // Action fields
  5037. if (r.jump_target) {
  5038. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5039. if (jtEl) jtEl.value = r.jump_target;
  5040. }
  5041. if (r.address_list) {
  5042. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5043. if (alEl) alEl.value = r.address_list;
  5044. }
  5045. if (r.address_list_timeout) {
  5046. const toEl = document.getElementById('mangle-modal-action-timeout');
  5047. if (toEl) toEl.value = r.address_list_timeout;
  5048. }
  5049. setMangleFieldVal('logprefix', r.log_prefix, false);
  5050. // Statistics
  5051. const bEl = document.getElementById('mangle-stat-bytes');
  5052. const pEl = document.getElementById('mangle-stat-packets');
  5053. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5054. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5055. state.mangleLastBytes = r.bytes || 0;
  5056. state.mangleLastPackets = r.packets || 0;
  5057. state.mangleLastTimestamp = Date.now();
  5058. state.mangleStatRateHistory = new Array(30).fill(0);
  5059. state.mangleStatPktHistory = new Array(30).fill(0);
  5060. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5061. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5062. toggleMangleActionFields();
  5063. document.getElementById('mangle-modal').classList.remove('hidden');
  5064. }
  5065. function closeMangleModal() {
  5066. stopMangleStatPolling();
  5067. document.getElementById('mangle-modal').classList.add('hidden');
  5068. }
  5069. function copyMangleRule() {
  5070. document.getElementById('mangle-modal-id').value = '';
  5071. const badge = document.getElementById('mangle-modal-badge');
  5072. if (badge) badge.innerText = 'New...';
  5073. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5074. }
  5075. function resetCurrentMangleRuleCounters() {
  5076. state.mangleStatRateHistory = new Array(30).fill(0);
  5077. state.mangleStatPktHistory = new Array(30).fill(0);
  5078. state.mangleLastBytes = 0;
  5079. state.mangleLastPackets = 0;
  5080. state.mangleLastTimestamp = Date.now();
  5081. const bEl = document.getElementById('mangle-stat-bytes');
  5082. const pEl = document.getElementById('mangle-stat-packets');
  5083. const rEl = document.getElementById('mangle-stat-rate');
  5084. const prEl = document.getElementById('mangle-stat-pktrate');
  5085. if (bEl) bEl.value = '0 B';
  5086. if (pEl) pEl.value = '0';
  5087. if (rEl) rEl.value = '0 bps';
  5088. if (prEl) prEl.value = '0 p/s';
  5089. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5090. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5091. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5092. }
  5093. async function applyMangleRule(closeAfter = false) {
  5094. const id = document.getElementById('mangle-modal-id').value;
  5095. const chain = document.getElementById('mangle-modal-chain').value;
  5096. const action = document.getElementById('mangle-modal-action').value;
  5097. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5098. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5099. const src = getMangleFieldVal('src', true);
  5100. const dst = getMangleFieldVal('dst', true);
  5101. const srclist = getMangleFieldVal('srclist', true);
  5102. const dstlist = getMangleFieldVal('dstlist', true);
  5103. const srcgeo = getMangleFieldVal('srcgeo', true);
  5104. const dstgeo = getMangleFieldVal('dstgeo', true);
  5105. const proto = getMangleFieldVal('proto', true);
  5106. const sport = getMangleFieldVal('sport', true);
  5107. const dport = getMangleFieldVal('dport', true);
  5108. const anyport = getMangleFieldVal('anyport', true);
  5109. const iniface = getMangleFieldVal('iniface', true);
  5110. const outiface = getMangleFieldVal('outiface', true);
  5111. const inifacelist = getMangleFieldVal('inifacelist', true);
  5112. const outifacelist = getMangleFieldVal('outifacelist', true);
  5113. const pktmark = getMangleFieldVal('pktmark', true);
  5114. const connmark = getMangleFieldVal('connmark', true);
  5115. const routingmark = getMangleFieldVal('routingmark', true);
  5116. const conntype = getMangleFieldVal('conntype', false);
  5117. const states = [];
  5118. const csBox = document.getElementById('mangle-field-cs');
  5119. if (csBox && !csBox.classList.contains('hidden')) {
  5120. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5121. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5122. });
  5123. }
  5124. const natStates = [];
  5125. const natBox = document.getElementById('mangle-field-natstate');
  5126. if (natBox && !natBox.classList.contains('hidden')) {
  5127. ['srcnat', 'dstnat'].forEach(s => {
  5128. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5129. });
  5130. }
  5131. const payload = {
  5132. id,
  5133. chain,
  5134. action,
  5135. protocol: proto || 'all',
  5136. src_address: src,
  5137. dst_address: dst,
  5138. src_port: sport,
  5139. dst_port: dport,
  5140. any_port: anyport,
  5141. in_interface: iniface,
  5142. out_interface: outiface,
  5143. in_interface_list: inifacelist,
  5144. out_interface_list: outifacelist,
  5145. packet_mark: pktmark,
  5146. connection_mark: connmark,
  5147. routing_mark: routingmark,
  5148. connection_type: conntype,
  5149. connection_state: states,
  5150. connection_nat_state: natStates,
  5151. src_address_list: srclist,
  5152. dst_address_list: dstlist,
  5153. src_geoip: srcgeo,
  5154. dst_geoip: dstgeo,
  5155. comment,
  5156. disabled: !enabled,
  5157. // Advanced tab
  5158. layer7_protocol: getMangleFieldVal('layer7', false),
  5159. content: getMangleFieldVal('content', false),
  5160. connection_bytes: getMangleFieldVal('connbytes', false),
  5161. connection_rate: getMangleFieldVal('connrate', false),
  5162. pcc: getMangleFieldVal('pcc', false),
  5163. src_mac_address: getMangleFieldVal('srcmac', true),
  5164. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5165. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5166. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5167. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5168. ipsec_policy: getMangleFieldVal('ipsec', false),
  5169. tls_host: getMangleFieldVal('tlshost', false),
  5170. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5171. priority: getMangleFieldVal('priority', false),
  5172. dscp: getMangleFieldVal('dscp', false),
  5173. tcp_mss: getMangleFieldVal('tcpmss', false),
  5174. tos: document.getElementById('mangle-val-tos')?.value || '',
  5175. packet_size: getMangleFieldVal('pktsize', false),
  5176. random: getMangleFieldVal('random', false),
  5177. tcp_flags: getMangleFieldVal('tcpflags', false),
  5178. icmp_options: getMangleFieldVal('icmpoptions', false),
  5179. ipv4_options: getMangleFieldVal('ipv4options', false),
  5180. ttl: getMangleFieldVal('ttl', false),
  5181. // Extra tab
  5182. nth: getMangleFieldVal('nth', false),
  5183. connection_limit: getMangleFieldVal('connlimit', false),
  5184. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5185. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5186. hotspot: getMangleFieldVal('hotspot', false),
  5187. ip_fragment: getMangleFieldVal('ipfragment', false),
  5188. limit: getMangleFieldVal('limit', false),
  5189. dst_limit: getMangleFieldVal('dstlimit', false),
  5190. time: getMangleFieldVal('time', false),
  5191. psd: getMangleFieldVal('psd', false),
  5192. // Action tab
  5193. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5194. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5195. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5196. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5197. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5198. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5199. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5200. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5201. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5202. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5203. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5204. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5205. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5206. log: document.getElementById('mangle-modal-log')?.checked || false,
  5207. log_prefix: getMangleFieldVal('logprefix', false)
  5208. };
  5209. try {
  5210. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5211. method: 'POST',
  5212. headers: { 'Content-Type': 'application/json' },
  5213. body: JSON.stringify(payload)
  5214. });
  5215. if (res.ok) {
  5216. const data = await res.json();
  5217. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5218. loadFirewall(false);
  5219. if (closeAfter) {
  5220. closeMangleModal();
  5221. } else {
  5222. if (data.id) {
  5223. document.getElementById('mangle-modal-id').value = data.id;
  5224. const badge = document.getElementById('mangle-modal-badge');
  5225. if (badge) badge.innerText = `#${data.id}`;
  5226. }
  5227. }
  5228. } else {
  5229. const err = await res.json();
  5230. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5231. }
  5232. } catch (err) {
  5233. showToast('Error', err.message, 'error');
  5234. }
  5235. }
  5236. function submitSaveMangleRule(e) {
  5237. if (e && e.preventDefault) e.preventDefault();
  5238. return applyMangleRule(true);
  5239. }
  5240. function startMangleStatPolling() {
  5241. stopMangleStatPolling();
  5242. pollMangleRuleStats();
  5243. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5244. }
  5245. function stopMangleStatPolling() {
  5246. if (state.mangleStatInterval) {
  5247. clearInterval(state.mangleStatInterval);
  5248. state.mangleStatInterval = null;
  5249. }
  5250. }
  5251. async function pollMangleRuleStats() {
  5252. const id = document.getElementById('mangle-modal-id')?.value;
  5253. if (!id) {
  5254. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5255. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5256. return;
  5257. }
  5258. try {
  5259. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5260. if (!res.ok) return;
  5261. const rules = await res.json();
  5262. const r = rules.find(x => x.id === id);
  5263. if (!r) return;
  5264. const now = Date.now();
  5265. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5266. state.mangleLastTimestamp = now;
  5267. const curBytes = r.bytes || 0;
  5268. const curPackets = r.packets || 0;
  5269. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5270. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5271. state.mangleLastBytes = curBytes;
  5272. state.mangleLastPackets = curPackets;
  5273. const rateBps = Math.round((deltaBytes * 8) / dt);
  5274. const ratePkt = Math.round(deltaPkts / dt);
  5275. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5276. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5277. state.mangleStatRateHistory.push(rateBps);
  5278. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5279. state.mangleStatPktHistory.push(ratePkt);
  5280. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5281. const bEl = document.getElementById('mangle-stat-bytes');
  5282. const pEl = document.getElementById('mangle-stat-packets');
  5283. const rEl = document.getElementById('mangle-stat-rate');
  5284. const prEl = document.getElementById('mangle-stat-pktrate');
  5285. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5286. if (pEl) pEl.value = curPackets.toLocaleString();
  5287. if (rEl) rEl.value = formatBps(rateBps);
  5288. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5289. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5290. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5291. } catch (e) {
  5292. console.error('Error polling Mangle rule stats', e);
  5293. }
  5294. }
  5295. async function moveMangleRule(id, dir) {
  5296. try {
  5297. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5298. method: 'POST',
  5299. headers: { 'Content-Type': 'application/json' },
  5300. body: JSON.stringify({ direction: dir })
  5301. });
  5302. if (res.ok) loadFirewall(false);
  5303. } catch (err) {
  5304. showToast('Error', err.message, 'error');
  5305. }
  5306. }
  5307. async function toggleMangleRuleState(id, disabled) {
  5308. try {
  5309. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5310. method: 'POST',
  5311. headers: { 'Content-Type': 'application/json' },
  5312. body: JSON.stringify({ disabled })
  5313. });
  5314. if (res.ok) loadFirewall(false);
  5315. } catch (err) {
  5316. showToast('Error', err.message, 'error');
  5317. }
  5318. }
  5319. async function deleteMangleRule(id) {
  5320. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5321. try {
  5322. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5323. if (res.ok) {
  5324. showToast('Deleted', 'Mangle rule removed', 'success');
  5325. loadFirewall(false);
  5326. }
  5327. } catch (err) {
  5328. showToast('Error', err.message, 'error');
  5329. }
  5330. }
  5331. // ----------------- Address Lists -----------------
  5332. function renderAddressLists() {
  5333. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5334. const tbody = document.getElementById('addrlist-table-body');
  5335. const empty = document.getElementById('addrlist-empty');
  5336. if (!tbody) return;
  5337. tbody.innerHTML = '';
  5338. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5339. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5340. // Update filter select
  5341. const sel = document.getElementById('addrlist-filter-name');
  5342. if (sel) {
  5343. const cur = sel.value;
  5344. sel.innerHTML = '<option value="">All Lists</option>';
  5345. const set = new Set((state.addressLists || []).map(a => a.name));
  5346. set.forEach(n => {
  5347. const opt = document.createElement('option');
  5348. opt.value = n;
  5349. opt.innerText = n;
  5350. if (n === cur) opt.selected = true;
  5351. sel.appendChild(opt);
  5352. });
  5353. }
  5354. if (entries.length === 0) {
  5355. empty?.classList.remove('hidden');
  5356. return;
  5357. }
  5358. empty?.classList.add('hidden');
  5359. entries.forEach((e, idx) => {
  5360. const tr = document.createElement('tr');
  5361. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5362. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5363. tr.innerHTML = `
  5364. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5365. <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>
  5366. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5367. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5368. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5369. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5370. <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>
  5371. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5372. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5373. </td>
  5374. `;
  5375. tbody.appendChild(tr);
  5376. });
  5377. populateCommonAddrListDatalist();
  5378. }
  5379. function openAddAddrListModal() {
  5380. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5381. document.getElementById('addrlist-modal-id').value = '';
  5382. document.getElementById('addrlist-modal-name').value = '';
  5383. document.getElementById('addrlist-modal-addr').value = '';
  5384. document.getElementById('addrlist-modal-comment').value = '';
  5385. document.getElementById('addrlist-modal-disabled').checked = false;
  5386. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5387. if (submitBtn) submitBtn.innerText = 'Add to List';
  5388. document.getElementById('addrlist-modal').classList.remove('hidden');
  5389. }
  5390. function openEditAddrListModal(id) {
  5391. const e = (state.addressLists || []).find(item => item.id === id);
  5392. if (!e) return;
  5393. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5394. document.getElementById('addrlist-modal-id').value = e.id;
  5395. document.getElementById('addrlist-modal-name').value = e.name;
  5396. document.getElementById('addrlist-modal-addr').value = e.address;
  5397. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5398. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5399. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5400. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5401. document.getElementById('addrlist-modal').classList.remove('hidden');
  5402. }
  5403. function closeAddrListModal() {
  5404. document.getElementById('addrlist-modal').classList.add('hidden');
  5405. }
  5406. async function submitSaveAddrList(e) {
  5407. e.preventDefault();
  5408. const id = document.getElementById('addrlist-modal-id').value;
  5409. const name = document.getElementById('addrlist-modal-name').value.trim();
  5410. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5411. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5412. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5413. try {
  5414. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5415. method: 'POST',
  5416. headers: { 'Content-Type': 'application/json' },
  5417. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5418. });
  5419. if (res.ok) {
  5420. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5421. closeAddrListModal();
  5422. loadFirewall(false);
  5423. } else {
  5424. const err = await res.json();
  5425. showToast('Error', err.message || 'Failed to save address list', 'error');
  5426. }
  5427. } catch (err) {
  5428. showToast('Error', err.message, 'error');
  5429. }
  5430. }
  5431. async function toggleAddrListState(id, disabled) {
  5432. try {
  5433. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5434. method: 'POST',
  5435. headers: { 'Content-Type': 'application/json' },
  5436. body: JSON.stringify({ disabled })
  5437. });
  5438. if (res.ok) {
  5439. loadFirewall(false);
  5440. }
  5441. } catch (err) {
  5442. showToast('Error', err.message, 'error');
  5443. }
  5444. }
  5445. async function deleteAddrList(id) {
  5446. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5447. try {
  5448. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5449. if (res.ok) {
  5450. showToast('Deleted', 'Address list item removed', 'info');
  5451. loadFirewall(false);
  5452. }
  5453. } catch (err) {
  5454. showToast('Error', err.message, 'error');
  5455. }
  5456. }
  5457. // ----------------- Geo-Location IP Management -----------------
  5458. async function loadGeoIP() {
  5459. try {
  5460. const [statusRes, countriesRes] = await Promise.all([
  5461. fetch(`${API_BASE}/firewall/geoip/status`),
  5462. fetch(`${API_BASE}/firewall/geoip/countries`)
  5463. ]);
  5464. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5465. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5466. updateGeoHeader();
  5467. renderGeoCountries();
  5468. } catch (err) {
  5469. console.error('Failed to load GeoIP:', err);
  5470. }
  5471. }
  5472. function getGeoUsageMap() {
  5473. const usage = {};
  5474. const checkRule = (r, type) => {
  5475. ['src_geoip', 'dst_geoip'].forEach(field => {
  5476. let val = (r && r[field]) || '';
  5477. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5478. if (code) {
  5479. if (!usage[code]) usage[code] = [];
  5480. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5481. if (!usage[code].includes(label)) usage[code].push(label);
  5482. }
  5483. });
  5484. };
  5485. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5486. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5487. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5488. return usage;
  5489. }
  5490. function updateGeoHeader() {
  5491. const s = state.geoStatus || {};
  5492. const statusBadge = document.getElementById('geo-status-badge');
  5493. if (statusBadge) {
  5494. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5495. statusBadge.className = s.auto_update
  5496. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5497. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5498. }
  5499. const intervalLabel = document.getElementById('geo-interval-label');
  5500. if (intervalLabel) {
  5501. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5502. }
  5503. const usageMap = getGeoUsageMap();
  5504. const inUseCount = Object.keys(usageMap).length;
  5505. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5506. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5507. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5508. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5509. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5510. if (lastSyncEl) {
  5511. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5512. const d = new Date(s.last_updated);
  5513. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5514. } else {
  5515. lastSyncEl.innerText = 'Never (Sync Pending)';
  5516. }
  5517. }
  5518. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5519. if (nextSyncEl) {
  5520. if (s.next_update && !s.next_update.startsWith('0001')) {
  5521. const d = new Date(s.next_update);
  5522. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5523. } else {
  5524. nextSyncEl.innerText = '-';
  5525. }
  5526. }
  5527. const badge = document.getElementById('fw-badge-geo');
  5528. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5529. }
  5530. function renderGeoCountries() {
  5531. const tbody = document.getElementById('geo-table-body');
  5532. const empty = document.getElementById('geo-empty');
  5533. if (!tbody) return;
  5534. tbody.innerHTML = '';
  5535. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5536. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5537. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5538. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5539. const usageMap = getGeoUsageMap();
  5540. const countries = (state.geoCountries || []).filter(c => {
  5541. const isUsed = !!usageMap[c.code];
  5542. if (inUseOnly && !isUsed) return false;
  5543. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5544. if (continent && c.continent !== continent) return false;
  5545. if (q) {
  5546. const matchCode = c.code.toLowerCase().includes(q);
  5547. const matchName = c.name.toLowerCase().includes(q);
  5548. if (!matchCode && !matchName) return false;
  5549. }
  5550. return true;
  5551. });
  5552. if (countries.length === 0) {
  5553. empty?.classList.remove('hidden');
  5554. return;
  5555. }
  5556. empty?.classList.add('hidden');
  5557. countries.forEach(c => {
  5558. const tr = document.createElement('tr');
  5559. const isUsed = !!usageMap[c.code];
  5560. const rulesUsing = usageMap[c.code] || [];
  5561. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5562. let statusHtml = '';
  5563. if (isUsed) {
  5564. 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>`;
  5565. } else if (c.subnet_count > 0) {
  5566. 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>';
  5567. } else {
  5568. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5569. }
  5570. tr.innerHTML = `
  5571. <td class="py-2.5 px-3 text-center">
  5572. <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'}">
  5573. ${c.code}
  5574. </span>
  5575. </td>
  5576. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5577. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5578. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5579. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5580. </td>
  5581. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5582. <td class="py-2.5 px-3">
  5583. ${statusHtml}
  5584. </td>
  5585. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5586. <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>
  5587. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5588. </td>
  5589. `;
  5590. tbody.appendChild(tr);
  5591. });
  5592. }
  5593. function quickFilterGeo(preset) {
  5594. const searchInput = document.getElementById('geo-search-input');
  5595. const continentSel = document.getElementById('geo-continent-filter');
  5596. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5597. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5598. if (searchInput) searchInput.value = '';
  5599. if (continentSel) continentSel.value = '';
  5600. if (inUseCheck) inUseCheck.checked = false;
  5601. if (cachedCheck) cachedCheck.checked = false;
  5602. if (preset === 'GR') {
  5603. if (searchInput) searchInput.value = 'Greece';
  5604. } else if (preset === 'Europe') {
  5605. if (continentSel) continentSel.value = 'Europe';
  5606. } else if (preset === 'HIGHRISK') {
  5607. if (searchInput) searchInput.value = 'China';
  5608. }
  5609. renderGeoCountries();
  5610. }
  5611. async function toggleGeoCountry(code, enabled) {
  5612. try {
  5613. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5614. method: 'POST',
  5615. headers: { 'Content-Type': 'application/json' },
  5616. body: JSON.stringify({ enabled })
  5617. });
  5618. if (res.ok) {
  5619. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5620. loadGeoIP();
  5621. } else {
  5622. const err = await res.json();
  5623. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5624. }
  5625. } catch (err) {
  5626. showToast('Error', err.message, 'error');
  5627. }
  5628. }
  5629. async function updateGeoCountry(code) {
  5630. try {
  5631. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5632. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5633. if (res.ok) {
  5634. const data = await res.json();
  5635. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5636. loadGeoIP();
  5637. } else {
  5638. const err = await res.json();
  5639. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5640. }
  5641. } catch (err) {
  5642. showToast('Error', err.message, 'error');
  5643. }
  5644. }
  5645. async function triggerGeoUpdateNow() {
  5646. const spinner = document.getElementById('geo-update-spinner');
  5647. if (spinner) spinner.classList.remove('hidden');
  5648. try {
  5649. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5650. if (res.ok) {
  5651. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5652. setTimeout(() => {
  5653. loadGeoIP();
  5654. if (spinner) spinner.classList.add('hidden');
  5655. }, 2500);
  5656. } else {
  5657. const err = await res.json();
  5658. showToast('Notice', err.message || 'Update in progress', 'info');
  5659. if (spinner) spinner.classList.add('hidden');
  5660. }
  5661. } catch (err) {
  5662. showToast('Error', err.message, 'error');
  5663. if (spinner) spinner.classList.add('hidden');
  5664. }
  5665. }
  5666. async function applyGeoPreset(preset) {
  5667. try {
  5668. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5669. method: 'POST',
  5670. headers: { 'Content-Type': 'application/json' },
  5671. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5672. });
  5673. if (res.ok) {
  5674. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5675. loadGeoIP();
  5676. }
  5677. } catch (err) {
  5678. showToast('Error', err.message, 'error');
  5679. }
  5680. }
  5681. function openGeoIntervalModal() {
  5682. const s = state.geoStatus || {};
  5683. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5684. const sel = document.getElementById('geo-cfg-interval');
  5685. const customBox = document.getElementById('geo-cfg-custom-box');
  5686. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5687. const curHours = s.interval_hours || 24;
  5688. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5689. if (matchOption) {
  5690. sel.value = String(curHours);
  5691. customBox.classList.add('hidden');
  5692. } else {
  5693. sel.value = 'custom';
  5694. customHoursInput.value = curHours;
  5695. customBox.classList.remove('hidden');
  5696. }
  5697. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5698. }
  5699. function closeGeoIntervalModal() {
  5700. document.getElementById('geo-interval-modal').classList.add('hidden');
  5701. }
  5702. function toggleCustomGeoInterval() {
  5703. const val = document.getElementById('geo-cfg-interval').value;
  5704. const customBox = document.getElementById('geo-cfg-custom-box');
  5705. if (val === 'custom') {
  5706. customBox.classList.remove('hidden');
  5707. } else {
  5708. customBox.classList.add('hidden');
  5709. }
  5710. }
  5711. async function submitGeoIntervalSettings(e) {
  5712. e.preventDefault();
  5713. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5714. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5715. let hours = 24;
  5716. if (intervalVal === 'custom') {
  5717. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5718. } else {
  5719. hours = parseInt(intervalVal, 10) || 24;
  5720. }
  5721. try {
  5722. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5723. method: 'POST',
  5724. headers: { 'Content-Type': 'application/json' },
  5725. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5726. });
  5727. if (res.ok) {
  5728. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5729. closeGeoIntervalModal();
  5730. loadGeoIP();
  5731. } else {
  5732. const err = await res.json();
  5733. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5734. }
  5735. } catch (err) {
  5736. showToast('Error', err.message, 'error');
  5737. }
  5738. }
  5739. async function viewGeoSubnets(code, name) {
  5740. if (!name) {
  5741. const found = (state.geoCountries || []).find(x => x.code === code);
  5742. name = found ? found.name : code;
  5743. }
  5744. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5745. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5746. const listEl = document.getElementById('geo-subnets-list');
  5747. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5748. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5749. try {
  5750. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5751. if (res.ok) {
  5752. const data = await res.json();
  5753. const subnets = data.subnets || [];
  5754. if (subnets.length === 0) {
  5755. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5756. } else {
  5757. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5758. }
  5759. } else {
  5760. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5761. }
  5762. } catch (err) {
  5763. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5764. }
  5765. }
  5766. function closeGeoSubnetsModal() {
  5767. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5768. }
  5769. // ----------------- Active Connections Tracking -----------------
  5770. async function loadConnections() {
  5771. try {
  5772. const res = await fetch(`${API_BASE}/firewall/connections`);
  5773. const data = await res.json();
  5774. state.connections = Array.isArray(data) ? data : [];
  5775. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5776. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5777. renderConnections();
  5778. } catch (err) {
  5779. console.error('Failed to load connections:', err);
  5780. }
  5781. }
  5782. function renderConnections() {
  5783. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5784. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5785. const tbody = document.getElementById('conns-table-body');
  5786. const empty = document.getElementById('conns-empty');
  5787. if (!tbody) return;
  5788. tbody.innerHTML = '';
  5789. const conns = (state.connections || []).filter(c => {
  5790. if (protoFilter && c.protocol !== protoFilter) return false;
  5791. if (search) {
  5792. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5793. if (!line.includes(search)) return false;
  5794. }
  5795. return true;
  5796. });
  5797. if (conns.length === 0) {
  5798. empty?.classList.remove('hidden');
  5799. return;
  5800. }
  5801. empty?.classList.add('hidden');
  5802. conns.slice(0, 150).forEach(c => {
  5803. const tr = document.createElement('tr');
  5804. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5805. let stateColor = 'text-slate-400';
  5806. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5807. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5808. tr.innerHTML = `
  5809. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5810. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5811. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5812. <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>
  5813. <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>
  5814. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5815. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5816. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5817. <td class="py-2.5 px-3 text-right font-sans">
  5818. <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>
  5819. </td>
  5820. `;
  5821. tbody.appendChild(tr);
  5822. });
  5823. }
  5824. async function killConnection(protocol, src, sport, dst, dport) {
  5825. try {
  5826. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5827. method: 'POST',
  5828. headers: { 'Content-Type': 'application/json' },
  5829. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5830. });
  5831. if (res.ok) {
  5832. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5833. loadConnections();
  5834. }
  5835. } catch (err) {
  5836. showToast('Error', err.message, 'error');
  5837. }
  5838. }
  5839. async function resetFirewallCounters() {
  5840. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5841. try {
  5842. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5843. if (res.ok) {
  5844. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5845. loadFirewall(false);
  5846. }
  5847. } catch (err) {
  5848. showToast('Error', err.message, 'error');
  5849. }
  5850. }
  5851. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5852. function switchRoutesSubTab(tab) {
  5853. state.routesSubTab = tab;
  5854. const tabs = ['routes', 'rules', 'tables'];
  5855. tabs.forEach(t => {
  5856. const panel = document.getElementById(`routes-subtab-${t}`);
  5857. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5858. if (panel) {
  5859. if (t === tab) panel.classList.remove('hidden');
  5860. else panel.classList.add('hidden');
  5861. }
  5862. if (btn) {
  5863. if (t === tab) {
  5864. 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';
  5865. } else {
  5866. 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';
  5867. }
  5868. }
  5869. });
  5870. setTimeout(initTableSorting, 50);
  5871. }
  5872. async function loadRoutes() {
  5873. try {
  5874. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5875. fetch(`${API_BASE}/routes`),
  5876. fetch(`${API_BASE}/routing/rules`),
  5877. fetch(`${API_BASE}/routing/tables`)
  5878. ]);
  5879. if (routesRes.ok) state.routes = await routesRes.json();
  5880. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5881. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5882. const bRoutes = document.getElementById('routes-badge-routes');
  5883. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5884. const showSystem = document.getElementById('prule-show-system')?.checked;
  5885. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5886. const bRules = document.getElementById('routes-badge-rules');
  5887. if (bRules) bRules.innerText = userRules.length;
  5888. const bTables = document.getElementById('routes-badge-tables');
  5889. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5890. const bRoutesCount = document.getElementById('badge-routes-count');
  5891. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5892. renderRoutesList();
  5893. renderPolicyRules();
  5894. renderRoutingTables();
  5895. } catch (err) {
  5896. console.error('Failed to load routing:', err);
  5897. }
  5898. }
  5899. function getRouteProtocolBadge(proto) {
  5900. const p = (proto || 'static').toLowerCase();
  5901. switch (p) {
  5902. case 'bgp':
  5903. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  5904. case 'ibgp':
  5905. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  5906. case 'ospf':
  5907. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  5908. case 'rip':
  5909. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  5910. case 'static':
  5911. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  5912. case 'connected':
  5913. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  5914. case 'dhcp':
  5915. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  5916. case 'multicast':
  5917. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  5918. default:
  5919. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  5920. }
  5921. }
  5922. function renderRoutesList() {
  5923. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5924. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  5925. const tbody = document.getElementById('routes-table-body');
  5926. const empty = document.getElementById('routes-empty');
  5927. if (!tbody) return;
  5928. // Update table filter select
  5929. const sel = document.getElementById('routes-filter-table');
  5930. if (sel) {
  5931. const cur = sel.value;
  5932. sel.innerHTML = '<option value="">All Tables</option>';
  5933. (state.routingTables || []).forEach(t => {
  5934. const opt = document.createElement('option');
  5935. opt.value = t.name;
  5936. opt.innerText = t.name;
  5937. if (t.name === cur) opt.selected = true;
  5938. sel.appendChild(opt);
  5939. });
  5940. }
  5941. const routes = (state.routes || []).filter(r => {
  5942. if (tableFilter && r.routing_table !== tableFilter) return false;
  5943. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  5944. if (typeFilter === 'multicast' && !r.multicast) return false;
  5945. if (typeFilter === 'static' && !r.static) return false;
  5946. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  5947. if (typeFilter === 'connected' && !r.connect) return false;
  5948. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  5949. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  5950. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  5951. return true;
  5952. });
  5953. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  5954. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  5955. let summaryText = `${routes.length} Routes`;
  5956. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  5957. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  5958. const badgeEl = document.getElementById('routes-count-badge');
  5959. if (badgeEl) badgeEl.innerText = summaryText;
  5960. if (routes.length === 0) {
  5961. empty?.classList.remove('hidden');
  5962. tbody.innerHTML = '';
  5963. return;
  5964. }
  5965. empty?.classList.add('hidden');
  5966. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  5967. if (tbody.dataset.sig === sig) {
  5968. return; // Routes table unchanged! Do not wipe DOM or flicker!
  5969. }
  5970. tbody.dataset.sig = sig;
  5971. tbody.innerHTML = '';
  5972. routes.forEach(r => {
  5973. const tr = document.createElement('tr');
  5974. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5975. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5976. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  5977. let flags = '';
  5978. if (r.dynamic) flags += 'D';
  5979. if (r.active) flags += 'A';
  5980. if (r.connect) flags += 'C';
  5981. if (r.static) flags += 'S';
  5982. if (r.ecmp) flags += 'E';
  5983. if (r.multicast) flags += 'M';
  5984. if (r.disabled) flags += 'X';
  5985. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5986. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  5987. if (r.check_gateway === 'internet') {
  5988. if (r.health_status === 'online') {
  5989. const ms = (r.health_rtt_ms || 0).toFixed(0);
  5990. healthCell = `
  5991. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  5992. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  5993. <span>Internet OK (${ms}ms)</span>
  5994. </span>
  5995. `;
  5996. } else if (r.health_status === 'offline') {
  5997. healthCell = `
  5998. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  5999. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6000. <span>Internet Down</span>
  6001. </span>
  6002. `;
  6003. } else {
  6004. healthCell = `
  6005. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  6006. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6007. <span>Checking...</span>
  6008. </span>
  6009. `;
  6010. }
  6011. } else if (r.check_gateway === 'ping') {
  6012. if (r.health_status === 'online') {
  6013. healthCell = `
  6014. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  6015. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6016. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6017. </span>
  6018. `;
  6019. } else if (r.health_status === 'offline') {
  6020. healthCell = `
  6021. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  6022. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6023. <span>Gateway Dead</span>
  6024. </span>
  6025. `;
  6026. }
  6027. }
  6028. const flagDescriptions = [];
  6029. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6030. if (r.active) flagDescriptions.push('Active (A)');
  6031. if (r.connect) flagDescriptions.push('Connected (C)');
  6032. if (r.static) flagDescriptions.push('Static (S)');
  6033. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6034. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6035. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6036. tr.innerHTML = `
  6037. <td class="py-2.5 px-3 text-center">
  6038. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6039. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  6040. }" title="Flags: ${flagDescriptions.join(', ')}">
  6041. ${flags || '-'}
  6042. </span>
  6043. </td>
  6044. <td class="py-2.5 px-3">
  6045. <div class="flex items-center gap-1.5 flex-wrap">
  6046. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6047. ${r.ecmp ? `
  6048. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  6049. <span>⚡ ECMP</span>
  6050. </span>
  6051. ` : ''}
  6052. ${r.multicast ? `
  6053. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  6054. <span>IGMP</span>
  6055. </span>
  6056. ` : ''}
  6057. </div>
  6058. </td>
  6059. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6060. <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>
  6061. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6062. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6063. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6064. <td class="py-2.5 px-3">${healthCell}</td>
  6065. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6066. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6067. ${r.static ? `
  6068. <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>
  6069. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6070. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6071. ` : `
  6072. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6073. `}
  6074. </td>
  6075. `;
  6076. tbody.appendChild(tr);
  6077. });
  6078. }
  6079. function openAddRouteModal() {
  6080. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6081. document.getElementById('route-modal-id').value = '';
  6082. document.getElementById('route-modal-old-dst').value = '';
  6083. document.getElementById('route-modal-old-gw').value = '';
  6084. document.getElementById('route-modal-old-distance').value = '';
  6085. document.getElementById('route-modal-old-table').value = '';
  6086. document.getElementById('route-modal-old-iface').value = '';
  6087. const dstInput = document.getElementById('route-modal-dst');
  6088. const gwInput = document.getElementById('route-modal-gw');
  6089. const distInput = document.getElementById('route-modal-distance');
  6090. const ifaceSelect = document.getElementById('route-modal-iface');
  6091. const tableSelect = document.getElementById('route-modal-table');
  6092. const commentInput = document.getElementById('route-modal-comment');
  6093. const disCheck = document.getElementById('route-modal-disabled');
  6094. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6095. dstInput.disabled = false;
  6096. dstInput.value = '0.0.0.0/0';
  6097. gwInput.disabled = false;
  6098. gwInput.value = '';
  6099. distInput.disabled = false;
  6100. distInput.value = '1';
  6101. ifaceSelect.disabled = false;
  6102. tableSelect.disabled = false;
  6103. commentInput.disabled = false;
  6104. commentInput.value = '';
  6105. disCheck.disabled = false;
  6106. disCheck.checked = false;
  6107. if (saveBtn) saveBtn.classList.remove('hidden');
  6108. const checkGw = document.getElementById('route-modal-check-gw');
  6109. if (checkGw) checkGw.value = 'internet';
  6110. const checkTarget = document.getElementById('route-modal-check-target');
  6111. if (checkTarget) checkTarget.value = '1.1.1.1';
  6112. const checkInterval = document.getElementById('route-modal-check-interval');
  6113. if (checkInterval) checkInterval.value = '5';
  6114. const checkThresh = document.getElementById('route-modal-check-threshold');
  6115. if (checkThresh) checkThresh.value = '3';
  6116. toggleRouteCheckModeUI();
  6117. populateInterfaceSelect('route-modal-iface');
  6118. // Populate tables
  6119. tableSelect.innerHTML = '';
  6120. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6121. const opt = document.createElement('option');
  6122. opt.value = t.name;
  6123. opt.innerText = t.name;
  6124. if (t.name === 'main') opt.selected = true;
  6125. tableSelect.appendChild(opt);
  6126. });
  6127. document.getElementById('route-modal').classList.remove('hidden');
  6128. }
  6129. function openEditRouteModal(id) {
  6130. const r = (state.routes || []).find(route => route.id === id);
  6131. if (!r) return;
  6132. const isStatic = !!r.static;
  6133. document.getElementById('route-modal-title').innerText = isStatic
  6134. ? `Edit Route: ${r.dst_address}`
  6135. : `Route Properties (Read Only): ${r.dst_address}`;
  6136. document.getElementById('route-modal-id').value = r.id;
  6137. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6138. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6139. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6140. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6141. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6142. const dstInput = document.getElementById('route-modal-dst');
  6143. const gwInput = document.getElementById('route-modal-gw');
  6144. const distInput = document.getElementById('route-modal-distance');
  6145. const ifaceSelect = document.getElementById('route-modal-iface');
  6146. const tableSelect = document.getElementById('route-modal-table');
  6147. const commentInput = document.getElementById('route-modal-comment');
  6148. const disCheck = document.getElementById('route-modal-disabled');
  6149. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6150. dstInput.value = r.dst_address;
  6151. gwInput.value = r.gateway || '';
  6152. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6153. commentInput.value = r.comment || '';
  6154. disCheck.checked = !!r.disabled;
  6155. const checkGw = document.getElementById('route-modal-check-gw');
  6156. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6157. const checkTarget = document.getElementById('route-modal-check-target');
  6158. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6159. const checkInterval = document.getElementById('route-modal-check-interval');
  6160. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6161. const checkThresh = document.getElementById('route-modal-check-threshold');
  6162. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6163. toggleRouteCheckModeUI();
  6164. dstInput.disabled = !isStatic;
  6165. gwInput.disabled = !isStatic;
  6166. distInput.disabled = !isStatic;
  6167. ifaceSelect.disabled = !isStatic;
  6168. tableSelect.disabled = !isStatic;
  6169. commentInput.disabled = !isStatic;
  6170. disCheck.disabled = !isStatic;
  6171. if (checkGw) checkGw.disabled = !isStatic;
  6172. if (checkTarget) checkTarget.disabled = !isStatic;
  6173. if (checkInterval) checkInterval.disabled = !isStatic;
  6174. if (checkThresh) checkThresh.disabled = !isStatic;
  6175. if (saveBtn) {
  6176. if (isStatic) {
  6177. saveBtn.classList.remove('hidden');
  6178. } else {
  6179. saveBtn.classList.add('hidden');
  6180. }
  6181. }
  6182. populateInterfaceSelect('route-modal-iface', r.interface);
  6183. tableSelect.innerHTML = '';
  6184. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6185. const opt = document.createElement('option');
  6186. opt.value = t.name;
  6187. opt.innerText = t.name;
  6188. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6189. tableSelect.appendChild(opt);
  6190. });
  6191. document.getElementById('route-modal').classList.remove('hidden');
  6192. }
  6193. function closeRouteModal() {
  6194. document.getElementById('route-modal').classList.add('hidden');
  6195. }
  6196. function setRouteCheckTarget(ip) {
  6197. const inp = document.getElementById('route-modal-check-target');
  6198. if (inp) inp.value = ip;
  6199. }
  6200. function toggleRouteCheckModeUI() {
  6201. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6202. const targetRow = document.getElementById('route-row-check-target');
  6203. const paramsRow = document.getElementById('route-row-check-params');
  6204. if (mode === 'none') {
  6205. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6206. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6207. } else if (mode === 'ping') {
  6208. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6209. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6210. } else { // internet
  6211. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6212. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6213. }
  6214. }
  6215. async function submitSaveRoute(e) {
  6216. e.preventDefault();
  6217. const id = document.getElementById('route-modal-id').value;
  6218. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6219. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6220. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6221. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6222. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6223. const dst = document.getElementById('route-modal-dst').value.trim();
  6224. const gw = document.getElementById('route-modal-gw').value.trim();
  6225. const table = document.getElementById('route-modal-table').value;
  6226. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6227. const iface = document.getElementById('route-modal-iface').value;
  6228. const comment = document.getElementById('route-modal-comment').value.trim();
  6229. const disabled = document.getElementById('route-modal-disabled').checked;
  6230. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6231. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6232. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6233. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6234. if (!dst) {
  6235. showToast('Error', 'Destination address is required', 'error');
  6236. return;
  6237. }
  6238. if (!gw && !iface) {
  6239. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6240. return;
  6241. }
  6242. const payload = {
  6243. id,
  6244. old_dst_address: oldDst,
  6245. old_gateway: oldGw,
  6246. old_routing_table: oldTable,
  6247. old_interface: oldIface,
  6248. dst_address: dst,
  6249. gateway: gw || iface,
  6250. routing_table: table,
  6251. distance,
  6252. interface: iface,
  6253. comment,
  6254. disabled,
  6255. check_gateway,
  6256. check_target,
  6257. check_interval,
  6258. check_threshold
  6259. };
  6260. if (oldDistStr !== undefined && oldDistStr !== '') {
  6261. payload.old_distance = parseInt(oldDistStr, 10);
  6262. }
  6263. try {
  6264. const res = await fetch(`${API_BASE}/routes`, {
  6265. method: 'POST',
  6266. headers: { 'Content-Type': 'application/json' },
  6267. body: JSON.stringify(payload)
  6268. });
  6269. if (res.ok) {
  6270. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6271. closeRouteModal();
  6272. loadRoutes();
  6273. } else {
  6274. const err = await res.json();
  6275. showToast('Error', err.message || 'Failed to save route', 'error');
  6276. }
  6277. } catch (err) {
  6278. showToast('Error', err.message, 'error');
  6279. }
  6280. }
  6281. async function toggleRouteState(id, disabled) {
  6282. try {
  6283. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6284. method: 'POST',
  6285. headers: { 'Content-Type': 'application/json' },
  6286. body: JSON.stringify({ disabled })
  6287. });
  6288. if (res.ok) loadRoutes();
  6289. } catch (err) {
  6290. showToast('Error', err.message, 'error');
  6291. }
  6292. }
  6293. async function deleteRoute(id) {
  6294. if (!confirm('Are you sure you want to delete this route?')) return;
  6295. try {
  6296. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6297. if (res.ok) {
  6298. showToast('Deleted', 'Route removed', 'success');
  6299. loadRoutes();
  6300. }
  6301. } catch (err) {
  6302. showToast('Error', err.message, 'error');
  6303. }
  6304. }
  6305. // ----------------- Policy Rules (/ip route rule) -----------------
  6306. function renderPolicyRules() {
  6307. const tbody = document.getElementById('rules-table-body');
  6308. const empty = document.getElementById('rules-empty');
  6309. if (!tbody) return;
  6310. const showSystem = document.getElementById('prule-show-system')?.checked;
  6311. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6312. const countBadge = document.getElementById('rules-count-badge');
  6313. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6314. const bRules = document.getElementById('routes-badge-rules');
  6315. if (bRules) bRules.innerText = filtered.length;
  6316. if (filtered.length === 0) {
  6317. empty?.classList.remove('hidden');
  6318. tbody.innerHTML = '';
  6319. return;
  6320. }
  6321. empty?.classList.add('hidden');
  6322. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6323. if (tbody.dataset.sig === sig) return;
  6324. tbody.dataset.sig = sig;
  6325. tbody.innerHTML = '';
  6326. filtered.forEach(pr => {
  6327. const isSys = pr.is_default || pr.is_system;
  6328. const tr = document.createElement('tr');
  6329. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6330. tr.innerHTML = `
  6331. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6332. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6333. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6334. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6335. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6336. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6337. <td class="py-2.5 px-3 text-right font-sans">
  6338. ${!pr.is_default ? `
  6339. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6340. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6341. </td>
  6342. `;
  6343. tbody.appendChild(tr);
  6344. });
  6345. }
  6346. function openAddPolicyRuleModal() {
  6347. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6348. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6349. document.getElementById('prule-modal-mark').value = '';
  6350. document.getElementById('prule-modal-src').value = '';
  6351. document.getElementById('prule-modal-dst').value = '';
  6352. const sel = document.getElementById('prule-modal-table');
  6353. sel.innerHTML = '';
  6354. (state.routingTables || []).forEach(t => {
  6355. const opt = document.createElement('option');
  6356. opt.value = t.name;
  6357. opt.innerText = t.name;
  6358. sel.appendChild(opt);
  6359. });
  6360. document.getElementById('prule-modal').classList.remove('hidden');
  6361. }
  6362. function closePolicyRuleModal() {
  6363. document.getElementById('prule-modal').classList.add('hidden');
  6364. }
  6365. async function submitSavePolicyRule(e) {
  6366. e.preventDefault();
  6367. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6368. const mark = document.getElementById('prule-modal-mark').value.trim();
  6369. const src = document.getElementById('prule-modal-src').value.trim();
  6370. const dst = document.getElementById('prule-modal-dst').value.trim();
  6371. const table = document.getElementById('prule-modal-table').value;
  6372. const action = document.getElementById('prule-modal-action').value;
  6373. try {
  6374. const res = await fetch(`${API_BASE}/routing/rules`, {
  6375. method: 'POST',
  6376. headers: { 'Content-Type': 'application/json' },
  6377. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6378. });
  6379. if (res.ok) {
  6380. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6381. closePolicyRuleModal();
  6382. loadRoutes();
  6383. } else {
  6384. const err = await res.json();
  6385. showToast('Error', err.message, 'error');
  6386. }
  6387. } catch (err) {
  6388. showToast('Error', err.message, 'error');
  6389. }
  6390. }
  6391. async function deletePolicyRule(id) {
  6392. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6393. try {
  6394. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6395. if (res.ok) {
  6396. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6397. loadRoutes();
  6398. }
  6399. } catch (err) {
  6400. showToast('Error', err.message, 'error');
  6401. }
  6402. }
  6403. // ----------------- Routing Tables -----------------
  6404. function renderRoutingTables() {
  6405. const tbody = document.getElementById('tables-table-body');
  6406. if (!tbody) return;
  6407. const tables = state.routingTables || [];
  6408. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6409. if (tbody.dataset.sig === sig) return;
  6410. tbody.dataset.sig = sig;
  6411. tbody.innerHTML = '';
  6412. (state.routingTables || []).forEach(t => {
  6413. const tr = document.createElement('tr');
  6414. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6415. tr.innerHTML = `
  6416. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6417. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6418. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6419. `;
  6420. tbody.appendChild(tr);
  6421. });
  6422. }
  6423. function openAddTableModal() {
  6424. document.getElementById('table-modal-name').value = '';
  6425. document.getElementById('table-modal-id').value = '';
  6426. document.getElementById('table-modal-comment').value = '';
  6427. document.getElementById('table-modal').classList.remove('hidden');
  6428. }
  6429. function closeTableModal() {
  6430. document.getElementById('table-modal').classList.add('hidden');
  6431. }
  6432. async function submitSaveTable(e) {
  6433. e.preventDefault();
  6434. const name = document.getElementById('table-modal-name').value.trim();
  6435. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6436. const comment = document.getElementById('table-modal-comment').value.trim();
  6437. try {
  6438. const res = await fetch(`${API_BASE}/routing/tables`, {
  6439. method: 'POST',
  6440. headers: { 'Content-Type': 'application/json' },
  6441. body: JSON.stringify({ name, table_id: id, comment })
  6442. });
  6443. if (res.ok) {
  6444. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6445. closeTableModal();
  6446. loadRoutes();
  6447. } else {
  6448. const err = await res.json();
  6449. showToast('Error', err.message, 'error');
  6450. }
  6451. } catch (err) {
  6452. showToast('Error', err.message, 'error');
  6453. }
  6454. }
  6455. async function loadDebianConfig() {
  6456. const view = document.getElementById('debian-config-view');
  6457. view.innerText = 'Generating live configuration...';
  6458. try {
  6459. const res = await fetch(`${API_BASE}/debian/config`);
  6460. const data = await res.json();
  6461. view.innerText = data.content || '# Empty config';
  6462. } catch (err) {
  6463. view.innerText = 'Failed to generate Debian network config.';
  6464. }
  6465. }
  6466. async function saveDebianConfig() {
  6467. try {
  6468. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6469. const data = await res.json();
  6470. if (res.ok) {
  6471. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6472. loadDebianConfig();
  6473. }
  6474. } catch (err) {
  6475. showToast('Error', err.message, 'error');
  6476. }
  6477. }
  6478. function showToast(title, message, type = 'info') {
  6479. const container = document.getElementById('toast-container');
  6480. const toast = document.createElement('div');
  6481. const borderColors = {
  6482. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6483. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6484. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6485. };
  6486. 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}`;
  6487. toast.innerHTML = `
  6488. <div class="flex-1">
  6489. <div class="font-bold text-xs text-white">${title}</div>
  6490. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6491. </div>
  6492. `;
  6493. container.appendChild(toast);
  6494. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6495. setTimeout(() => {
  6496. toast.classList.add('opacity-0', 'translate-y-2');
  6497. setTimeout(() => toast.remove(), 300);
  6498. }, 4000);
  6499. }
  6500. function formatTraffic(bytesPerSec) {
  6501. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6502. const kb = bytesPerSec / 1024;
  6503. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6504. const mb = kb / 1024;
  6505. return `${mb.toFixed(2)} MB/s`;
  6506. }
  6507. function toggleSidebar() {
  6508. const sb = document.getElementById('sidebar');
  6509. sb.classList.toggle('-translate-x-full');
  6510. }
  6511. // ======================== EoIP (Ethernet over IP) ========================
  6512. async function loadEoIP(populate = true) {
  6513. try {
  6514. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6515. const data = await res.json();
  6516. state.eoipTunnels = Array.isArray(data) ? data : [];
  6517. const badge = document.getElementById('eoip-count-badge');
  6518. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6519. const sideBadge = document.getElementById('badge-eoip-count');
  6520. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6521. renderEoIPTunnels();
  6522. } catch (err) {
  6523. console.error('Failed to load EoIP:', err);
  6524. }
  6525. }
  6526. function renderEoIPTunnels() {
  6527. const tbody = document.getElementById('eoip-table-body');
  6528. const empty = document.getElementById('eoip-empty');
  6529. if (!tbody) return;
  6530. tbody.innerHTML = '';
  6531. const tunnels = state.eoipTunnels || [];
  6532. if (tunnels.length === 0) {
  6533. empty?.classList.remove('hidden');
  6534. return;
  6535. }
  6536. empty?.classList.add('hidden');
  6537. tunnels.forEach(t => {
  6538. const tr = document.createElement('tr');
  6539. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6540. tr.innerHTML = `
  6541. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6542. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6543. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6544. <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>
  6545. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6546. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6547. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6548. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6549. <td class="py-2.5 px-3 font-mono text-[11px]">
  6550. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6551. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6552. </td>
  6553. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6554. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6555. <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>
  6556. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6557. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6558. </td>
  6559. `;
  6560. tbody.appendChild(tr);
  6561. });
  6562. }
  6563. function openAddEoIPModal() {
  6564. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6565. document.getElementById('eoip-modal-id').value = '';
  6566. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6567. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6568. document.getElementById('eoip-modal-remote').value = '';
  6569. document.getElementById('eoip-modal-ip').value = '';
  6570. document.getElementById('eoip-modal-local').value = '';
  6571. document.getElementById('eoip-modal-mac').value = '';
  6572. document.getElementById('eoip-modal-mtu').value = '1500';
  6573. document.getElementById('eoip-modal-comment').value = '';
  6574. document.getElementById('eoip-modal-clampmss').checked = true;
  6575. document.getElementById('eoip-modal-disabled').checked = false;
  6576. document.getElementById('eoip-modal').classList.remove('hidden');
  6577. }
  6578. function openEditEoIPModal(id) {
  6579. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6580. if (!t) return;
  6581. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6582. document.getElementById('eoip-modal-id').value = t.id;
  6583. document.getElementById('eoip-modal-name').value = t.name;
  6584. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6585. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6586. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6587. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6588. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6589. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6590. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6591. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6592. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6593. document.getElementById('eoip-modal').classList.remove('hidden');
  6594. }
  6595. function closeEoIPModal() {
  6596. document.getElementById('eoip-modal').classList.add('hidden');
  6597. }
  6598. async function submitSaveEoIP(e) {
  6599. e.preventDefault();
  6600. const id = document.getElementById('eoip-modal-id').value;
  6601. const name = document.getElementById('eoip-modal-name').value.trim();
  6602. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6603. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6604. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6605. const local = document.getElementById('eoip-modal-local').value.trim();
  6606. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6607. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6608. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6609. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6610. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6611. try {
  6612. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6613. method: 'POST',
  6614. headers: { 'Content-Type': 'application/json' },
  6615. body: JSON.stringify({
  6616. id,
  6617. name,
  6618. tunnel_id: tunnelId,
  6619. remote_address: remote,
  6620. ip_address: ipAddress,
  6621. local_address: local,
  6622. mac_address: mac,
  6623. mtu,
  6624. clamp_mss: clampMss,
  6625. comment,
  6626. disabled
  6627. })
  6628. });
  6629. if (res.ok) {
  6630. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6631. closeEoIPModal();
  6632. loadEoIP(false);
  6633. fetchData(false);
  6634. } else {
  6635. const err = await res.json();
  6636. showToast('Error', err.message, 'error');
  6637. }
  6638. } catch (err) {
  6639. showToast('Error', err.message, 'error');
  6640. }
  6641. }
  6642. async function toggleEoIPState(id, disabled) {
  6643. try {
  6644. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6645. method: 'POST',
  6646. headers: { 'Content-Type': 'application/json' },
  6647. body: JSON.stringify({ disabled })
  6648. });
  6649. if (res.ok) {
  6650. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6651. loadEoIP(false);
  6652. fetchData(false);
  6653. }
  6654. } catch (err) {
  6655. showToast('Error', err.message, 'error');
  6656. }
  6657. }
  6658. async function deleteEoIP(id) {
  6659. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6660. try {
  6661. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6662. if (res.ok) {
  6663. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6664. loadEoIP(false);
  6665. fetchData(false);
  6666. }
  6667. } catch (err) {
  6668. showToast('Error', err.message, 'error');
  6669. }
  6670. }
  6671. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6672. async function loadAeroTUN(populate = true) {
  6673. try {
  6674. const [tunnelsRes, statsRes] = await Promise.all([
  6675. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6676. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6677. ]);
  6678. if (tunnelsRes.ok) {
  6679. const data = await tunnelsRes.json();
  6680. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6681. }
  6682. if (statsRes.ok) {
  6683. state.aerotunStats = await statsRes.json();
  6684. }
  6685. const countBadge = document.getElementById('aerotun-count-badge');
  6686. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6687. const sideBadge = document.getElementById('badge-aerotun-count');
  6688. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6689. renderAeroTUN();
  6690. } catch (err) {
  6691. console.error('Failed to load AeroTUN:', err);
  6692. }
  6693. }
  6694. function renderAeroTUN() {
  6695. const tbody = document.getElementById('aerotun-table-body');
  6696. const empty = document.getElementById('aerotun-empty');
  6697. // Update summary cards
  6698. const stats = state.aerotunStats || {};
  6699. const tunnels = state.aerotunTunnels || [];
  6700. const statActive = document.getElementById('aerotun-stat-active');
  6701. if (statActive) {
  6702. const activeCount = tunnels.filter(t => t.running).length;
  6703. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6704. }
  6705. const statSaved = document.getElementById('aerotun-stat-saved');
  6706. if (statSaved) {
  6707. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6708. }
  6709. const statRatio = document.getElementById('aerotun-stat-ratio');
  6710. if (statRatio) {
  6711. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6712. }
  6713. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6714. if (statTraffic) {
  6715. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6716. }
  6717. if (!tbody) return;
  6718. tbody.innerHTML = '';
  6719. if (tunnels.length === 0) {
  6720. empty?.classList.remove('hidden');
  6721. return;
  6722. }
  6723. empty?.classList.add('hidden');
  6724. tunnels.forEach(t => {
  6725. const tr = document.createElement('tr');
  6726. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6727. const modeBadge = t.mode === 'server'
  6728. ? `<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>`
  6729. : `<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>`;
  6730. const endpointInfo = t.mode === 'server'
  6731. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6732. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6733. const compBadge = t.compression
  6734. ? `<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>`
  6735. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6736. const activePeer = t.active_peer_endpoint
  6737. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6738. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6739. const rawRx = formatBytes(t.rx_bytes || 0);
  6740. const rawTx = formatBytes(t.tx_bytes || 0);
  6741. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6742. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6743. tr.innerHTML = `
  6744. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6745. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6746. <span>${escapeHtml(t.name)}</span>
  6747. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6748. </td>
  6749. <td class="py-2.5 px-3">${modeBadge}</td>
  6750. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6751. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6752. <td class="py-2.5 px-3">${compBadge}</td>
  6753. <td class="py-2.5 px-3">${activePeer}</td>
  6754. <td class="py-2.5 px-3 font-mono text-[11px]">
  6755. <span class="text-emerald-400">↓ ${rawRx}</span>
  6756. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6757. </td>
  6758. <td class="py-2.5 px-3 font-mono text-[11px]">
  6759. <span class="text-slate-400">↓ ${wireRx}</span>
  6760. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6761. </td>
  6762. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6763. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6764. ${t.running
  6765. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6766. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6767. }
  6768. <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>
  6769. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6770. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6771. </td>
  6772. `;
  6773. tbody.appendChild(tr);
  6774. });
  6775. }
  6776. function onAeroTUNModeChange() {
  6777. const mode = document.getElementById('aerotun-modal-mode').value;
  6778. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6779. const portInput = document.getElementById('aerotun-modal-port');
  6780. if (mode === 'server') {
  6781. if (!portInput.value) portInput.value = '51830';
  6782. endpointInput.placeholder = 'Optional / learned roaming peer';
  6783. } else {
  6784. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6785. if (!portInput.value) portInput.value = '';
  6786. }
  6787. }
  6788. async function generateAeroTUNKey() {
  6789. try {
  6790. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6791. if (res.ok) {
  6792. const data = await res.json();
  6793. document.getElementById('aerotun-modal-psk').value = data.key;
  6794. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6795. }
  6796. } catch (err) {
  6797. const arr = new Uint8Array(32);
  6798. crypto.getRandomValues(arr);
  6799. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6800. document.getElementById('aerotun-modal-psk').value = hex;
  6801. }
  6802. }
  6803. function openAddAeroTUNModal() {
  6804. const tunnels = state.aerotunTunnels || [];
  6805. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6806. document.getElementById('aerotun-modal-id').value = '';
  6807. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6808. document.getElementById('aerotun-modal-mode').value = 'server';
  6809. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6810. document.getElementById('aerotun-modal-endpoint').value = '';
  6811. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6812. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6813. document.getElementById('aerotun-modal-psk').value = '';
  6814. document.getElementById('aerotun-modal-mtu').value = '1420';
  6815. document.getElementById('aerotun-modal-comment').value = '';
  6816. document.getElementById('aerotun-modal-compression').checked = true;
  6817. document.getElementById('aerotun-modal-defroute').checked = false;
  6818. document.getElementById('aerotun-modal-disabled').checked = false;
  6819. generateAeroTUNKey();
  6820. onAeroTUNModeChange();
  6821. document.getElementById('aerotun-modal').classList.remove('hidden');
  6822. }
  6823. function openEditAeroTUNModal(id) {
  6824. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6825. if (!t) return;
  6826. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6827. document.getElementById('aerotun-modal-id').value = t.id;
  6828. document.getElementById('aerotun-modal-name').value = t.name;
  6829. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6830. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6831. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6832. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6833. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6834. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6835. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6836. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6837. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6838. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6839. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6840. onAeroTUNModeChange();
  6841. document.getElementById('aerotun-modal').classList.remove('hidden');
  6842. }
  6843. function closeAeroTUNModal() {
  6844. document.getElementById('aerotun-modal').classList.add('hidden');
  6845. }
  6846. async function submitSaveAeroTUN(e) {
  6847. e.preventDefault();
  6848. const id = document.getElementById('aerotun-modal-id').value;
  6849. const name = document.getElementById('aerotun-modal-name').value.trim();
  6850. const mode = document.getElementById('aerotun-modal-mode').value;
  6851. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6852. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6853. const local = document.getElementById('aerotun-modal-local').value.trim();
  6854. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6855. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6856. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6857. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6858. const compression = document.getElementById('aerotun-modal-compression').checked;
  6859. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6860. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6861. if (mode === 'client' && !endpoint) {
  6862. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6863. return;
  6864. }
  6865. if (!psk) {
  6866. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6867. return;
  6868. }
  6869. try {
  6870. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6871. method: 'POST',
  6872. headers: { 'Content-Type': 'application/json' },
  6873. body: JSON.stringify({
  6874. id,
  6875. name,
  6876. mode,
  6877. listen_port: port,
  6878. remote_endpoint: endpoint,
  6879. local_address: local,
  6880. peer_address: peer,
  6881. psk,
  6882. mtu,
  6883. compression,
  6884. default_route: defaultRoute,
  6885. comment,
  6886. disabled
  6887. })
  6888. });
  6889. if (res.ok) {
  6890. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6891. closeAeroTUNModal();
  6892. loadAeroTUN(false);
  6893. fetchData(false);
  6894. } else {
  6895. const err = await res.text();
  6896. showToast('Error Saving Tunnel', err, 'error');
  6897. }
  6898. } catch (err) {
  6899. showToast('Network Error', err.message, 'error');
  6900. }
  6901. }
  6902. async function startAeroTUNTunnel(id) {
  6903. try {
  6904. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6905. if (res.ok) {
  6906. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6907. loadAeroTUN(false);
  6908. fetchData(false);
  6909. } else {
  6910. const err = await res.text();
  6911. showToast('Failed to Start', err, 'error');
  6912. }
  6913. } catch (err) {
  6914. showToast('Error', err.message, 'error');
  6915. }
  6916. }
  6917. async function stopAeroTUNTunnel(id) {
  6918. try {
  6919. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6920. if (res.ok) {
  6921. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6922. loadAeroTUN(false);
  6923. fetchData(false);
  6924. } else {
  6925. const err = await res.text();
  6926. showToast('Failed to Stop', err, 'error');
  6927. }
  6928. } catch (err) {
  6929. showToast('Error', err.message, 'error');
  6930. }
  6931. }
  6932. async function toggleAeroTUNState(id, disabled) {
  6933. try {
  6934. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6935. method: 'POST',
  6936. headers: { 'Content-Type': 'application/json' },
  6937. body: JSON.stringify({ disabled })
  6938. });
  6939. if (res.ok) {
  6940. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6941. loadAeroTUN(false);
  6942. fetchData(false);
  6943. }
  6944. } catch (err) {
  6945. showToast('Error', err.message, 'error');
  6946. }
  6947. }
  6948. async function deleteAeroTUN(id) {
  6949. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6950. try {
  6951. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6952. if (res.ok) {
  6953. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6954. loadAeroTUN(false);
  6955. fetchData(false);
  6956. }
  6957. } catch (err) {
  6958. showToast('Error', err.message, 'error');
  6959. }
  6960. }
  6961. // ======================== PPP Central Hub & Servers ========================
  6962. function switchPPPSubTab(tab) {
  6963. state.pppSubTab = tab;
  6964. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6965. tabs.forEach(t => {
  6966. const panel = document.getElementById(`ppp-subtab-${t}`);
  6967. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6968. if (panel) {
  6969. if (t === tab) panel.classList.remove('hidden');
  6970. else panel.classList.add('hidden');
  6971. }
  6972. if (btn) {
  6973. if (t === tab) {
  6974. 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';
  6975. } else {
  6976. 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';
  6977. }
  6978. }
  6979. });
  6980. const addBtn = document.getElementById('ppp-primary-add-btn');
  6981. if (addBtn) {
  6982. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6983. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6984. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6985. else addBtn.innerHTML = '<span>Save Config</span>';
  6986. }
  6987. if (tab === 'active') loadPPPSessions();
  6988. }
  6989. function openCurrentPPPModal() {
  6990. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6991. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6992. else if (state.pppSubTab === 'active') loadPPPSessions();
  6993. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6994. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6995. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6996. }
  6997. async function loadPPP(populateDropdowns = true) {
  6998. await Promise.all([
  6999. loadPPPSecrets(),
  7000. loadPPPProfiles(),
  7001. loadPPPServers(),
  7002. loadPPPSessions()
  7003. ]);
  7004. }
  7005. async function loadPPPSecrets() {
  7006. try {
  7007. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7008. const data = await res.json();
  7009. state.pppSecrets = Array.isArray(data) ? data : [];
  7010. const b = document.getElementById('ppp-badge-secrets');
  7011. if (b) b.innerText = state.pppSecrets.length;
  7012. const b2 = document.getElementById('secrets-count-badge');
  7013. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7014. renderPPPSecrets();
  7015. } catch (err) {
  7016. console.error('Failed to load PPP secrets:', err);
  7017. }
  7018. }
  7019. function renderPPPSecrets() {
  7020. const tbody = document.getElementById('secrets-table-body');
  7021. const empty = document.getElementById('secrets-empty');
  7022. if (!tbody) return;
  7023. tbody.innerHTML = '';
  7024. const secrets = state.pppSecrets || [];
  7025. if (secrets.length === 0) {
  7026. empty?.classList.remove('hidden');
  7027. return;
  7028. }
  7029. empty?.classList.add('hidden');
  7030. secrets.forEach(s => {
  7031. const tr = document.createElement('tr');
  7032. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7033. tr.innerHTML = `
  7034. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7035. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7036. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7037. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7038. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7039. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7040. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7041. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7042. <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>
  7043. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7044. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7045. </td>
  7046. `;
  7047. tbody.appendChild(tr);
  7048. });
  7049. }
  7050. async function loadPPPProfiles() {
  7051. try {
  7052. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7053. const data = await res.json();
  7054. state.pppProfiles = Array.isArray(data) ? data : [];
  7055. const b = document.getElementById('ppp-badge-profiles');
  7056. if (b) b.innerText = state.pppProfiles.length;
  7057. const b2 = document.getElementById('profiles-count-badge');
  7058. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7059. // Populate profile selects across modals
  7060. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7061. selects.forEach(sid => {
  7062. const el = document.getElementById(sid);
  7063. if (!el) return;
  7064. const cur = el.value;
  7065. el.innerHTML = '';
  7066. state.pppProfiles.forEach(p => {
  7067. const opt = document.createElement('option');
  7068. opt.value = p.name;
  7069. opt.innerText = `${p.name} (${p.remote_address})`;
  7070. if (p.name === cur) opt.selected = true;
  7071. el.appendChild(opt);
  7072. });
  7073. });
  7074. renderPPPProfiles();
  7075. } catch (err) {
  7076. console.error('Failed to load PPP profiles:', err);
  7077. }
  7078. }
  7079. function renderPPPProfiles() {
  7080. const tbody = document.getElementById('profiles-table-body');
  7081. if (!tbody) return;
  7082. tbody.innerHTML = '';
  7083. (state.pppProfiles || []).forEach(p => {
  7084. const isDefault = p.name.startsWith('default');
  7085. const tr = document.createElement('tr');
  7086. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7087. tr.innerHTML = `
  7088. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7089. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7090. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7091. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7092. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7093. <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>
  7094. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7095. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7096. ${!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>`}
  7097. </td>
  7098. `;
  7099. tbody.appendChild(tr);
  7100. });
  7101. }
  7102. async function loadPPPServers() {
  7103. try {
  7104. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7105. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7106. fetch(`${API_BASE}/vpn/servers/pptp`),
  7107. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7108. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7109. ]);
  7110. if (pppoeRes.ok) {
  7111. state.pppoeServer = await pppoeRes.json();
  7112. const s = state.pppoeServer;
  7113. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7114. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7115. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7116. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7117. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7118. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7119. const pill = document.getElementById('pppoe-server-status-pill');
  7120. if (pill) {
  7121. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7122. 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';
  7123. }
  7124. setDotBadge('ppp-badge-pppoe-state', s.running);
  7125. }
  7126. if (pptpRes.ok) {
  7127. state.pptpServer = await pptpRes.json();
  7128. const s = state.pptpServer;
  7129. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7130. document.getElementById('pptp-server-port').value = s.port || 1723;
  7131. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7132. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7133. const pill = document.getElementById('pptp-server-status-pill');
  7134. if (pill) {
  7135. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7136. 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';
  7137. }
  7138. setDotBadge('ppp-badge-pptp-state', s.running);
  7139. }
  7140. if (l2tpRes.ok) {
  7141. state.l2tpServer = await l2tpRes.json();
  7142. const s = state.l2tpServer;
  7143. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7144. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7145. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7146. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7147. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7148. const pill = document.getElementById('l2tp-server-status-pill');
  7149. if (pill) {
  7150. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7151. 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';
  7152. }
  7153. setDotBadge('ppp-badge-l2tp-state', s.running);
  7154. }
  7155. if (ipsecRes.ok) {
  7156. state.ipsecServer = await ipsecRes.json();
  7157. const s = state.ipsecServer;
  7158. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7159. if (modalEn) modalEn.checked = !!s.enabled;
  7160. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7161. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7162. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7163. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7164. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7165. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7166. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7167. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7168. const pill = document.getElementById('modal-ipsec-server-status');
  7169. if (pill) {
  7170. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7171. 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';
  7172. }
  7173. }
  7174. } catch (err) {
  7175. console.error('Failed to load VPN servers:', err);
  7176. }
  7177. }
  7178. async function loadPPPSessions() {
  7179. try {
  7180. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7181. const data = await res.json();
  7182. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7183. const b = document.getElementById('ppp-badge-active');
  7184. if (b) b.innerText = state.pppActiveSessions.length;
  7185. const sideB = document.getElementById('badge-ppp-sessions');
  7186. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7187. renderPPPSessions();
  7188. } catch (err) {
  7189. console.error('Failed to load active PPP sessions:', err);
  7190. }
  7191. }
  7192. function renderPPPSessions() {
  7193. const tbody = document.getElementById('active-ppp-table-body');
  7194. const empty = document.getElementById('active-ppp-empty');
  7195. if (!tbody) return;
  7196. tbody.innerHTML = '';
  7197. const list = state.pppActiveSessions || [];
  7198. if (list.length === 0) {
  7199. empty?.classList.remove('hidden');
  7200. return;
  7201. }
  7202. empty?.classList.add('hidden');
  7203. list.forEach(s => {
  7204. const tr = document.createElement('tr');
  7205. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7206. tr.innerHTML = `
  7207. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7208. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7209. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7210. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7211. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7212. <td class="py-2.5 px-3 text-[11px]">
  7213. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7214. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7215. </td>
  7216. <td class="py-2.5 px-3 text-right font-sans">
  7217. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7218. </td>
  7219. `;
  7220. tbody.appendChild(tr);
  7221. });
  7222. }
  7223. async function disconnectPPPSession(iface) {
  7224. if (!confirm(`Disconnect session ${iface}?`)) return;
  7225. try {
  7226. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7227. if (res.ok) {
  7228. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7229. loadPPPSessions();
  7230. }
  7231. } catch (err) {
  7232. showToast('Error', err.message, 'error');
  7233. }
  7234. }
  7235. // PPP Secret Modal handlers
  7236. function openAddPPPSecretModal() {
  7237. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7238. document.getElementById('secret-modal-id').value = '';
  7239. document.getElementById('secret-modal-name').value = '';
  7240. document.getElementById('secret-modal-password').value = '';
  7241. document.getElementById('secret-modal-service').value = 'any';
  7242. document.getElementById('secret-modal-profile').value = 'default';
  7243. document.getElementById('secret-modal-local').value = '';
  7244. document.getElementById('secret-modal-remote').value = '';
  7245. document.getElementById('secret-modal-comment').value = '';
  7246. document.getElementById('secret-modal-disabled').checked = false;
  7247. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7248. }
  7249. function openEditPPPSecretModal(id) {
  7250. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7251. if (!s) return;
  7252. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7253. document.getElementById('secret-modal-id').value = s.id;
  7254. document.getElementById('secret-modal-name').value = s.name;
  7255. document.getElementById('secret-modal-password').value = s.password;
  7256. document.getElementById('secret-modal-service').value = s.service || 'any';
  7257. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7258. document.getElementById('secret-modal-local').value = s.local_address || '';
  7259. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7260. document.getElementById('secret-modal-comment').value = s.comment || '';
  7261. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7262. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7263. }
  7264. function closePPPSecretModal() {
  7265. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7266. }
  7267. async function submitSavePPPSecret(e) {
  7268. e.preventDefault();
  7269. const id = document.getElementById('secret-modal-id').value;
  7270. const name = document.getElementById('secret-modal-name').value.trim();
  7271. const password = document.getElementById('secret-modal-password').value.trim();
  7272. const service = document.getElementById('secret-modal-service').value;
  7273. const profile = document.getElementById('secret-modal-profile').value;
  7274. const local = document.getElementById('secret-modal-local').value.trim();
  7275. const remote = document.getElementById('secret-modal-remote').value.trim();
  7276. const comment = document.getElementById('secret-modal-comment').value.trim();
  7277. const disabled = document.getElementById('secret-modal-disabled').checked;
  7278. try {
  7279. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7280. method: 'POST',
  7281. headers: { 'Content-Type': 'application/json' },
  7282. body: JSON.stringify({
  7283. id,
  7284. name,
  7285. password,
  7286. service,
  7287. profile,
  7288. local_address: local,
  7289. remote_address: remote,
  7290. comment,
  7291. disabled
  7292. })
  7293. });
  7294. if (res.ok) {
  7295. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7296. closePPPSecretModal();
  7297. loadPPPSecrets();
  7298. } else {
  7299. const err = await res.json();
  7300. showToast('Error', err.message, 'error');
  7301. }
  7302. } catch (err) {
  7303. showToast('Error', err.message, 'error');
  7304. }
  7305. }
  7306. async function togglePPPSecretState(id, disabled) {
  7307. try {
  7308. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7309. method: 'POST',
  7310. headers: { 'Content-Type': 'application/json' },
  7311. body: JSON.stringify({ disabled })
  7312. });
  7313. if (res.ok) {
  7314. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7315. loadPPPSecrets();
  7316. }
  7317. } catch (err) {
  7318. showToast('Error', err.message, 'error');
  7319. }
  7320. }
  7321. async function deletePPPSecret(id) {
  7322. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7323. try {
  7324. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7325. if (res.ok) {
  7326. showToast('Deleted', 'Secret account removed', 'success');
  7327. loadPPPSecrets();
  7328. }
  7329. } catch (err) {
  7330. showToast('Error', err.message, 'error');
  7331. }
  7332. }
  7333. // PPP Profile Modal handlers
  7334. function openAddPPPProfileModal() {
  7335. document.getElementById('profile-modal-name').value = '';
  7336. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7337. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7338. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7339. document.getElementById('profile-modal-encryption').value = 'required';
  7340. document.getElementById('profile-modal-onlyone').checked = true;
  7341. document.getElementById('profile-modal-comment').value = '';
  7342. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7343. }
  7344. function closePPPProfileModal() {
  7345. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7346. }
  7347. async function submitSavePPPProfile(e) {
  7348. e.preventDefault();
  7349. const name = document.getElementById('profile-modal-name').value.trim();
  7350. const local = document.getElementById('profile-modal-local').value.trim();
  7351. const remote = document.getElementById('profile-modal-remote').value.trim();
  7352. const dns = document.getElementById('profile-modal-dns').value.trim();
  7353. const enc = document.getElementById('profile-modal-encryption').value;
  7354. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7355. const comment = document.getElementById('profile-modal-comment').value.trim();
  7356. try {
  7357. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7358. method: 'POST',
  7359. headers: { 'Content-Type': 'application/json' },
  7360. body: JSON.stringify({
  7361. id: name,
  7362. name,
  7363. local_address: local,
  7364. remote_address: remote,
  7365. dns_servers: dns,
  7366. use_encryption: enc,
  7367. only_one: onlyone,
  7368. comment
  7369. })
  7370. });
  7371. if (res.ok) {
  7372. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7373. closePPPProfileModal();
  7374. loadPPPProfiles();
  7375. } else {
  7376. const err = await res.json();
  7377. showToast('Error', err.message, 'error');
  7378. }
  7379. } catch (err) {
  7380. showToast('Error', err.message, 'error');
  7381. }
  7382. }
  7383. async function deletePPPProfile(name) {
  7384. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7385. try {
  7386. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7387. if (res.ok) {
  7388. showToast('Deleted', 'Profile removed', 'success');
  7389. loadPPPProfiles();
  7390. } else {
  7391. const err = await res.json();
  7392. showToast('Error', err.message, 'error');
  7393. }
  7394. } catch (err) {
  7395. showToast('Error', err.message, 'error');
  7396. }
  7397. }
  7398. // Server Config submissions
  7399. async function savePPPoEServerConfig(e) {
  7400. e.preventDefault();
  7401. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7402. const name = document.getElementById('pppoe-server-name').value.trim();
  7403. const iface = document.getElementById('pppoe-server-iface').value;
  7404. const profile = document.getElementById('pppoe-server-profile').value;
  7405. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7406. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7407. try {
  7408. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7409. method: 'POST',
  7410. headers: { 'Content-Type': 'application/json' },
  7411. body: JSON.stringify({
  7412. enabled,
  7413. service_name: name,
  7414. interface: iface,
  7415. default_profile: profile,
  7416. max_mtu: mtu,
  7417. max_mru: mtu,
  7418. one_session_per_host: onesession
  7419. })
  7420. });
  7421. if (res.ok) {
  7422. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7423. loadPPPServers();
  7424. fetchData(false);
  7425. } else {
  7426. const err = await res.json();
  7427. showToast('Error', err.message, 'error');
  7428. }
  7429. } catch (err) {
  7430. showToast('Error', err.message, 'error');
  7431. }
  7432. }
  7433. async function savePPTPServerConfig(e) {
  7434. e.preventDefault();
  7435. const enabled = document.getElementById('pptp-server-enabled').checked;
  7436. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7437. const profile = document.getElementById('pptp-server-profile').value;
  7438. const mppe = document.getElementById('pptp-server-mppe').checked;
  7439. try {
  7440. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7441. method: 'POST',
  7442. headers: { 'Content-Type': 'application/json' },
  7443. body: JSON.stringify({
  7444. enabled,
  7445. port,
  7446. default_profile: profile,
  7447. require_mppe: mppe
  7448. })
  7449. });
  7450. if (res.ok) {
  7451. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7452. loadPPPServers();
  7453. fetchData(false);
  7454. } else {
  7455. const err = await res.json();
  7456. showToast('Error', err.message, 'error');
  7457. }
  7458. } catch (err) {
  7459. showToast('Error', err.message, 'error');
  7460. }
  7461. }
  7462. async function saveL2TPServerConfig(e) {
  7463. e.preventDefault();
  7464. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7465. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7466. const profile = document.getElementById('l2tp-server-profile').value;
  7467. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7468. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7469. try {
  7470. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7471. method: 'POST',
  7472. headers: { 'Content-Type': 'application/json' },
  7473. body: JSON.stringify({
  7474. enabled,
  7475. port,
  7476. default_profile: profile,
  7477. use_ipsec: useipsec,
  7478. ipsec_secret: psk
  7479. })
  7480. });
  7481. if (res.ok) {
  7482. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7483. loadPPPServers();
  7484. fetchData(false);
  7485. } else {
  7486. const err = await res.json();
  7487. showToast('Error', err.message, 'error');
  7488. }
  7489. } catch (err) {
  7490. showToast('Error', err.message, 'error');
  7491. }
  7492. }
  7493. // IPSec Server Modal
  7494. function openIPSecServerModal() {
  7495. loadPPPServers();
  7496. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7497. }
  7498. function closeIPSecServerModal() {
  7499. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7500. }
  7501. async function submitSaveIPSecServer(e) {
  7502. e.preventDefault();
  7503. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7504. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7505. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7506. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7507. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7508. try {
  7509. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7510. method: 'POST',
  7511. headers: { 'Content-Type': 'application/json' },
  7512. body: JSON.stringify({
  7513. enabled,
  7514. preshared_key: psk,
  7515. pool_address: pool,
  7516. dns_servers: dns,
  7517. local_subnet: subnet
  7518. })
  7519. });
  7520. if (res.ok) {
  7521. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7522. closeIPSecServerModal();
  7523. loadPPPServers();
  7524. fetchData(false);
  7525. } else {
  7526. const err = await res.json();
  7527. showToast('Error', err.message, 'error');
  7528. }
  7529. } catch (err) {
  7530. showToast('Error', err.message, 'error');
  7531. }
  7532. }
  7533. // WireGuard Client Config Viewer
  7534. let currentWGClientConf = '';
  7535. async function openWGClientConfModal(iface, clientIP) {
  7536. try {
  7537. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7538. method: 'POST',
  7539. headers: { 'Content-Type': 'application/json' },
  7540. body: JSON.stringify({
  7541. interface: iface,
  7542. address: clientIP || '10.10.0.2/32',
  7543. dns: '1.1.1.1, 8.8.8.8'
  7544. })
  7545. });
  7546. if (res.ok) {
  7547. const data = await res.json();
  7548. currentWGClientConf = data.config;
  7549. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7550. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7551. } else {
  7552. const err = await res.json();
  7553. showToast('Error', err.message, 'error');
  7554. }
  7555. } catch (err) {
  7556. showToast('Error', err.message, 'error');
  7557. }
  7558. }
  7559. function closeWGClientConfModal() {
  7560. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7561. }
  7562. function copyWGClientConf() {
  7563. if (!currentWGClientConf) return;
  7564. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7565. }
  7566. function downloadWGClientConf() {
  7567. if (!currentWGClientConf) return;
  7568. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7569. const a = document.createElement('a');
  7570. a.href = URL.createObjectURL(blob);
  7571. a.download = 'wireguard-client.conf';
  7572. document.body.appendChild(a);
  7573. a.click();
  7574. document.body.removeChild(a);
  7575. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7576. }
  7577. // =========================================================================
  7578. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7579. // =========================================================================
  7580. state.activeDynSubTab = 'bgp-peers';
  7581. state.activeBgpSubTab = 'bgp-peers';
  7582. state.activeOspfTab = 'instances';
  7583. state.bgpInstance = null;
  7584. state.bgpPeers = [];
  7585. state.bgpNets = [];
  7586. state.bgpRoutes = [];
  7587. state.ospfInstance = null;
  7588. state.ospfInstances = [];
  7589. state.ospfAreas = [];
  7590. state.ospfAreaRanges = [];
  7591. state.ospfTemplates = [];
  7592. state.ospfLiveInterfaces = [];
  7593. state.ospfStaticNbrs = [];
  7594. state.ospfNeighbors = [];
  7595. state.ospfLSA = [];
  7596. state.ospfRoutes = [];
  7597. state.selectedOspfRow = {
  7598. instances: null,
  7599. areas: null,
  7600. 'area-ranges': null,
  7601. templates: null,
  7602. interfaces: null,
  7603. 'static-nbrs': null,
  7604. neighbors: null,
  7605. lsa: null,
  7606. };
  7607. state.ospfSort = {
  7608. instances: { col: 'name', asc: true },
  7609. areas: { col: 'name', asc: true },
  7610. ranges: { col: 'area', asc: true },
  7611. templates: { col: 'interfaces', asc: true },
  7612. live_ifaces: { col: 'interface', asc: true },
  7613. snbrs: { col: 'address', asc: true },
  7614. neighbors: { col: 'address', asc: true },
  7615. lsa: { col: 'instance', asc: true },
  7616. };
  7617. function switchBgpSubTab(subTab) {
  7618. state.activeBgpSubTab = subTab;
  7619. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7620. tabs.forEach(t => {
  7621. const el = document.getElementById(`dyn-subtab-${t}`);
  7622. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7623. if (el) el.classList.toggle('hidden', t !== subTab);
  7624. if (btn) {
  7625. if (t === subTab) {
  7626. 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';
  7627. } else {
  7628. 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';
  7629. }
  7630. }
  7631. });
  7632. }
  7633. function switchOspfTab(tabName) {
  7634. state.activeOspfTab = tabName;
  7635. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7636. tabs.forEach(t => {
  7637. const pane = document.getElementById(`ospf-pane-${t}`);
  7638. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7639. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7640. if (btn) {
  7641. if (t === tabName) {
  7642. 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';
  7643. } else {
  7644. 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';
  7645. }
  7646. }
  7647. });
  7648. }
  7649. function switchOspfSubTab(tab) {
  7650. // Legacy alias
  7651. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7652. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7653. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7654. else switchOspfTab('instances');
  7655. }
  7656. function switchDynSubTab(subTab) {
  7657. if (subTab.startsWith('bgp')) {
  7658. if (state.activeTab !== 'bgp') navigate('bgp');
  7659. switchBgpSubTab(subTab);
  7660. } else if (subTab.startsWith('ospf')) {
  7661. if (state.activeTab !== 'ospf') navigate('ospf');
  7662. switchOspfTab('instances');
  7663. }
  7664. }
  7665. async function loadDynamicRouting(showToastMsg = false) {
  7666. try {
  7667. const fetchSafeJson = async (url) => {
  7668. try {
  7669. const r = await fetch(url);
  7670. return r.ok ? await r.json() : null;
  7671. } catch (e) {
  7672. return null;
  7673. }
  7674. };
  7675. const [
  7676. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7677. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7678. selectRules, commLists, asLists
  7679. ] = await Promise.all([
  7680. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7681. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7682. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7683. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7684. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7685. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7686. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7687. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7688. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7689. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7690. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7691. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7692. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7693. fetchSafeJson(`${API_BASE}/routing/filters`),
  7694. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7695. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7696. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7697. ]);
  7698. if (sum) state.dynSummary = sum;
  7699. if (bgpInst) state.bgpInstance = bgpInst;
  7700. if (bgpPeers) state.bgpPeers = bgpPeers;
  7701. if (bgpNets) state.bgpNets = bgpNets;
  7702. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7703. if (ospfInsts) state.ospfInstances = ospfInsts;
  7704. if (ospfAreas) state.ospfAreas = ospfAreas;
  7705. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7706. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7707. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7708. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7709. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7710. if (ospfLsa) state.ospfLSA = ospfLsa;
  7711. if (filters) state.routingFilters = filters;
  7712. if (selectRules) state.routingSelectRules = selectRules;
  7713. if (commLists) state.routingCommunityLists = commLists;
  7714. if (asLists) state.routingASLists = asLists;
  7715. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7716. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7717. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7718. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7719. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7720. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7721. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7722. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7723. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7724. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7725. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7726. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7727. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7728. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7729. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7730. } catch (err) {
  7731. console.error('Failed to load dynamic routing:', err);
  7732. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7733. }
  7734. }
  7735. async function loadOspfAll() {
  7736. await loadDynamicRouting(true);
  7737. }
  7738. function renderBgpStatusPill() {
  7739. const pill = document.getElementById('bgp-live-status-pill');
  7740. if (!pill) return;
  7741. const inst = state.bgpInstance;
  7742. if (!inst || !inst.enabled) {
  7743. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7744. pill.innerText = 'BGP DISABLED';
  7745. } else if (inst.running) {
  7746. 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';
  7747. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7748. } else {
  7749. 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';
  7750. pill.innerText = 'BGP STARTING...';
  7751. }
  7752. }
  7753. function renderBgpPeers() {
  7754. const tbody = document.getElementById('bgp-peers-table-body');
  7755. if (!tbody) return;
  7756. const empty = document.getElementById('bgp-peers-empty');
  7757. const countBadge = document.getElementById('bgp-peers-count-badge');
  7758. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7759. const peers = state.bgpPeers || [];
  7760. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7761. if (navBadge) navBadge.innerText = peers.length;
  7762. if (peers.length === 0) {
  7763. tbody.innerHTML = '';
  7764. if (empty) empty.classList.remove('hidden');
  7765. return;
  7766. }
  7767. if (empty) empty.classList.add('hidden');
  7768. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7769. if (tbody.dataset.sig === sig) return;
  7770. tbody.dataset.sig = sig;
  7771. tbody.innerHTML = peers.map(p => {
  7772. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7773. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7774. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7775. let stateBadge = '';
  7776. if (p.disabled) {
  7777. 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>';
  7778. } else if (p.state === 'Established') {
  7779. 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>';
  7780. } else if (p.state === 'Connect' || p.state === 'Active') {
  7781. 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>`;
  7782. } else {
  7783. 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>`;
  7784. }
  7785. return `
  7786. <tr class="hover:bg-slate-800/40 transition">
  7787. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7788. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7789. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7790. <td class="py-2.5 px-3">
  7791. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7792. ${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>`}
  7793. </td>
  7794. <td class="py-2.5 px-3">${stateBadge}</td>
  7795. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7796. <td class="py-2.5 px-3 text-slate-300">
  7797. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7798. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7799. </td>
  7800. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7801. ${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> ` : ''}
  7802. ${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>` : ''}
  7803. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7804. </td>
  7805. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7806. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7807. <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'}">
  7808. ${p.disabled ? 'Enable' : 'Disable'}
  7809. </button>
  7810. <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">
  7811. Edit
  7812. </button>
  7813. <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">
  7814. Delete
  7815. </button>
  7816. </td>
  7817. </tr>
  7818. `;
  7819. }).join('');
  7820. }
  7821. function renderBgpNetworks() {
  7822. const tbody = document.getElementById('bgp-nets-table-body');
  7823. if (!tbody) return;
  7824. const empty = document.getElementById('bgp-nets-empty');
  7825. const countBadge = document.getElementById('bgp-nets-count-badge');
  7826. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7827. const nets = state.bgpNets || [];
  7828. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7829. if (navBadge) navBadge.innerText = nets.length;
  7830. if (nets.length === 0) {
  7831. tbody.innerHTML = '';
  7832. if (empty) empty.classList.remove('hidden');
  7833. return;
  7834. }
  7835. if (empty) empty.classList.add('hidden');
  7836. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7837. if (tbody.dataset.sig === sig) return;
  7838. tbody.dataset.sig = sig;
  7839. tbody.innerHTML = nets.map(n => `
  7840. <tr class="hover:bg-slate-800/40 transition">
  7841. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7842. <td class="py-2.5 px-3">
  7843. ${n.disabled
  7844. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7845. : '<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>'}
  7846. </td>
  7847. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7848. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7849. <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">
  7850. Delete
  7851. </button>
  7852. </td>
  7853. </tr>
  7854. `).join('');
  7855. }
  7856. function renderBgpRoutes() {
  7857. const tbody = document.getElementById('bgp-routes-table-body');
  7858. if (!tbody) return;
  7859. const empty = document.getElementById('bgp-routes-empty');
  7860. const countBadge = document.getElementById('bgp-routes-count-badge');
  7861. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7862. const routes = state.bgpRoutes || [];
  7863. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7864. if (navBadge) navBadge.innerText = routes.length;
  7865. if (routes.length === 0) {
  7866. tbody.innerHTML = '';
  7867. if (empty) empty.classList.remove('hidden');
  7868. return;
  7869. }
  7870. if (empty) empty.classList.add('hidden');
  7871. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7872. if (tbody.dataset.sig === sig) return;
  7873. tbody.dataset.sig = sig;
  7874. tbody.innerHTML = routes.map(r => `
  7875. <tr class="hover:bg-slate-800/40 transition">
  7876. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7877. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7878. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7879. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7880. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7881. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7882. </tr>
  7883. `).join('');
  7884. }
  7885. // =========================================================================
  7886. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7887. // =========================================================================
  7888. function sortOspfTable(tab, col) {
  7889. if (!state.ospfSort) state.ospfSort = {};
  7890. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7891. if (state.ospfSort[tab].col === col) {
  7892. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7893. } else {
  7894. state.ospfSort[tab].col = col;
  7895. state.ospfSort[tab].asc = true;
  7896. }
  7897. const asc = state.ospfSort[tab].asc;
  7898. let list = [];
  7899. if (tab === 'instances') list = state.ospfInstances || [];
  7900. else if (tab === 'areas') list = state.ospfAreas || [];
  7901. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7902. else if (tab === 'templates') list = state.ospfTemplates || [];
  7903. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7904. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7905. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7906. else if (tab === 'lsa') list = state.ospfLSA || [];
  7907. list.sort((a, b) => {
  7908. let valA = a[col] ?? '';
  7909. let valB = b[col] ?? '';
  7910. if (typeof valA === 'number' && typeof valB === 'number') {
  7911. return asc ? valA - valB : valB - valA;
  7912. }
  7913. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7914. });
  7915. if (tab === 'instances') renderOspfInstances();
  7916. else if (tab === 'areas') renderOspfAreas();
  7917. else if (tab === 'ranges') renderOspfAreaRanges();
  7918. else if (tab === 'templates') renderOspfTemplates();
  7919. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7920. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7921. else if (tab === 'neighbors') renderOspfNeighbors();
  7922. else if (tab === 'lsa') renderOspfLSA();
  7923. }
  7924. function selectOspfRow(tab, id) {
  7925. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7926. state.selectedOspfRow[tab] = id;
  7927. if (tab === 'instances') {
  7928. renderOspfInstances();
  7929. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7930. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7931. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7932. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7933. if (btnEn) btnEn.disabled = false;
  7934. if (btnDis) btnDis.disabled = false;
  7935. if (btnRem) btnRem.disabled = false;
  7936. if (btnCom) btnCom.disabled = false;
  7937. } else if (tab === 'areas') {
  7938. renderOspfAreas();
  7939. const btnEn = document.getElementById('btn-ospf-area-enable');
  7940. const btnDis = document.getElementById('btn-ospf-area-disable');
  7941. const btnRem = document.getElementById('btn-ospf-area-remove');
  7942. const btnCom = document.getElementById('btn-ospf-area-comment');
  7943. if (btnEn) btnEn.disabled = false;
  7944. if (btnDis) btnDis.disabled = false;
  7945. if (btnRem) btnRem.disabled = false;
  7946. if (btnCom) btnCom.disabled = false;
  7947. } else if (tab === 'ranges') {
  7948. renderOspfAreaRanges();
  7949. const btnEn = document.getElementById('btn-ospf-range-enable');
  7950. const btnDis = document.getElementById('btn-ospf-range-disable');
  7951. const btnRem = document.getElementById('btn-ospf-range-remove');
  7952. const btnCom = document.getElementById('btn-ospf-range-comment');
  7953. if (btnEn) btnEn.disabled = false;
  7954. if (btnDis) btnDis.disabled = false;
  7955. if (btnRem) btnRem.disabled = false;
  7956. if (btnCom) btnCom.disabled = false;
  7957. } else if (tab === 'templates') {
  7958. renderOspfTemplates();
  7959. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7960. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7961. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7962. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7963. if (btnEn) btnEn.disabled = false;
  7964. if (btnDis) btnDis.disabled = false;
  7965. if (btnRem) btnRem.disabled = false;
  7966. if (btnCom) btnCom.disabled = false;
  7967. } else if (tab === 'snbrs') {
  7968. renderOspfStaticNbrs();
  7969. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7970. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7971. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7972. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7973. if (btnEn) btnEn.disabled = false;
  7974. if (btnDis) btnDis.disabled = false;
  7975. if (btnRem) btnRem.disabled = false;
  7976. if (btnCom) btnCom.disabled = false;
  7977. }
  7978. }
  7979. // TAB 1: INSTANCES
  7980. function renderOspfInstances() {
  7981. const tbody = document.getElementById('ospf-instances-table-body');
  7982. if (!tbody) return;
  7983. const countEl = document.getElementById('ospf-instances-footer-count');
  7984. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7985. let list = state.ospfInstances || [];
  7986. if (filter) {
  7987. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7988. }
  7989. if (countEl) countEl.innerText = list.length;
  7990. const selId = state.selectedOspfRow?.instances;
  7991. tbody.innerHTML = list.map((inst, idx) => {
  7992. const isSel = inst.id === selId;
  7993. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7994. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7995. return `
  7996. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7997. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7998. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7999. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8000. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8001. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8002. </td>
  8003. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8004. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8005. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8006. </tr>
  8007. `;
  8008. }).join('');
  8009. }
  8010. // TAB 2: AREAS
  8011. function renderOspfAreas() {
  8012. const tbody = document.getElementById('ospf-areas-table-body');
  8013. if (!tbody) return;
  8014. const countEl = document.getElementById('ospf-areas-footer-count');
  8015. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8016. let list = state.ospfAreas || [];
  8017. if (filter) {
  8018. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8019. }
  8020. if (countEl) countEl.innerText = list.length;
  8021. const selId = state.selectedOspfRow?.areas;
  8022. tbody.innerHTML = list.map((a, idx) => {
  8023. const isSel = a.id === selId;
  8024. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8025. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8026. return `
  8027. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8028. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8029. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8030. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8031. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8032. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8033. </td>
  8034. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8035. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8036. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8037. </tr>
  8038. `;
  8039. }).join('');
  8040. }
  8041. // TAB 3: AREA RANGES
  8042. function renderOspfAreaRanges() {
  8043. const tbody = document.getElementById('ospf-ranges-table-body');
  8044. if (!tbody) return;
  8045. const countEl = document.getElementById('ospf-ranges-footer-count');
  8046. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8047. let list = state.ospfAreaRanges || [];
  8048. if (filter) {
  8049. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8050. }
  8051. if (countEl) countEl.innerText = list.length;
  8052. const selId = state.selectedOspfRow?.['area-ranges'];
  8053. tbody.innerHTML = list.map((r, idx) => {
  8054. const isSel = r.id === selId;
  8055. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8056. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8057. return `
  8058. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8059. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8060. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8061. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8062. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8063. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8064. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8065. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8066. </tr>
  8067. `;
  8068. }).join('');
  8069. }
  8070. // TAB 4: INTERFACE TEMPLATES
  8071. function renderOspfTemplates() {
  8072. const tbody = document.getElementById('ospf-templates-table-body');
  8073. if (!tbody) return;
  8074. const countEl = document.getElementById('ospf-templates-footer-count');
  8075. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8076. let list = state.ospfTemplates || [];
  8077. if (filter) {
  8078. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8079. }
  8080. if (countEl) countEl.innerText = list.length;
  8081. const selId = state.selectedOspfRow?.templates;
  8082. tbody.innerHTML = list.map((t, idx) => {
  8083. const isSel = t.id === selId;
  8084. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8085. const ifaces = t.interfaces || t.interface || 'all';
  8086. const nets = t.networks || t.network || '';
  8087. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8088. return `
  8089. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8090. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8091. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8092. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8093. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8094. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8095. </td>
  8096. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8097. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8098. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8099. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8100. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8101. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8102. </tr>
  8103. `;
  8104. }).join('');
  8105. }
  8106. // TAB 5: LIVE INTERFACES
  8107. function renderOspfLiveInterfaces() {
  8108. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8109. if (!tbody) return;
  8110. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8111. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8112. let list = state.ospfLiveInterfaces || [];
  8113. if (filter) {
  8114. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8115. }
  8116. if (countEl) countEl.innerText = list.length;
  8117. tbody.innerHTML = list.map(i => `
  8118. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8119. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8120. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8121. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8122. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8123. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8124. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8125. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8126. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8127. </tr>
  8128. `).join('');
  8129. }
  8130. // TAB 6: STATIC NEIGHBORS
  8131. function renderOspfStaticNbrs() {
  8132. const tbody = document.getElementById('ospf-snbrs-table-body');
  8133. if (!tbody) return;
  8134. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8135. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8136. let list = state.ospfStaticNbrs || [];
  8137. if (filter) {
  8138. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8139. }
  8140. if (countEl) countEl.innerText = list.length;
  8141. const selId = state.selectedOspfRow?.['static-nbrs'];
  8142. tbody.innerHTML = list.map((n, idx) => {
  8143. const isSel = n.id === selId;
  8144. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8145. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8146. return `
  8147. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8148. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8149. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8150. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8151. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8152. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8153. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8154. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8155. </tr>
  8156. `;
  8157. }).join('');
  8158. }
  8159. // TAB 7: LIVE NEIGHBORS
  8160. function renderOspfNeighbors() {
  8161. const tbody = document.getElementById('ospf-neighbors-table-body');
  8162. if (!tbody) return;
  8163. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8164. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8165. let list = state.ospfNeighbors || [];
  8166. if (filter) {
  8167. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8168. }
  8169. if (countEl) countEl.innerText = list.length;
  8170. tbody.innerHTML = list.map(n => `
  8171. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8172. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8173. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8174. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8175. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8176. </td>
  8177. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8178. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8179. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8180. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8181. </tr>
  8182. `).join('');
  8183. }
  8184. // TAB 8: LINK-STATE DATABASE (LSA)
  8185. function renderOspfLSA() {
  8186. const tbody = document.getElementById('ospf-lsa-table-body');
  8187. if (!tbody) return;
  8188. const countEl = document.getElementById('ospf-lsa-footer-count');
  8189. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8190. let list = state.ospfLSA || [];
  8191. if (filter) {
  8192. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8193. }
  8194. if (countEl) countEl.innerText = list.length;
  8195. tbody.innerHTML = list.map(l => `
  8196. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8197. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8198. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8199. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8200. </td>
  8201. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8202. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8203. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8204. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8205. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8206. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8207. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8208. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8209. </tr>
  8210. `).join('');
  8211. }
  8212. function renderOspfStatusPill() {
  8213. // Maintained for backward compatibility
  8214. const pill = document.getElementById('ospf-live-status-pill');
  8215. if (!pill) return;
  8216. 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';
  8217. pill.innerText = 'OSPF ACTIVE';
  8218. }
  8219. function renderOspfInterfaces() {
  8220. renderOspfTemplates();
  8221. }
  8222. function renderOspfRoutes() {
  8223. // Routes retained in background
  8224. }
  8225. // BGP Modals & Actions
  8226. function openBgpInstanceModal() {
  8227. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8228. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8229. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8230. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8231. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8232. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8233. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8234. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8235. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8236. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8237. }
  8238. function closeBgpInstanceModal() {
  8239. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8240. }
  8241. async function submitBgpInstance(e) {
  8242. e.preventDefault();
  8243. const payload = {
  8244. enabled: document.getElementById('modal-bgp-enabled').checked,
  8245. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8246. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8247. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8248. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8249. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8250. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8251. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8252. };
  8253. try {
  8254. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8255. method: 'POST',
  8256. headers: { 'Content-Type': 'application/json' },
  8257. body: JSON.stringify(payload)
  8258. });
  8259. if (res.ok) {
  8260. closeBgpInstanceModal();
  8261. showToast('Success', 'BGP instance configuration updated', 'success');
  8262. loadDynamicRouting();
  8263. } else {
  8264. const err = await res.json();
  8265. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8266. }
  8267. } catch (err) {
  8268. showToast('Error', err.message, 'error');
  8269. }
  8270. }
  8271. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8272. function switchBgpPeerModalTab(tab) {
  8273. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8274. tabs.forEach(t => {
  8275. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8276. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8277. if (t === tab) {
  8278. if (pane) pane.classList.remove('hidden');
  8279. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8280. } else {
  8281. if (pane) pane.classList.add('hidden');
  8282. 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';
  8283. }
  8284. });
  8285. }
  8286. function addOutputNetworkRow(val = '') {
  8287. const container = document.getElementById('modal-bgp-output-networks-container');
  8288. if (!container) return;
  8289. const row = document.createElement('div');
  8290. row.className = 'flex items-center gap-2 output-net-row';
  8291. row.innerHTML = `
  8292. <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">
  8293. <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>
  8294. `;
  8295. container.appendChild(row);
  8296. }
  8297. function parseBgpTime(val) {
  8298. if (!val) return 0;
  8299. val = String(val).trim();
  8300. if (val.includes(':')) {
  8301. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8302. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8303. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8304. }
  8305. return parseInt(val, 10) || 0;
  8306. }
  8307. function formatBgpTime(secs) {
  8308. if (!secs || secs <= 0) return '00:00:00';
  8309. const h = Math.floor(secs / 3600);
  8310. const m = Math.floor((secs % 3600) / 60);
  8311. const s = secs % 60;
  8312. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8313. }
  8314. function populateBgpRoutingTables() {
  8315. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8316. if (!sel) return;
  8317. const cur = sel.value || 'main';
  8318. sel.innerHTML = '<option value="main">main</option>';
  8319. (state.routingTables || []).forEach(t => {
  8320. if (t.name !== 'main') {
  8321. const opt = document.createElement('option');
  8322. opt.value = t.name;
  8323. opt.innerText = t.name;
  8324. sel.appendChild(opt);
  8325. }
  8326. });
  8327. sel.value = cur;
  8328. }
  8329. function openAddBgpPeerModal() {
  8330. document.getElementById('bgp-peer-form').reset();
  8331. document.getElementById('modal-bgp-peer-id').value = '';
  8332. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8333. // General Tab
  8334. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8335. document.getElementById('modal-bgp-peer-comment').value = '';
  8336. document.getElementById('modal-bgp-peer-name').value = '';
  8337. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8338. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8339. document.getElementById('modal-bgp-peer-local-as').value = '';
  8340. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8341. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8342. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8343. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8344. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8345. document.getElementById('modal-bgp-peer-router-id').value = '';
  8346. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8347. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8348. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8349. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8350. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8351. document.getElementById('modal-bgp-peer-local-port').value = '';
  8352. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8353. document.getElementById('modal-bgp-peer-password').value = '';
  8354. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8355. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8356. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8357. document.getElementById('modal-bgp-peer-connect').checked = true;
  8358. document.getElementById('modal-bgp-peer-listen').checked = true;
  8359. // Extra Tab
  8360. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8361. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8362. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8363. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8364. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8365. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8366. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8367. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8368. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8369. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8370. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8371. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8372. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8373. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8374. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8375. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8376. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8377. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8378. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8379. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8380. // Attributes Tab
  8381. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8382. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8383. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8384. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8385. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8386. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8387. // Filter Tab
  8388. populateFilterChainsDatalist();
  8389. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8390. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8391. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8392. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8393. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8394. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8395. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8396. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8397. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8398. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8399. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8400. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8401. populateBgpRoutingTables();
  8402. const container = document.getElementById('modal-bgp-output-networks-container');
  8403. if (container) {
  8404. container.innerHTML = '';
  8405. addOutputNetworkRow('');
  8406. }
  8407. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8408. if (removeBtn) removeBtn.classList.add('hidden');
  8409. switchBgpPeerModalTab('general');
  8410. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8411. }
  8412. function populateFilterChainsDatalist() {
  8413. const dl = document.getElementById('filter-chains-list');
  8414. if (!dl) return;
  8415. const chains = new Set();
  8416. (state.routingFilters || []).forEach(f => {
  8417. if (f.chain) chains.add(f.chain);
  8418. });
  8419. if (chains.size === 0) {
  8420. chains.add('awmn');
  8421. chains.add('bgp-in');
  8422. chains.add('bgp-out');
  8423. }
  8424. dl.innerHTML = '';
  8425. chains.forEach(c => {
  8426. const opt = document.createElement('option');
  8427. opt.value = c;
  8428. dl.appendChild(opt);
  8429. });
  8430. }
  8431. function openEditBgpPeerModal(id) {
  8432. const p = (state.bgpPeers || []).find(item => item.id === id);
  8433. if (!p) return;
  8434. populateBgpRoutingTables();
  8435. populateFilterChainsDatalist();
  8436. document.getElementById('modal-bgp-peer-id').value = p.id;
  8437. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8438. // General Tab
  8439. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8440. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8441. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8442. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8443. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8444. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8445. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8446. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8447. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8448. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8449. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8450. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8451. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8452. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8453. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8454. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8455. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8456. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8457. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8458. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8459. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8460. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8461. // Extra Tab
  8462. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8463. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8464. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8465. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8466. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8467. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8468. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8469. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8470. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8471. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8472. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8473. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8474. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8475. 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;
  8476. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8477. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8478. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8479. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8480. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8481. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8482. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8483. // Attributes Tab
  8484. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8485. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8486. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8487. 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;
  8488. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8489. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8490. // Filter Tab
  8491. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8492. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8493. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8494. 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 || '';
  8495. 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 || '';
  8496. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8497. 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 || '';
  8498. 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 || '';
  8499. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8500. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8501. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8502. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8503. // Output Networks
  8504. const container = document.getElementById('modal-bgp-output-networks-container');
  8505. if (container) {
  8506. container.innerHTML = '';
  8507. if (p.output_networks && p.output_networks.length > 0) {
  8508. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8509. } else {
  8510. addOutputNetworkRow('');
  8511. }
  8512. }
  8513. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8514. if (removeBtn) removeBtn.classList.remove('hidden');
  8515. switchBgpPeerModalTab('general');
  8516. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8517. }
  8518. function copyCurrentBgpPeer() {
  8519. document.getElementById('modal-bgp-peer-id').value = '';
  8520. const nameEl = document.getElementById('modal-bgp-peer-name');
  8521. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8522. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8523. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8524. if (removeBtn) removeBtn.classList.add('hidden');
  8525. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8526. }
  8527. function removeCurrentBgpPeer() {
  8528. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8529. if (!id) return;
  8530. deleteBgpPeer(id);
  8531. closeBgpPeerModal();
  8532. }
  8533. function closeBgpPeerModal() {
  8534. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8535. }
  8536. function getBgpPeerFormData() {
  8537. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8538. const outputNetworks = [];
  8539. netInputs.forEach(inp => {
  8540. const v = inp.value.trim();
  8541. if (v) outputNetworks.push(v);
  8542. });
  8543. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8544. return {
  8545. id: document.getElementById('modal-bgp-peer-id').value,
  8546. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8547. enabled: enabled,
  8548. disabled: !enabled,
  8549. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8550. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8551. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8552. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8553. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8554. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8555. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8556. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8557. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8558. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8559. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8560. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8561. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8562. password: document.getElementById('modal-bgp-peer-password').value,
  8563. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8564. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8565. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8566. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8567. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8568. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8569. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8570. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8571. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8572. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8573. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8574. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8575. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8576. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8577. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8578. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8579. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8580. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8581. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8582. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8583. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8584. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8585. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8586. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8587. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8588. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8589. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8590. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8591. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8592. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8593. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8594. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8595. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8596. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8597. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8598. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8599. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8600. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8601. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8602. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8603. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8604. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8605. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8606. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8607. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8608. output_networks: outputNetworks
  8609. };
  8610. }
  8611. async function submitBgpPeer(e) {
  8612. if (e) e.preventDefault();
  8613. const payload = getBgpPeerFormData();
  8614. try {
  8615. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8616. method: 'POST',
  8617. headers: { 'Content-Type': 'application/json' },
  8618. body: JSON.stringify(payload)
  8619. });
  8620. if (res.ok) {
  8621. closeBgpPeerModal();
  8622. showToast('Success', 'BGP Connection saved', 'success');
  8623. loadDynamicRouting();
  8624. } else {
  8625. const err = await res.json();
  8626. showToast('Error', err.error || 'Failed to save peer', 'error');
  8627. }
  8628. } catch (err) {
  8629. showToast('Error', err.message, 'error');
  8630. }
  8631. }
  8632. async function applyBgpPeerModal(e) {
  8633. if (e) e.preventDefault();
  8634. const payload = getBgpPeerFormData();
  8635. try {
  8636. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8637. method: 'POST',
  8638. headers: { 'Content-Type': 'application/json' },
  8639. body: JSON.stringify(payload)
  8640. });
  8641. if (res.ok) {
  8642. const data = await res.json();
  8643. if (data.peer && data.peer.id) {
  8644. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8645. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8646. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8647. }
  8648. showToast('Applied', 'BGP Connection applied', 'success');
  8649. loadDynamicRouting();
  8650. } else {
  8651. const err = await res.json();
  8652. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8653. }
  8654. } catch (err) {
  8655. showToast('Error', err.message, 'error');
  8656. }
  8657. }
  8658. async function deleteBgpPeer(id) {
  8659. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8660. try {
  8661. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8662. if (res.ok) {
  8663. showToast('Deleted', 'BGP peer removed', 'success');
  8664. loadDynamicRouting();
  8665. }
  8666. } catch (err) {
  8667. showToast('Error', err.message, 'error');
  8668. }
  8669. }
  8670. async function toggleBgpPeerState(id, disabled) {
  8671. try {
  8672. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8673. method: 'POST',
  8674. headers: { 'Content-Type': 'application/json' },
  8675. body: JSON.stringify({ disabled })
  8676. });
  8677. if (res.ok) {
  8678. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8679. loadDynamicRouting();
  8680. }
  8681. } catch (err) {
  8682. showToast('Error', err.message, 'error');
  8683. }
  8684. }
  8685. function openAddBgpNetworkModal() {
  8686. document.getElementById('bgp-network-form').reset();
  8687. document.getElementById('modal-bgp-net-id').value = '';
  8688. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8689. }
  8690. function closeBgpNetworkModal() {
  8691. document.getElementById('bgp-network-modal').classList.add('hidden');
  8692. }
  8693. async function submitBgpNetwork(e) {
  8694. e.preventDefault();
  8695. const payload = {
  8696. id: document.getElementById('modal-bgp-net-id').value,
  8697. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8698. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8699. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8700. };
  8701. try {
  8702. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8703. method: 'POST',
  8704. headers: { 'Content-Type': 'application/json' },
  8705. body: JSON.stringify(payload)
  8706. });
  8707. if (res.ok) {
  8708. closeBgpNetworkModal();
  8709. showToast('Success', 'BGP network advertisement saved', 'success');
  8710. loadDynamicRouting();
  8711. } else {
  8712. const err = await res.json();
  8713. showToast('Error', err.error || 'Failed to save network', 'error');
  8714. }
  8715. } catch (err) {
  8716. showToast('Error', err.message, 'error');
  8717. }
  8718. }
  8719. async function deleteBgpNetwork(id) {
  8720. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8721. try {
  8722. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8723. if (res.ok) {
  8724. showToast('Deleted', 'Network advertisement removed', 'success');
  8725. loadDynamicRouting();
  8726. }
  8727. } catch (err) {
  8728. showToast('Error', err.message, 'error');
  8729. }
  8730. }
  8731. // =========================================================================
  8732. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8733. // =========================================================================
  8734. // --- 1. OSPF INSTANCE ---
  8735. function openOspfInstanceModal(id = null) {
  8736. const isEdit = !!id;
  8737. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8738. id: '',
  8739. name: 'Default',
  8740. version: 2,
  8741. vrf: 'main',
  8742. router_id: '192.168.131.56',
  8743. routing_table: 'main',
  8744. enabled: true,
  8745. redistribute_connected: false,
  8746. redistribute_static: true,
  8747. redistribute_bgp: false,
  8748. comment: ''
  8749. };
  8750. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8751. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8752. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8753. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8754. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8755. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8756. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8757. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8758. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8759. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8760. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8761. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8762. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8763. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8764. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8765. }
  8766. function openEditOspfInstanceModal(id) {
  8767. openOspfInstanceModal(id);
  8768. }
  8769. function closeOspfInstanceModal() {
  8770. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8771. }
  8772. async function submitOspfInstance(e) {
  8773. if (e) e.preventDefault();
  8774. const payload = {
  8775. id: document.getElementById('modal-ospf-inst-id').value,
  8776. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8777. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8778. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8779. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8780. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8781. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8782. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8783. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8784. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8785. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8786. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8787. };
  8788. try {
  8789. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8790. method: 'POST',
  8791. headers: { 'Content-Type': 'application/json' },
  8792. body: JSON.stringify(payload)
  8793. });
  8794. if (res.ok) {
  8795. closeOspfInstanceModal();
  8796. showToast('Saved', 'OSPF instance updated', 'success');
  8797. loadDynamicRouting();
  8798. } else {
  8799. const err = await res.json();
  8800. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8801. }
  8802. } catch (err) {
  8803. showToast('Error', err.message, 'error');
  8804. }
  8805. }
  8806. function applyOspfInstanceForm() {
  8807. submitOspfInstance(null);
  8808. }
  8809. function copyOspfInstance() {
  8810. document.getElementById('modal-ospf-inst-id').value = '';
  8811. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8812. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8813. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8814. }
  8815. async function deleteCurrentOspfInstance() {
  8816. const id = document.getElementById('modal-ospf-inst-id').value;
  8817. if (!id) return;
  8818. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8819. try {
  8820. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8821. if (res.ok) {
  8822. closeOspfInstanceModal();
  8823. showToast('Removed', 'OSPF instance deleted', 'success');
  8824. loadDynamicRouting();
  8825. }
  8826. } catch (err) {
  8827. showToast('Error', err.message, 'error');
  8828. }
  8829. }
  8830. async function enableSelectedOspfInstance() {
  8831. const id = state.selectedOspfRow?.instances;
  8832. if (!id) return;
  8833. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8834. method: 'POST',
  8835. headers: { 'Content-Type': 'application/json' },
  8836. body: JSON.stringify({ disabled: false })
  8837. });
  8838. loadDynamicRouting();
  8839. }
  8840. async function disableSelectedOspfInstance() {
  8841. const id = state.selectedOspfRow?.instances;
  8842. if (!id) return;
  8843. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8844. method: 'POST',
  8845. headers: { 'Content-Type': 'application/json' },
  8846. body: JSON.stringify({ disabled: true })
  8847. });
  8848. loadDynamicRouting();
  8849. }
  8850. async function removeSelectedOspfInstance() {
  8851. const id = state.selectedOspfRow?.instances;
  8852. if (!id) return;
  8853. if (!confirm('Delete selected OSPF instance?')) return;
  8854. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8855. loadDynamicRouting();
  8856. }
  8857. async function promptCommentOspfInstance() {
  8858. const id = state.selectedOspfRow?.instances;
  8859. if (!id) return;
  8860. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8861. if (!inst) return;
  8862. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8863. if (comment === null) return;
  8864. inst.comment = comment;
  8865. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8866. method: 'POST',
  8867. headers: { 'Content-Type': 'application/json' },
  8868. body: JSON.stringify(inst)
  8869. });
  8870. loadDynamicRouting();
  8871. }
  8872. // --- 2. OSPF AREA ---
  8873. function populateOspfAreaDropdowns() {
  8874. const instSelect = document.getElementById('modal-ospf-area-instance');
  8875. if (instSelect) {
  8876. const cur = instSelect.value;
  8877. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8878. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8879. if (cur) instSelect.value = cur;
  8880. }
  8881. }
  8882. function openOspfAreaModal(id = null) {
  8883. const isEdit = !!id;
  8884. populateOspfAreaDropdowns();
  8885. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8886. id: '',
  8887. name: 'Default',
  8888. instance: 'Default',
  8889. area_id: '0.0.0.0',
  8890. area_type: 'default',
  8891. default_cost: 1,
  8892. no_summaries: false,
  8893. disabled: false,
  8894. comment: ''
  8895. };
  8896. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8897. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8898. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8899. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8900. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8901. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8902. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8903. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8904. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8905. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8906. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8907. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8908. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8909. }
  8910. function openEditOspfAreaModal(id) {
  8911. openOspfAreaModal(id);
  8912. }
  8913. function closeOspfAreaModal() {
  8914. document.getElementById('ospf-area-modal').classList.add('hidden');
  8915. }
  8916. async function submitOspfArea(e) {
  8917. if (e) e.preventDefault();
  8918. const payload = {
  8919. id: document.getElementById('modal-ospf-area-id').value,
  8920. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8921. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8922. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8923. area_type: document.getElementById('modal-ospf-area-type').value,
  8924. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8925. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8926. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8927. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8928. };
  8929. try {
  8930. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8931. method: 'POST',
  8932. headers: { 'Content-Type': 'application/json' },
  8933. body: JSON.stringify(payload)
  8934. });
  8935. if (res.ok) {
  8936. closeOspfAreaModal();
  8937. showToast('Saved', 'OSPF area saved', 'success');
  8938. loadDynamicRouting();
  8939. } else {
  8940. const err = await res.json();
  8941. showToast('Error', err.error || 'Failed to save area', 'error');
  8942. }
  8943. } catch (err) {
  8944. showToast('Error', err.message, 'error');
  8945. }
  8946. }
  8947. function applyOspfAreaForm() {
  8948. submitOspfArea(null);
  8949. }
  8950. function copyOspfArea() {
  8951. document.getElementById('modal-ospf-area-id').value = '';
  8952. document.getElementById('modal-ospf-area-name').value += '-copy';
  8953. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8954. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8955. }
  8956. async function deleteCurrentOspfArea() {
  8957. const id = document.getElementById('modal-ospf-area-id').value;
  8958. if (!id) return;
  8959. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8960. try {
  8961. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8962. if (res.ok) {
  8963. closeOspfAreaModal();
  8964. showToast('Removed', 'OSPF area deleted', 'success');
  8965. loadDynamicRouting();
  8966. }
  8967. } catch (err) {
  8968. showToast('Error', err.message, 'error');
  8969. }
  8970. }
  8971. async function enableSelectedOspfArea() {
  8972. const id = state.selectedOspfRow?.areas;
  8973. if (!id) return;
  8974. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8975. method: 'POST',
  8976. headers: { 'Content-Type': 'application/json' },
  8977. body: JSON.stringify({ disabled: false })
  8978. });
  8979. loadDynamicRouting();
  8980. }
  8981. async function disableSelectedOspfArea() {
  8982. const id = state.selectedOspfRow?.areas;
  8983. if (!id) return;
  8984. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8985. method: 'POST',
  8986. headers: { 'Content-Type': 'application/json' },
  8987. body: JSON.stringify({ disabled: true })
  8988. });
  8989. loadDynamicRouting();
  8990. }
  8991. async function removeSelectedOspfArea() {
  8992. const id = state.selectedOspfRow?.areas;
  8993. if (!id) return;
  8994. if (!confirm('Delete selected OSPF area?')) return;
  8995. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8996. loadDynamicRouting();
  8997. }
  8998. async function promptCommentOspfArea() {
  8999. const id = state.selectedOspfRow?.areas;
  9000. if (!id) return;
  9001. const area = (state.ospfAreas || []).find(a => a.id === id);
  9002. if (!area) return;
  9003. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9004. if (comment === null) return;
  9005. area.comment = comment;
  9006. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9007. method: 'POST',
  9008. headers: { 'Content-Type': 'application/json' },
  9009. body: JSON.stringify(area)
  9010. });
  9011. loadDynamicRouting();
  9012. }
  9013. // --- 3. OSPF AREA RANGE ---
  9014. function populateAreaRangeDropdowns() {
  9015. const select = document.getElementById('modal-ospf-range-area');
  9016. if (select) {
  9017. const cur = select.value;
  9018. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9019. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9020. if (cur) select.value = cur;
  9021. }
  9022. }
  9023. function openOspfAreaRangeModal(id = null) {
  9024. const isEdit = !!id;
  9025. populateAreaRangeDropdowns();
  9026. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9027. id: '',
  9028. area: 'Default',
  9029. prefix: '',
  9030. cost: 1,
  9031. advertise: true,
  9032. disabled: false,
  9033. comment: ''
  9034. };
  9035. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9036. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9037. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9038. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9039. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9040. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9041. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9042. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9043. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9044. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9045. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9046. }
  9047. function openEditOspfAreaRangeModal(id) {
  9048. openOspfAreaRangeModal(id);
  9049. }
  9050. function closeOspfAreaRangeModal() {
  9051. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9052. }
  9053. async function submitOspfAreaRange(e) {
  9054. if (e) e.preventDefault();
  9055. const payload = {
  9056. id: document.getElementById('modal-ospf-range-id').value,
  9057. area: document.getElementById('modal-ospf-range-area').value,
  9058. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9059. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9060. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9061. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9062. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9063. };
  9064. try {
  9065. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9066. method: 'POST',
  9067. headers: { 'Content-Type': 'application/json' },
  9068. body: JSON.stringify(payload)
  9069. });
  9070. if (res.ok) {
  9071. closeOspfAreaRangeModal();
  9072. showToast('Saved', 'Area range saved', 'success');
  9073. loadDynamicRouting();
  9074. } else {
  9075. const err = await res.json();
  9076. showToast('Error', err.error || 'Failed to save area range', 'error');
  9077. }
  9078. } catch (err) {
  9079. showToast('Error', err.message, 'error');
  9080. }
  9081. }
  9082. function applyOspfAreaRangeForm() {
  9083. submitOspfAreaRange(null);
  9084. }
  9085. async function deleteCurrentOspfAreaRange() {
  9086. const id = document.getElementById('modal-ospf-range-id').value;
  9087. if (!id) return;
  9088. if (!confirm('Delete this area range?')) return;
  9089. try {
  9090. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9091. closeOspfAreaRangeModal();
  9092. showToast('Removed', 'Area range removed', 'success');
  9093. loadDynamicRouting();
  9094. } catch (err) {
  9095. showToast('Error', err.message, 'error');
  9096. }
  9097. }
  9098. async function enableSelectedOspfAreaRange() {
  9099. const id = state.selectedOspfRow?.['area-ranges'];
  9100. if (!id) return;
  9101. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9102. if (!r) return;
  9103. r.disabled = false;
  9104. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9105. loadDynamicRouting();
  9106. }
  9107. async function disableSelectedOspfAreaRange() {
  9108. const id = state.selectedOspfRow?.['area-ranges'];
  9109. if (!id) return;
  9110. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9111. if (!r) return;
  9112. r.disabled = true;
  9113. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9114. loadDynamicRouting();
  9115. }
  9116. async function removeSelectedOspfAreaRange() {
  9117. const id = state.selectedOspfRow?.['area-ranges'];
  9118. if (!id) return;
  9119. if (!confirm('Delete selected area range?')) return;
  9120. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9121. loadDynamicRouting();
  9122. }
  9123. async function promptCommentOspfAreaRange() {
  9124. const id = state.selectedOspfRow?.['area-ranges'];
  9125. if (!id) return;
  9126. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9127. if (!r) return;
  9128. const comment = prompt('Enter comment for area range:', r.comment || '');
  9129. if (comment === null) return;
  9130. r.comment = comment;
  9131. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9132. loadDynamicRouting();
  9133. }
  9134. // --- 4. OSPF INTERFACE TEMPLATE ---
  9135. function switchOspfTemplateTab(tab) {
  9136. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9137. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9138. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9139. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9140. if (tab === 'general') {
  9141. if (tabGen) tabGen.classList.remove('hidden');
  9142. if (tabAuth) tabAuth.classList.add('hidden');
  9143. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9144. 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';
  9145. } else {
  9146. if (tabGen) tabGen.classList.add('hidden');
  9147. if (tabAuth) tabAuth.classList.remove('hidden');
  9148. 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';
  9149. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9150. }
  9151. }
  9152. function populateTemplateAreaDropdowns() {
  9153. const select = document.getElementById('modal-ospf-tmpl-area');
  9154. if (select) {
  9155. const cur = select.value;
  9156. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9157. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9158. if (cur) select.value = cur;
  9159. }
  9160. }
  9161. function openOspfTemplateModal(id = null) {
  9162. const isEdit = !!id;
  9163. populateTemplateAreaDropdowns();
  9164. switchOspfTemplateTab('general');
  9165. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9166. id: '',
  9167. interfaces: '',
  9168. area: 'Default',
  9169. networks: '',
  9170. network_type: 'broadcast',
  9171. cost: 1,
  9172. priority: 128,
  9173. passive: false,
  9174. hello_interval: 10,
  9175. dead_interval: 40,
  9176. auth: 'none',
  9177. auth_key: '',
  9178. disabled: false,
  9179. comment: ''
  9180. };
  9181. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9182. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9183. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9184. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9185. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9186. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9187. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9188. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9189. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9190. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9191. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9192. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9193. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9194. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9195. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9196. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9197. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9198. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9199. }
  9200. function openEditOspfTemplateModal(id) {
  9201. openOspfTemplateModal(id);
  9202. }
  9203. function closeOspfTemplateModal() {
  9204. document.getElementById('ospf-template-modal').classList.add('hidden');
  9205. }
  9206. async function submitOspfTemplate(e) {
  9207. if (e) e.preventDefault();
  9208. const payload = {
  9209. id: document.getElementById('modal-ospf-tmpl-id').value,
  9210. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9211. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9212. area: document.getElementById('modal-ospf-tmpl-area').value,
  9213. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9214. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9215. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9216. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9217. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9218. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9219. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9220. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9221. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9222. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9223. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9224. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9225. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9226. };
  9227. try {
  9228. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9229. method: 'POST',
  9230. headers: { 'Content-Type': 'application/json' },
  9231. body: JSON.stringify(payload)
  9232. });
  9233. if (res.ok) {
  9234. closeOspfTemplateModal();
  9235. showToast('Saved', 'Interface template saved', 'success');
  9236. loadDynamicRouting();
  9237. } else {
  9238. const err = await res.json();
  9239. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9240. }
  9241. } catch (err) {
  9242. showToast('Error', err.message, 'error');
  9243. }
  9244. }
  9245. function applyOspfTemplateForm() {
  9246. submitOspfTemplate(null);
  9247. }
  9248. function copyOspfTemplate() {
  9249. document.getElementById('modal-ospf-tmpl-id').value = '';
  9250. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9251. showToast('Copied', 'Duplicated as new template', 'info');
  9252. }
  9253. async function deleteCurrentOspfTemplate() {
  9254. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9255. if (!id) return;
  9256. if (!confirm('Delete this interface template?')) return;
  9257. try {
  9258. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9259. closeOspfTemplateModal();
  9260. showToast('Removed', 'Interface template deleted', 'success');
  9261. loadDynamicRouting();
  9262. } catch (err) {
  9263. showToast('Error', err.message, 'error');
  9264. }
  9265. }
  9266. async function enableSelectedOspfTemplate() {
  9267. const id = state.selectedOspfRow?.templates;
  9268. if (!id) return;
  9269. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9270. method: 'POST',
  9271. headers: { 'Content-Type': 'application/json' },
  9272. body: JSON.stringify({ disabled: false })
  9273. });
  9274. loadDynamicRouting();
  9275. }
  9276. async function disableSelectedOspfTemplate() {
  9277. const id = state.selectedOspfRow?.templates;
  9278. if (!id) return;
  9279. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9280. method: 'POST',
  9281. headers: { 'Content-Type': 'application/json' },
  9282. body: JSON.stringify({ disabled: true })
  9283. });
  9284. loadDynamicRouting();
  9285. }
  9286. async function removeSelectedOspfTemplate() {
  9287. const id = state.selectedOspfRow?.templates;
  9288. if (!id) return;
  9289. if (!confirm('Delete selected interface template?')) return;
  9290. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9291. loadDynamicRouting();
  9292. }
  9293. async function promptCommentOspfTemplate() {
  9294. const id = state.selectedOspfRow?.templates;
  9295. if (!id) return;
  9296. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9297. if (!tmpl) return;
  9298. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9299. if (comment === null) return;
  9300. tmpl.comment = comment;
  9301. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9302. method: 'POST',
  9303. headers: { 'Content-Type': 'application/json' },
  9304. body: JSON.stringify(tmpl)
  9305. });
  9306. loadDynamicRouting();
  9307. }
  9308. // --- 5. OSPF STATIC NEIGHBOR ---
  9309. function populateStaticNbrAreaDropdowns() {
  9310. const select = document.getElementById('modal-ospf-snbr-area');
  9311. if (select) {
  9312. const cur = select.value;
  9313. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9314. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9315. if (cur) select.value = cur;
  9316. }
  9317. }
  9318. function openOspfStaticNbrModal(id = null) {
  9319. const isEdit = !!id;
  9320. populateStaticNbrAreaDropdowns();
  9321. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9322. id: '',
  9323. address: '',
  9324. area: 'Default',
  9325. poll_interval: 120,
  9326. cost: 1,
  9327. disabled: false,
  9328. comment: ''
  9329. };
  9330. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9331. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9332. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9333. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9334. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9335. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9336. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9337. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9338. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9339. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9340. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9341. }
  9342. function openEditOspfStaticNbrModal(id) {
  9343. openOspfStaticNbrModal(id);
  9344. }
  9345. function closeOspfStaticNbrModal() {
  9346. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9347. }
  9348. async function submitOspfStaticNbr(e) {
  9349. if (e) e.preventDefault();
  9350. const payload = {
  9351. id: document.getElementById('modal-ospf-snbr-id').value,
  9352. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9353. area: document.getElementById('modal-ospf-snbr-area').value,
  9354. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9355. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9356. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9357. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9358. };
  9359. try {
  9360. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9361. method: 'POST',
  9362. headers: { 'Content-Type': 'application/json' },
  9363. body: JSON.stringify(payload)
  9364. });
  9365. if (res.ok) {
  9366. closeOspfStaticNbrModal();
  9367. showToast('Saved', 'Static neighbor saved', 'success');
  9368. loadDynamicRouting();
  9369. } else {
  9370. const err = await res.json();
  9371. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9372. }
  9373. } catch (err) {
  9374. showToast('Error', err.message, 'error');
  9375. }
  9376. }
  9377. function applyOspfStaticNbrForm() {
  9378. submitOspfStaticNbr(null);
  9379. }
  9380. async function deleteCurrentOspfStaticNbr() {
  9381. const id = document.getElementById('modal-ospf-snbr-id').value;
  9382. if (!id) return;
  9383. if (!confirm('Delete this static neighbor?')) return;
  9384. try {
  9385. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9386. closeOspfStaticNbrModal();
  9387. showToast('Removed', 'Static neighbor removed', 'success');
  9388. loadDynamicRouting();
  9389. } catch (err) {
  9390. showToast('Error', err.message, 'error');
  9391. }
  9392. }
  9393. async function enableSelectedOspfStaticNbr() {
  9394. const id = state.selectedOspfRow?.['static-nbrs'];
  9395. if (!id) return;
  9396. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9397. if (!n) return;
  9398. n.disabled = false;
  9399. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9400. loadDynamicRouting();
  9401. }
  9402. async function disableSelectedOspfStaticNbr() {
  9403. const id = state.selectedOspfRow?.['static-nbrs'];
  9404. if (!id) return;
  9405. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9406. if (!n) return;
  9407. n.disabled = true;
  9408. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9409. loadDynamicRouting();
  9410. }
  9411. async function removeSelectedOspfStaticNbr() {
  9412. const id = state.selectedOspfRow?.['static-nbrs'];
  9413. if (!id) return;
  9414. if (!confirm('Delete selected static neighbor?')) return;
  9415. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9416. loadDynamicRouting();
  9417. }
  9418. async function promptCommentOspfStaticNbr() {
  9419. const id = state.selectedOspfRow?.['static-nbrs'];
  9420. if (!id) return;
  9421. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9422. if (!n) return;
  9423. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9424. if (comment === null) return;
  9425. n.comment = comment;
  9426. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9427. loadDynamicRouting();
  9428. }
  9429. // Backward-compat aliases
  9430. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9431. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9432. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9433. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9434. function deleteOspfInterface(id) {
  9435. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9436. }
  9437. function toggleOspfInterfaceState(id, disabled) {
  9438. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9439. method: 'POST',
  9440. headers: { 'Content-Type': 'application/json' },
  9441. body: JSON.stringify({ disabled })
  9442. }).then(() => loadDynamicRouting());
  9443. }
  9444. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9445. function deleteOspfArea(id) {
  9446. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9447. }
  9448. // ============================================================================
  9449. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9450. // ============================================================================
  9451. function switchBridgeSubTab(tab) {
  9452. state.bridgeSubTab = tab;
  9453. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9454. tabs.forEach(t => {
  9455. const panel = document.getElementById(`bridge-subtab-${t}`);
  9456. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9457. if (panel) {
  9458. if (t === tab) panel.classList.remove('hidden');
  9459. else panel.classList.add('hidden');
  9460. }
  9461. if (btn) {
  9462. if (t === tab) {
  9463. 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';
  9464. } else {
  9465. 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';
  9466. }
  9467. }
  9468. });
  9469. const addBtn = document.getElementById('bridge-top-action-btn');
  9470. if (addBtn) {
  9471. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9472. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9473. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9474. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9475. }
  9476. if (tab === 'hosts') loadBridgeHosts();
  9477. setTimeout(initTableSorting, 50);
  9478. }
  9479. function openCurrentBridgeModal() {
  9480. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9481. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9482. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9483. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9484. }
  9485. async function loadBridge() {
  9486. try {
  9487. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9488. fetch(`${API_BASE}/bridge/bridges`),
  9489. fetch(`${API_BASE}/bridge/ports`),
  9490. fetch(`${API_BASE}/bridge/vlans`),
  9491. fetch(`${API_BASE}/bridge/summary`),
  9492. fetch(`${API_BASE}/vpn/eoip`),
  9493. fetch(`${API_BASE}/vlans`)
  9494. ]);
  9495. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9496. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9497. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9498. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9499. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9500. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9501. // Badges & Stats
  9502. const bBridges = document.getElementById('bridge-badge-bridges');
  9503. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9504. const bPorts = document.getElementById('bridge-badge-ports');
  9505. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9506. const bVlans = document.getElementById('bridge-badge-vlans');
  9507. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9508. const bHosts = document.getElementById('bridge-badge-hosts');
  9509. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9510. const sBr = document.getElementById('bridge-stat-bridges');
  9511. if (sBr) sBr.innerText = (state.bridges || []).length;
  9512. const sPorts = document.getElementById('bridge-stat-ports');
  9513. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9514. const sHosts = document.getElementById('bridge-stat-hosts');
  9515. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9516. renderBridges();
  9517. renderBridgePorts();
  9518. renderBridgeVLANs();
  9519. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9520. } catch (err) {
  9521. console.error('Failed to load bridge subsystem:', err);
  9522. }
  9523. }
  9524. // ----------------- Bridges -----------------
  9525. function renderBridges() {
  9526. const tbody = document.getElementById('bridge-table-body');
  9527. const empty = document.getElementById('bridge-empty-bridges');
  9528. const countBadge = document.getElementById('bridge-count-badge');
  9529. if (!tbody) return;
  9530. tbody.innerHTML = '';
  9531. const bridges = state.bridges || [];
  9532. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9533. if (bridges.length === 0) {
  9534. empty?.classList.remove('hidden');
  9535. return;
  9536. }
  9537. empty?.classList.add('hidden');
  9538. bridges.forEach((b, idx) => {
  9539. const tr = document.createElement('tr');
  9540. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9541. // Format IP addresses pill list
  9542. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9543. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9544. ipsHtml = b.ip_addresses.map(ip => `
  9545. <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">
  9546. <span>${ip}</span>
  9547. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9548. </span>
  9549. `).join(' ');
  9550. }
  9551. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9552. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9553. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9554. tr.innerHTML = `
  9555. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9556. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9557. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9558. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9559. </td>
  9560. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9561. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9562. <td class="py-2.5 px-3">
  9563. <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>
  9564. </td>
  9565. <td class="py-2.5 px-3 text-center">
  9566. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9567. </td>
  9568. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9569. <td class="py-2.5 px-3">
  9570. <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>
  9571. </td>
  9572. <td class="py-2.5 px-3">
  9573. <div class="flex items-center gap-1.5 flex-wrap">
  9574. ${ipsHtml}
  9575. <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>
  9576. </div>
  9577. </td>
  9578. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9579. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9580. </td>
  9581. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9582. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9583. <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>
  9584. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9585. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9586. </td>
  9587. `;
  9588. tbody.appendChild(tr);
  9589. });
  9590. }
  9591. function openAddBridgeModal() {
  9592. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9593. document.getElementById('bridge-modal-id').value = '';
  9594. document.getElementById('bridge-modal-name').value = 'bridge1';
  9595. document.getElementById('bridge-modal-name').disabled = false;
  9596. document.getElementById('bridge-modal-mtu').value = '1500';
  9597. document.getElementById('bridge-modal-mac').value = '';
  9598. document.getElementById('bridge-modal-stp').value = 'rstp';
  9599. document.getElementById('bridge-modal-priority').value = '32768';
  9600. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9601. document.getElementById('bridge-modal-pvid').value = '1';
  9602. document.getElementById('bridge-modal-fastforward').checked = true;
  9603. document.getElementById('bridge-modal-comment').value = '';
  9604. document.getElementById('bridge-modal-disabled').checked = false;
  9605. toggleBridgeModalVlanFiltering();
  9606. document.getElementById('bridge-modal').classList.remove('hidden');
  9607. }
  9608. function openEditBridgeModal(id) {
  9609. const b = (state.bridges || []).find(x => x.id === id);
  9610. if (!b) return;
  9611. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9612. document.getElementById('bridge-modal-id').value = b.id;
  9613. document.getElementById('bridge-modal-name').value = b.name;
  9614. document.getElementById('bridge-modal-name').disabled = true;
  9615. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9616. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9617. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9618. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9619. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9620. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9621. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9622. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9623. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9624. toggleBridgeModalVlanFiltering();
  9625. document.getElementById('bridge-modal').classList.remove('hidden');
  9626. }
  9627. function closeBridgeModal() {
  9628. document.getElementById('bridge-modal').classList.add('hidden');
  9629. }
  9630. function toggleBridgeModalVlanFiltering() {
  9631. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9632. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9633. if (pvidBox) {
  9634. if (chk) pvidBox.classList.remove('opacity-40');
  9635. else pvidBox.classList.add('opacity-40');
  9636. }
  9637. }
  9638. async function submitSaveBridge(e) {
  9639. e.preventDefault();
  9640. const id = document.getElementById('bridge-modal-id').value;
  9641. const name = document.getElementById('bridge-modal-name').value.trim();
  9642. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9643. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9644. const stp = document.getElementById('bridge-modal-stp').value;
  9645. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9646. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9647. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9648. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9649. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9650. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9651. try {
  9652. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9653. method: 'POST',
  9654. headers: { 'Content-Type': 'application/json' },
  9655. body: JSON.stringify({
  9656. id,
  9657. name,
  9658. mtu,
  9659. mac_address: mac,
  9660. stp,
  9661. priority,
  9662. vlan_filtering: vlanFiltering,
  9663. pvid,
  9664. fast_forward: fastForward,
  9665. comment,
  9666. disabled
  9667. })
  9668. });
  9669. if (res.ok) {
  9670. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9671. closeBridgeModal();
  9672. loadBridge();
  9673. fetchData(false);
  9674. } else {
  9675. const err = await res.json();
  9676. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9677. }
  9678. } catch (err) {
  9679. showToast('Error', err.message, 'error');
  9680. }
  9681. }
  9682. async function toggleBridgeState(id, disabled) {
  9683. try {
  9684. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9685. method: 'POST',
  9686. headers: { 'Content-Type': 'application/json' },
  9687. body: JSON.stringify({ disabled })
  9688. });
  9689. if (res.ok) {
  9690. loadBridge();
  9691. fetchData(false);
  9692. }
  9693. } catch (err) {
  9694. showToast('Error', err.message, 'error');
  9695. }
  9696. }
  9697. async function deleteBridge(id) {
  9698. const b = (state.bridges || []).find(x => x.id === id);
  9699. const name = b ? b.name : id;
  9700. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9701. try {
  9702. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9703. if (res.ok) {
  9704. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9705. loadBridge();
  9706. fetchData(false);
  9707. } else {
  9708. const err = await res.json();
  9709. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9710. }
  9711. } catch (err) {
  9712. showToast('Error', err.message, 'error');
  9713. }
  9714. }
  9715. // ----------------- Bridge IP Assignments -----------------
  9716. function openAddBridgeIPModal(id, name) {
  9717. document.getElementById('bridge-ip-modal-id').value = id;
  9718. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9719. document.getElementById('bridge-ip-modal-cidr').value = '';
  9720. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9721. }
  9722. function closeBridgeIPModal() {
  9723. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9724. }
  9725. async function submitAddBridgeIP(e) {
  9726. e.preventDefault();
  9727. const id = document.getElementById('bridge-ip-modal-id').value;
  9728. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9729. try {
  9730. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9731. method: 'POST',
  9732. headers: { 'Content-Type': 'application/json' },
  9733. body: JSON.stringify({ ip })
  9734. });
  9735. if (res.ok) {
  9736. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9737. closeBridgeIPModal();
  9738. loadBridge();
  9739. fetchData(false);
  9740. } else {
  9741. const err = await res.json();
  9742. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9743. }
  9744. } catch (err) {
  9745. showToast('Error', err.message, 'error');
  9746. }
  9747. }
  9748. async function deleteBridgeIP(id, ip) {
  9749. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9750. try {
  9751. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9752. method: 'DELETE',
  9753. headers: { 'Content-Type': 'application/json' },
  9754. body: JSON.stringify({ ip })
  9755. });
  9756. if (res.ok) {
  9757. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9758. loadBridge();
  9759. fetchData(false);
  9760. }
  9761. } catch (err) {
  9762. showToast('Error', err.message, 'error');
  9763. }
  9764. }
  9765. // ----------------- Bridge Ports -----------------
  9766. function renderBridgePorts() {
  9767. const tbody = document.getElementById('bridge-ports-table-body');
  9768. const empty = document.getElementById('bridge-empty-ports');
  9769. const countBadge = document.getElementById('bridge-ports-count-badge');
  9770. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9771. if (!tbody) return;
  9772. tbody.innerHTML = '';
  9773. // Update filter select
  9774. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9775. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9776. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9777. if (ports.length === 0) {
  9778. empty?.classList.remove('hidden');
  9779. return;
  9780. }
  9781. empty?.classList.add('hidden');
  9782. ports.forEach((p, idx) => {
  9783. const tr = document.createElement('tr');
  9784. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9785. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9786. tr.innerHTML = `
  9787. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9788. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9789. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9790. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9791. </td>
  9792. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9793. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9794. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9795. <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>
  9796. <td class="py-2.5 px-3">
  9797. ${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>'}
  9798. </td>
  9799. <td class="py-2.5 px-3">
  9800. <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>
  9801. </td>
  9802. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9803. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9804. <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>
  9805. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9806. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9807. </td>
  9808. `;
  9809. tbody.appendChild(tr);
  9810. });
  9811. }
  9812. function openAddBridgePortModal() {
  9813. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9814. document.getElementById('bridge-port-modal-id').value = '';
  9815. populateBridgeSelect('bridge-port-modal-bridge');
  9816. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9817. document.getElementById('bridge-port-modal-pvid').value = '1';
  9818. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9819. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9820. document.getElementById('bridge-port-modal-horizon').value = '0';
  9821. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9822. document.getElementById('bridge-port-modal-priority').value = '128';
  9823. document.getElementById('bridge-port-modal-learn').checked = true;
  9824. document.getElementById('bridge-port-modal-comment').value = '';
  9825. document.getElementById('bridge-port-modal-disabled').checked = false;
  9826. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9827. }
  9828. function openEditBridgePortModal(id) {
  9829. const p = (state.bridgePorts || []).find(x => x.id === id);
  9830. if (!p) return;
  9831. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9832. document.getElementById('bridge-port-modal-id').value = p.id;
  9833. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9834. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9835. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9836. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9837. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9838. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9839. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9840. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9841. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9842. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9843. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9844. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9845. }
  9846. function closeBridgePortModal() {
  9847. document.getElementById('bridge-port-modal').classList.add('hidden');
  9848. }
  9849. async function submitSaveBridgePort(e) {
  9850. e.preventDefault();
  9851. const id = document.getElementById('bridge-port-modal-id').value;
  9852. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9853. const iface = document.getElementById('bridge-port-modal-interface').value;
  9854. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9855. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9856. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9857. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9858. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9859. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9860. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9861. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9862. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9863. try {
  9864. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9865. method: 'POST',
  9866. headers: { 'Content-Type': 'application/json' },
  9867. body: JSON.stringify({
  9868. id,
  9869. bridge,
  9870. interface: iface,
  9871. pvid,
  9872. frame_types: frameTypes,
  9873. ingress_filtering: ingressFiltering,
  9874. horizon,
  9875. path_cost: pathCost,
  9876. priority,
  9877. learn,
  9878. comment,
  9879. disabled
  9880. })
  9881. });
  9882. if (res.ok) {
  9883. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9884. closeBridgePortModal();
  9885. loadBridge();
  9886. fetchData(false);
  9887. } else {
  9888. const err = await res.json();
  9889. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9890. }
  9891. } catch (err) {
  9892. showToast('Error', err.message, 'error');
  9893. }
  9894. }
  9895. async function toggleBridgePortState(id, disabled) {
  9896. try {
  9897. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9898. method: 'POST',
  9899. headers: { 'Content-Type': 'application/json' },
  9900. body: JSON.stringify({ disabled })
  9901. });
  9902. if (res.ok) {
  9903. loadBridge();
  9904. fetchData(false);
  9905. }
  9906. } catch (err) {
  9907. showToast('Error', err.message, 'error');
  9908. }
  9909. }
  9910. async function deleteBridgePort(id) {
  9911. const p = (state.bridgePorts || []).find(x => x.id === id);
  9912. const iface = p ? p.interface : id;
  9913. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9914. try {
  9915. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9916. if (res.ok) {
  9917. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9918. loadBridge();
  9919. fetchData(false);
  9920. }
  9921. } catch (err) {
  9922. showToast('Error', err.message, 'error');
  9923. }
  9924. }
  9925. // ----------------- Bridge VLANs -----------------
  9926. function renderBridgeVLANs() {
  9927. const tbody = document.getElementById('bridge-vlans-table-body');
  9928. const empty = document.getElementById('bridge-empty-vlans');
  9929. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9930. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9931. if (!tbody) return;
  9932. tbody.innerHTML = '';
  9933. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9934. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9935. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9936. if (vlans.length === 0) {
  9937. empty?.classList.remove('hidden');
  9938. return;
  9939. }
  9940. empty?.classList.add('hidden');
  9941. vlans.forEach((v, idx) => {
  9942. const tr = document.createElement('tr');
  9943. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9944. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9945. ? 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(' ')
  9946. : '<span class="text-slate-600">none</span>';
  9947. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9948. ? 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(' ')
  9949. : '<span class="text-slate-600">none</span>';
  9950. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9951. tr.innerHTML = `
  9952. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9953. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9954. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9955. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9956. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9957. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9958. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9959. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9960. <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>
  9961. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9962. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9963. </td>
  9964. `;
  9965. tbody.appendChild(tr);
  9966. });
  9967. }
  9968. function openAddBridgeVLANModal() {
  9969. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9970. document.getElementById('bridge-vlan-modal-id').value = '';
  9971. populateBridgeSelect('bridge-vlan-modal-bridge');
  9972. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9973. document.getElementById('bridge-vlan-modal-comment').value = '';
  9974. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9975. updateBridgeVlanPortCheckboxes();
  9976. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9977. }
  9978. function openEditBridgeVLANModal(id) {
  9979. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9980. if (!v) return;
  9981. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9982. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9983. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9984. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9985. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9986. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9987. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9988. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9989. }
  9990. function closeBridgeVlanModal() {
  9991. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9992. }
  9993. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9994. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9995. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9996. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9997. if (!taggedBox || !untaggedBox) return;
  9998. // Ports belonging to the selected bridge
  9999. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10000. if (memberPorts.length === 0) {
  10001. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10002. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10003. return;
  10004. }
  10005. taggedBox.innerHTML = memberPorts.map(p => `
  10006. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10007. <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">
  10008. <span>${p.interface}</span>
  10009. </label>
  10010. `).join('');
  10011. untaggedBox.innerHTML = memberPorts.map(p => `
  10012. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10013. <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">
  10014. <span>${p.interface}</span>
  10015. </label>
  10016. `).join('');
  10017. }
  10018. async function submitSaveBridgeVLAN(e) {
  10019. e.preventDefault();
  10020. const id = document.getElementById('bridge-vlan-modal-id').value;
  10021. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10022. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10023. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10024. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10025. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10026. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10027. try {
  10028. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10029. method: 'POST',
  10030. headers: { 'Content-Type': 'application/json' },
  10031. body: JSON.stringify({
  10032. id,
  10033. bridge,
  10034. vlan_ids: vlanIDs,
  10035. tagged,
  10036. untagged,
  10037. comment,
  10038. disabled
  10039. })
  10040. });
  10041. if (res.ok) {
  10042. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10043. closeBridgeVlanModal();
  10044. loadBridge();
  10045. } else {
  10046. const err = await res.json();
  10047. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10048. }
  10049. } catch (err) {
  10050. showToast('Error', err.message, 'error');
  10051. }
  10052. }
  10053. async function toggleBridgeVLANState(id, disabled) {
  10054. try {
  10055. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10056. method: 'POST',
  10057. headers: { 'Content-Type': 'application/json' },
  10058. body: JSON.stringify({ disabled })
  10059. });
  10060. if (res.ok) loadBridge();
  10061. } catch (err) {
  10062. showToast('Error', err.message, 'error');
  10063. }
  10064. }
  10065. async function deleteBridgeVLAN(id) {
  10066. if (!confirm('Delete this bridge VLAN entry?')) return;
  10067. try {
  10068. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10069. if (res.ok) {
  10070. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10071. loadBridge();
  10072. }
  10073. } catch (err) {
  10074. showToast('Error', err.message, 'error');
  10075. }
  10076. }
  10077. // ----------------- Hosts / MAC Table -----------------
  10078. async function loadBridgeHosts() {
  10079. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10080. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10081. try {
  10082. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10083. const res = await fetch(url);
  10084. if (res.ok) {
  10085. state.bridgeHosts = await res.json();
  10086. renderBridgeHosts();
  10087. }
  10088. } catch (err) {
  10089. console.error('Failed to load bridge hosts:', err);
  10090. }
  10091. }
  10092. function renderBridgeHosts() {
  10093. const tbody = document.getElementById('bridge-hosts-table-body');
  10094. const empty = document.getElementById('bridge-empty-hosts');
  10095. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10096. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10097. if (!tbody) return;
  10098. tbody.innerHTML = '';
  10099. const hosts = (state.bridgeHosts || []).filter(h => {
  10100. if (!search) return true;
  10101. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10102. });
  10103. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10104. if (hosts.length === 0) {
  10105. empty?.classList.remove('hidden');
  10106. return;
  10107. }
  10108. empty?.classList.add('hidden');
  10109. hosts.forEach(h => {
  10110. const tr = document.createElement('tr');
  10111. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10112. let flagBadges = '';
  10113. 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>';
  10114. 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>';
  10115. 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>';
  10116. tr.innerHTML = `
  10117. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10118. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10119. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10120. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10121. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10122. <td class="py-2.5 px-3">${flagBadges}</td>
  10123. `;
  10124. tbody.appendChild(tr);
  10125. });
  10126. }
  10127. async function flushBridgeHosts() {
  10128. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10129. if (!selBridge) {
  10130. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10131. return;
  10132. }
  10133. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10134. try {
  10135. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10136. method: 'POST',
  10137. headers: { 'Content-Type': 'application/json' },
  10138. body: JSON.stringify({ bridge: selBridge })
  10139. });
  10140. if (res.ok) {
  10141. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10142. loadBridgeHosts();
  10143. }
  10144. } catch (err) {
  10145. showToast('Error', err.message, 'error');
  10146. }
  10147. }
  10148. // ----------------- Helpers -----------------
  10149. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10150. const sel = document.getElementById(selectId);
  10151. if (!sel) return;
  10152. const prevVal = currentVal || sel.value;
  10153. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10154. (state.bridges || []).forEach(b => {
  10155. const opt = document.createElement('option');
  10156. opt.value = b.name;
  10157. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10158. if (b.name === prevVal) opt.selected = true;
  10159. sel.appendChild(opt);
  10160. });
  10161. }
  10162. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10163. const sel = document.getElementById(selectId);
  10164. if (!sel) return;
  10165. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10166. // 1. Physical Interfaces
  10167. const grpPhys = document.createElement('optgroup');
  10168. grpPhys.label = 'Physical Interfaces';
  10169. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10170. const opt = document.createElement('option');
  10171. opt.value = i.name;
  10172. opt.innerText = `${i.name} (${i.role || i.type})`;
  10173. if (i.name === currentVal) opt.selected = true;
  10174. grpPhys.appendChild(opt);
  10175. });
  10176. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10177. // 2. VLAN Sub-interfaces
  10178. const grpVlans = document.createElement('optgroup');
  10179. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10180. (state.vlans || []).forEach(v => {
  10181. const opt = document.createElement('option');
  10182. opt.value = v.name;
  10183. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10184. if (v.name === currentVal) opt.selected = true;
  10185. grpVlans.appendChild(opt);
  10186. });
  10187. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10188. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10189. const grpEoip = document.createElement('optgroup');
  10190. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10191. (state.eoipTunnels || []).forEach(t => {
  10192. const opt = document.createElement('option');
  10193. opt.value = t.name;
  10194. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10195. if (t.name === currentVal) opt.selected = true;
  10196. grpEoip.appendChild(opt);
  10197. });
  10198. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10199. }
  10200. // -------------------------------------------------------------
  10201. // RouterOS v7 Routing Filters Management (/routing filter)
  10202. // -------------------------------------------------------------
  10203. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10204. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10205. if (!state.rfSort) state.rfSort = {};
  10206. function switchRoutingFilterTab(tab) {
  10207. state.activeRoutingFilterTab = tab;
  10208. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10209. tabs.forEach(t => {
  10210. const btn = document.getElementById(`tab-rf-${t}`);
  10211. const content = document.getElementById(`tab-content-rf-${t}`);
  10212. if (btn) {
  10213. if (t === tab) {
  10214. 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';
  10215. } else {
  10216. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10217. }
  10218. }
  10219. if (content) {
  10220. if (t === tab) content.classList.remove('hidden');
  10221. else content.classList.add('hidden');
  10222. }
  10223. });
  10224. const chainContainer = document.getElementById('rf-chain-filter-container');
  10225. if (chainContainer) {
  10226. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10227. else chainContainer.classList.add('hidden');
  10228. }
  10229. renderRoutingFilters();
  10230. }
  10231. function selectFilterRow(tab, id) {
  10232. if (state.selectedFilterRow[tab] === id) {
  10233. delete state.selectedFilterRow[tab];
  10234. } else {
  10235. state.selectedFilterRow[tab] = id;
  10236. }
  10237. if (tab === 'rules') renderRoutingFilterRules();
  10238. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10239. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10240. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10241. }
  10242. function openRoutingFilterNewModal() {
  10243. const tab = state.activeRoutingFilterTab || 'rules';
  10244. if (tab === 'rules') openAddRoutingFilterModal();
  10245. else if (tab === 'select-rules') openAddSelectRuleModal();
  10246. else if (tab === 'community-lists') openAddCommunityListModal();
  10247. else if (tab === 'as-lists') openAddASListModal();
  10248. }
  10249. function toggleSelectedRoutingFilter(disabled) {
  10250. const tab = state.activeRoutingFilterTab || 'rules';
  10251. const id = state.selectedFilterRow[tab];
  10252. if (!id) {
  10253. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10254. return;
  10255. }
  10256. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10257. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10258. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10259. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10260. }
  10261. function removeSelectedRoutingFilter() {
  10262. const tab = state.activeRoutingFilterTab || 'rules';
  10263. const id = state.selectedFilterRow[tab];
  10264. if (!id) {
  10265. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10266. return;
  10267. }
  10268. if (tab === 'rules') deleteRoutingFilter(id);
  10269. else if (tab === 'select-rules') deleteSelectRule(id);
  10270. else if (tab === 'community-lists') deleteCommunityList(id);
  10271. else if (tab === 'as-lists') deleteASList(id);
  10272. }
  10273. function searchRoutingFilters(q) {
  10274. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10275. renderRoutingFilters();
  10276. }
  10277. function sortFilterTable(tab, col) {
  10278. if (!state.rfSort) state.rfSort = {};
  10279. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10280. if (state.rfSort[tab].col === col) {
  10281. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10282. } else {
  10283. state.rfSort[tab].col = col;
  10284. state.rfSort[tab].asc = true;
  10285. }
  10286. const asc = state.rfSort[tab].asc;
  10287. let list = [];
  10288. if (tab === 'rules') list = state.routingFilters || [];
  10289. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10290. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10291. else if (tab === 'as-lists') list = state.routingASLists || [];
  10292. list.sort((a, b) => {
  10293. let valA = a[col] ?? '';
  10294. let valB = b[col] ?? '';
  10295. if (col === 'flags') {
  10296. valA = a.disabled ? 'X' : 'A';
  10297. valB = b.disabled ? 'X' : 'A';
  10298. }
  10299. if (typeof valA === 'number' && typeof valB === 'number') {
  10300. return asc ? valA - valB : valB - valA;
  10301. }
  10302. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10303. });
  10304. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10305. allCols.forEach(c => {
  10306. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10307. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10308. });
  10309. if (tab === 'rules') renderRoutingFilterRules();
  10310. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10311. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10312. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10313. }
  10314. function renderRoutingFilters() {
  10315. const navBadge = document.getElementById('badge-filters-count');
  10316. const allRules = state.routingFilters || [];
  10317. if (navBadge) navBadge.innerText = allRules.length;
  10318. // Populate chain filter select options and datalist
  10319. const chainSelect = document.getElementById('routing-filter-chain-select');
  10320. const chainDatalist = document.getElementById('dl-routing-chains');
  10321. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10322. if (chainSelect) {
  10323. const currentVal = state.filterChainSelected || 'all';
  10324. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10325. uniqueChains.map(ch => {
  10326. const count = allRules.filter(r => r.chain === ch).length;
  10327. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10328. }).join('');
  10329. chainSelect.value = currentVal;
  10330. }
  10331. if (chainDatalist) {
  10332. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10333. }
  10334. renderRoutingFilterRules();
  10335. renderRoutingFilterSelectRules();
  10336. renderRoutingFilterCommunityLists();
  10337. renderRoutingFilterASLists();
  10338. }
  10339. function filterRoutingFiltersByChain(chain) {
  10340. state.filterChainSelected = chain;
  10341. renderRoutingFilters();
  10342. }
  10343. // -------------------------------------------------------------
  10344. // TAB 1: RULES (/routing filter rule)
  10345. // -------------------------------------------------------------
  10346. function renderRoutingFilterRules() {
  10347. const tbody = document.getElementById('routing-filter-rules-tbody');
  10348. if (!tbody) return;
  10349. const empty = document.getElementById('rf-rules-empty');
  10350. const statusCount = document.getElementById('rf-status-count');
  10351. let list = (state.routingFilters || []).slice();
  10352. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10353. list = list.filter(r => r.chain === state.filterChainSelected);
  10354. }
  10355. const q = state.rfSearchQuery;
  10356. if (q) {
  10357. list = list.filter(r =>
  10358. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10359. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10360. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10361. (r.comment && r.comment.toLowerCase().includes(q))
  10362. );
  10363. }
  10364. if (!state.rfSort?.['rules']) {
  10365. list.sort((a, b) => {
  10366. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10367. return (a.rule_order || 0) - (b.rule_order || 0);
  10368. });
  10369. }
  10370. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10371. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10372. }
  10373. if (list.length === 0) {
  10374. tbody.innerHTML = '';
  10375. if (empty) empty.classList.remove('hidden');
  10376. return;
  10377. }
  10378. if (empty) empty.classList.add('hidden');
  10379. tbody.innerHTML = list.map(r => {
  10380. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10381. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10382. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10383. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10384. let ruleDisplay = '';
  10385. if (r.rule && r.rule.trim() !== '') {
  10386. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10387. } else {
  10388. let conds = [];
  10389. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10390. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10391. let act = r.action || 'accept';
  10392. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10393. }
  10394. return `
  10395. <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'}">
  10396. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10397. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10398. <td class="py-2 px-3">
  10399. <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>
  10400. </td>
  10401. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10402. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10403. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10404. <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>
  10405. <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>
  10406. <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'}">
  10407. ${r.disabled ? 'Enable' : 'Disable'}
  10408. </button>
  10409. <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">
  10410. Edit
  10411. </button>
  10412. <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">
  10413. ✕
  10414. </button>
  10415. </td>
  10416. </tr>
  10417. `;
  10418. }).join('');
  10419. }
  10420. // -------------------------------------------------------------
  10421. // TAB 2: SELECT RULES (/routing filter select-rule)
  10422. // -------------------------------------------------------------
  10423. function renderRoutingFilterSelectRules() {
  10424. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10425. if (!tbody) return;
  10426. const empty = document.getElementById('rf-select-rules-empty');
  10427. const statusCount = document.getElementById('rf-status-count');
  10428. let list = (state.routingSelectRules || []).slice();
  10429. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10430. list = list.filter(r => r.chain === state.filterChainSelected);
  10431. }
  10432. const q = state.rfSearchQuery;
  10433. if (q) {
  10434. list = list.filter(r =>
  10435. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10436. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10437. (r.comment && r.comment.toLowerCase().includes(q))
  10438. );
  10439. }
  10440. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10441. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10442. }
  10443. if (list.length === 0) {
  10444. tbody.innerHTML = '';
  10445. if (empty) empty.classList.remove('hidden');
  10446. return;
  10447. }
  10448. if (empty) empty.classList.add('hidden');
  10449. tbody.innerHTML = list.map(r => {
  10450. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10451. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10452. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10453. return `
  10454. <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'}">
  10455. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10456. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10457. <td class="py-2 px-3">
  10458. <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>
  10459. </td>
  10460. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10461. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10462. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10463. <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'}">
  10464. ${r.disabled ? 'Enable' : 'Disable'}
  10465. </button>
  10466. <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">
  10467. Edit
  10468. </button>
  10469. <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">
  10470. ✕
  10471. </button>
  10472. </td>
  10473. </tr>
  10474. `;
  10475. }).join('');
  10476. }
  10477. // -------------------------------------------------------------
  10478. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10479. // -------------------------------------------------------------
  10480. function renderRoutingFilterCommunityLists() {
  10481. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10482. if (!tbody) return;
  10483. const empty = document.getElementById('rf-comm-lists-empty');
  10484. const statusCount = document.getElementById('rf-status-count');
  10485. let list = (state.routingCommunityLists || []).slice();
  10486. const q = state.rfSearchQuery;
  10487. if (q) {
  10488. list = list.filter(cl =>
  10489. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10490. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10491. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10492. );
  10493. }
  10494. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10495. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10496. }
  10497. if (list.length === 0) {
  10498. tbody.innerHTML = '';
  10499. if (empty) empty.classList.remove('hidden');
  10500. return;
  10501. }
  10502. if (empty) empty.classList.add('hidden');
  10503. tbody.innerHTML = list.map(cl => {
  10504. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10505. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10506. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10507. const commBadges = (cl.communities || []).map(c =>
  10508. `<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>`
  10509. ).join(' ');
  10510. return `
  10511. <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'}">
  10512. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10513. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10514. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10515. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10516. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10517. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10518. <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'}">
  10519. ${cl.disabled ? 'Enable' : 'Disable'}
  10520. </button>
  10521. <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">
  10522. Edit
  10523. </button>
  10524. <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">
  10525. ✕
  10526. </button>
  10527. </td>
  10528. </tr>
  10529. `;
  10530. }).join('');
  10531. }
  10532. // -------------------------------------------------------------
  10533. // TAB 4: AS LISTS (/routing filter num-list)
  10534. // -------------------------------------------------------------
  10535. function renderRoutingFilterASLists() {
  10536. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10537. if (!tbody) return;
  10538. const empty = document.getElementById('rf-as-lists-empty');
  10539. const statusCount = document.getElementById('rf-status-count');
  10540. let list = (state.routingASLists || []).slice();
  10541. const q = state.rfSearchQuery;
  10542. if (q) {
  10543. list = list.filter(al =>
  10544. (al.name && al.name.toLowerCase().includes(q)) ||
  10545. (al.range && al.range.toLowerCase().includes(q)) ||
  10546. (al.comment && al.comment.toLowerCase().includes(q))
  10547. );
  10548. }
  10549. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10550. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10551. }
  10552. if (list.length === 0) {
  10553. tbody.innerHTML = '';
  10554. if (empty) empty.classList.remove('hidden');
  10555. return;
  10556. }
  10557. if (empty) empty.classList.add('hidden');
  10558. tbody.innerHTML = list.map(al => {
  10559. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10560. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10561. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10562. return `
  10563. <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'}">
  10564. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10565. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10566. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10567. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10568. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10569. <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'}">
  10570. ${al.disabled ? 'Enable' : 'Disable'}
  10571. </button>
  10572. <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">
  10573. Edit
  10574. </button>
  10575. <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">
  10576. ✕
  10577. </button>
  10578. </td>
  10579. </tr>
  10580. `;
  10581. }).join('');
  10582. }
  10583. // -------------------------------------------------------------
  10584. // SNIPPETS & WIZARD HELPERS
  10585. // -------------------------------------------------------------
  10586. function insertRuleSnippet(type) {
  10587. const textarea = document.getElementById('modal-rf-rule');
  10588. if (!textarea) return;
  10589. let snippet = '';
  10590. switch (type) {
  10591. case 'accept-default':
  10592. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10593. break;
  10594. case 'drop-rfc1918':
  10595. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10596. break;
  10597. case 'len-24':
  10598. snippet = 'if (dst-len > 24) { reject; }';
  10599. break;
  10600. case 'local-pref-150':
  10601. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10602. break;
  10603. case 'as-prepend-2':
  10604. snippet = 'set bgp-path-prepend 2; accept;';
  10605. break;
  10606. case 'set-comm':
  10607. snippet = 'set bgp-communities.add 65000:100; accept;';
  10608. break;
  10609. case 'match-comm':
  10610. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10611. break;
  10612. case 'reject-all':
  10613. snippet = 'reject;';
  10614. break;
  10615. }
  10616. if (!snippet) return;
  10617. if (!textarea.value.trim()) {
  10618. textarea.value = snippet;
  10619. } else {
  10620. textarea.value = textarea.value.trim() + '\n' + snippet;
  10621. }
  10622. }
  10623. function generateScriptFromWizard() {
  10624. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10625. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10626. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10627. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10628. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10629. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10630. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10631. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10632. const conds = [];
  10633. if (pfx) {
  10634. if (pfxLen) {
  10635. if (pfxLen.includes('-')) {
  10636. const parts = pfxLen.split('-');
  10637. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10638. } else {
  10639. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10640. }
  10641. } else {
  10642. conds.push(`dst in ${pfx}`);
  10643. }
  10644. }
  10645. if (proto && proto !== 'any') {
  10646. conds.push(`protocol ${proto}`);
  10647. }
  10648. if (asp) {
  10649. conds.push(`bgp-as-path "${asp}"`);
  10650. }
  10651. if (comm) {
  10652. conds.push(`bgp-communities includes ${comm}`);
  10653. }
  10654. const actions = [];
  10655. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10656. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10657. actions.push(`${act};`);
  10658. let code = '';
  10659. if (conds.length > 0) {
  10660. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10661. } else {
  10662. code = actions.join(' ');
  10663. }
  10664. const textarea = document.getElementById('modal-rf-rule');
  10665. if (textarea) textarea.value = code;
  10666. }
  10667. // -------------------------------------------------------------
  10668. // MODAL CRUD: RULES (/routing filter rule)
  10669. // -------------------------------------------------------------
  10670. function openAddRoutingFilterModal(defaultChain = '') {
  10671. const form = document.getElementById('routing-filter-form');
  10672. if (form) form.reset();
  10673. const idEl = document.getElementById('modal-rf-id');
  10674. if (idEl) idEl.value = '';
  10675. const titleEl = document.getElementById('modal-rf-title');
  10676. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10677. const chainEl = document.getElementById('modal-rf-chain');
  10678. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10679. const orderEl = document.getElementById('modal-rf-order');
  10680. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10681. const ruleEl = document.getElementById('modal-rf-rule');
  10682. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10683. const disEl = document.getElementById('modal-rf-disabled');
  10684. if (disEl) disEl.checked = false;
  10685. const modal = document.getElementById('modal-routing-filter');
  10686. if (modal) modal.classList.remove('hidden');
  10687. }
  10688. function openEditRoutingFilterModal(id) {
  10689. const r = (state.routingFilters || []).find(item => item.id === id);
  10690. if (!r) return;
  10691. const idEl = document.getElementById('modal-rf-id');
  10692. if (idEl) idEl.value = r.id;
  10693. const titleEl = document.getElementById('modal-rf-title');
  10694. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10695. const chainEl = document.getElementById('modal-rf-chain');
  10696. if (chainEl) chainEl.value = r.chain || '';
  10697. const orderEl = document.getElementById('modal-rf-order');
  10698. if (orderEl) orderEl.value = r.rule_order || 10;
  10699. const ruleEl = document.getElementById('modal-rf-rule');
  10700. if (ruleEl) {
  10701. if (r.rule) {
  10702. ruleEl.value = r.rule;
  10703. } else {
  10704. let conds = [];
  10705. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10706. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10707. let act = r.action || 'accept';
  10708. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10709. }
  10710. }
  10711. const comEl = document.getElementById('modal-rf-comment');
  10712. if (comEl) comEl.value = r.comment || '';
  10713. const disEl = document.getElementById('modal-rf-disabled');
  10714. if (disEl) disEl.checked = !!r.disabled;
  10715. const modal = document.getElementById('modal-routing-filter');
  10716. if (modal) modal.classList.remove('hidden');
  10717. }
  10718. function closeRoutingFilterModal() {
  10719. const modal = document.getElementById('modal-routing-filter');
  10720. if (modal) modal.classList.add('hidden');
  10721. }
  10722. async function submitRoutingFilter(e) {
  10723. if (e) e.preventDefault();
  10724. const payload = {
  10725. id: document.getElementById('modal-rf-id').value,
  10726. chain: document.getElementById('modal-rf-chain').value.trim(),
  10727. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10728. rule: document.getElementById('modal-rf-rule').value.trim(),
  10729. comment: document.getElementById('modal-rf-comment').value.trim(),
  10730. disabled: document.getElementById('modal-rf-disabled').checked
  10731. };
  10732. try {
  10733. const res = await fetch(`${API_BASE}/routing/filters`, {
  10734. method: 'POST',
  10735. headers: { 'Content-Type': 'application/json' },
  10736. body: JSON.stringify(payload)
  10737. });
  10738. if (res.ok) {
  10739. closeRoutingFilterModal();
  10740. showToast('Success', 'Routing filter rule saved', 'success');
  10741. loadDynamicRouting();
  10742. } else {
  10743. const err = await res.json();
  10744. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10745. }
  10746. } catch (err) {
  10747. showToast('Error', err.message, 'error');
  10748. }
  10749. }
  10750. async function applyRoutingFilterForm() {
  10751. const payload = {
  10752. id: document.getElementById('modal-rf-id').value,
  10753. chain: document.getElementById('modal-rf-chain').value.trim(),
  10754. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10755. rule: document.getElementById('modal-rf-rule').value.trim(),
  10756. comment: document.getElementById('modal-rf-comment').value.trim(),
  10757. disabled: document.getElementById('modal-rf-disabled').checked
  10758. };
  10759. try {
  10760. const res = await fetch(`${API_BASE}/routing/filters`, {
  10761. method: 'POST',
  10762. headers: { 'Content-Type': 'application/json' },
  10763. body: JSON.stringify(payload)
  10764. });
  10765. if (res.ok) {
  10766. const data = await res.json();
  10767. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10768. showToast('Applied', 'Routing filter configuration applied', 'success');
  10769. loadDynamicRouting();
  10770. } else {
  10771. const err = await res.json();
  10772. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10773. }
  10774. } catch (err) {
  10775. showToast('Error', err.message, 'error');
  10776. }
  10777. }
  10778. async function moveRoutingFilterOrder(id, delta) {
  10779. const list = state.routingFilters || [];
  10780. const idx = list.findIndex(r => r.id === id);
  10781. if (idx < 0) return;
  10782. const targetIdx = idx + delta;
  10783. if (targetIdx < 0 || targetIdx >= list.length) return;
  10784. const currentOrder = list[idx].rule_order || 10;
  10785. const targetOrder = list[targetIdx].rule_order || 20;
  10786. list[idx].rule_order = targetOrder;
  10787. list[targetIdx].rule_order = currentOrder;
  10788. try {
  10789. await fetch(`${API_BASE}/routing/filters`, {
  10790. method: 'POST',
  10791. headers: { 'Content-Type': 'application/json' },
  10792. body: JSON.stringify(list[idx])
  10793. });
  10794. await fetch(`${API_BASE}/routing/filters`, {
  10795. method: 'POST',
  10796. headers: { 'Content-Type': 'application/json' },
  10797. body: JSON.stringify(list[targetIdx])
  10798. });
  10799. loadDynamicRouting();
  10800. } catch (e) {
  10801. console.error('Reorder error:', e);
  10802. }
  10803. }
  10804. async function deleteRoutingFilter(id) {
  10805. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10806. try {
  10807. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10808. if (res.ok) {
  10809. showToast('Deleted', 'Routing filter rule removed', 'info');
  10810. loadDynamicRouting();
  10811. } else {
  10812. const err = await res.json();
  10813. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10814. }
  10815. } catch (err) {
  10816. showToast('Error', err.message, 'error');
  10817. }
  10818. }
  10819. async function toggleRoutingFilterState(id, disabled) {
  10820. try {
  10821. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10822. method: 'POST',
  10823. headers: { 'Content-Type': 'application/json' },
  10824. body: JSON.stringify({ disabled })
  10825. });
  10826. if (res.ok) {
  10827. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10828. loadDynamicRouting();
  10829. } else {
  10830. const err = await res.json();
  10831. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10832. }
  10833. } catch (err) {
  10834. showToast('Error', err.message, 'error');
  10835. }
  10836. }
  10837. // -------------------------------------------------------------
  10838. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10839. // -------------------------------------------------------------
  10840. function openAddSelectRuleModal() {
  10841. document.getElementById('modal-rf-sr-id').value = '';
  10842. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10843. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10844. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10845. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10846. document.getElementById('modal-rf-sr-comment').value = '';
  10847. document.getElementById('modal-rf-sr-disabled').checked = false;
  10848. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10849. }
  10850. function openEditSelectRuleModal(id) {
  10851. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10852. if (!r) return;
  10853. document.getElementById('modal-rf-sr-id').value = r.id;
  10854. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10855. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10856. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10857. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10858. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10859. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10860. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10861. }
  10862. function closeSelectRuleModal() {
  10863. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10864. }
  10865. async function submitSelectRule(e) {
  10866. e.preventDefault();
  10867. const payload = {
  10868. id: document.getElementById('modal-rf-sr-id').value,
  10869. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10870. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10871. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10872. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10873. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10874. };
  10875. try {
  10876. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10877. method: 'POST',
  10878. headers: { 'Content-Type': 'application/json' },
  10879. body: JSON.stringify(payload)
  10880. });
  10881. if (res.ok) {
  10882. closeSelectRuleModal();
  10883. showToast('Success', 'Select rule saved', 'success');
  10884. loadDynamicRouting();
  10885. } else {
  10886. const err = await res.json();
  10887. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10888. }
  10889. } catch (err) {
  10890. showToast('Error', err.message, 'error');
  10891. }
  10892. }
  10893. async function deleteSelectRule(id) {
  10894. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10895. try {
  10896. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10897. if (res.ok) {
  10898. showToast('Deleted', 'Select rule removed', 'info');
  10899. loadDynamicRouting();
  10900. } else {
  10901. const err = await res.json();
  10902. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10903. }
  10904. } catch (err) {
  10905. showToast('Error', err.message, 'error');
  10906. }
  10907. }
  10908. async function toggleSelectRuleState(id, disabled) {
  10909. try {
  10910. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10911. method: 'POST',
  10912. headers: { 'Content-Type': 'application/json' },
  10913. body: JSON.stringify({ disabled })
  10914. });
  10915. if (res.ok) {
  10916. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10917. loadDynamicRouting();
  10918. } else {
  10919. const err = await res.json();
  10920. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10921. }
  10922. } catch (err) {
  10923. showToast('Error', err.message, 'error');
  10924. }
  10925. }
  10926. // -------------------------------------------------------------
  10927. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10928. // -------------------------------------------------------------
  10929. function openAddCommunityListModal() {
  10930. document.getElementById('modal-rf-cl-id').value = '';
  10931. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10932. document.getElementById('modal-rf-cl-name').value = '';
  10933. document.getElementById('modal-rf-cl-communities').value = '';
  10934. document.getElementById('modal-rf-cl-regexp').value = '';
  10935. document.getElementById('modal-rf-cl-comment').value = '';
  10936. document.getElementById('modal-rf-cl-disabled').checked = false;
  10937. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10938. }
  10939. function openEditCommunityListModal(id) {
  10940. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10941. if (!cl) return;
  10942. document.getElementById('modal-rf-cl-id').value = cl.id;
  10943. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10944. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10945. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10946. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10947. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10948. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10949. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10950. }
  10951. function closeCommunityListModal() {
  10952. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10953. }
  10954. async function submitCommunityList(e) {
  10955. e.preventDefault();
  10956. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10957. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10958. const payload = {
  10959. id: document.getElementById('modal-rf-cl-id').value,
  10960. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10961. communities: comms,
  10962. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10963. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10964. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10965. };
  10966. try {
  10967. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10968. method: 'POST',
  10969. headers: { 'Content-Type': 'application/json' },
  10970. body: JSON.stringify(payload)
  10971. });
  10972. if (res.ok) {
  10973. closeCommunityListModal();
  10974. showToast('Success', 'Community list saved', 'success');
  10975. loadDynamicRouting();
  10976. } else {
  10977. const err = await res.json();
  10978. showToast('Error', err.error || 'Failed to save community list', 'error');
  10979. }
  10980. } catch (err) {
  10981. showToast('Error', err.message, 'error');
  10982. }
  10983. }
  10984. async function deleteCommunityList(id) {
  10985. if (!confirm('Are you sure you want to delete this community list?')) return;
  10986. try {
  10987. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10988. if (res.ok) {
  10989. showToast('Deleted', 'Community list removed', 'info');
  10990. loadDynamicRouting();
  10991. } else {
  10992. const err = await res.json();
  10993. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10994. }
  10995. } catch (err) {
  10996. showToast('Error', err.message, 'error');
  10997. }
  10998. }
  10999. async function toggleCommunityListState(id, disabled) {
  11000. try {
  11001. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11002. method: 'POST',
  11003. headers: { 'Content-Type': 'application/json' },
  11004. body: JSON.stringify({ disabled })
  11005. });
  11006. if (res.ok) {
  11007. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11008. loadDynamicRouting();
  11009. } else {
  11010. const err = await res.json();
  11011. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11012. }
  11013. } catch (err) {
  11014. showToast('Error', err.message, 'error');
  11015. }
  11016. }
  11017. // -------------------------------------------------------------
  11018. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11019. // -------------------------------------------------------------
  11020. function openAddASListModal() {
  11021. document.getElementById('modal-rf-al-id').value = '';
  11022. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11023. document.getElementById('modal-rf-al-name').value = '';
  11024. document.getElementById('modal-rf-al-range').value = '';
  11025. document.getElementById('modal-rf-al-comment').value = '';
  11026. document.getElementById('modal-rf-al-disabled').checked = false;
  11027. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11028. }
  11029. function openEditASListModal(id) {
  11030. const al = (state.routingASLists || []).find(item => item.id === id);
  11031. if (!al) return;
  11032. document.getElementById('modal-rf-al-id').value = al.id;
  11033. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11034. document.getElementById('modal-rf-al-name').value = al.name || '';
  11035. document.getElementById('modal-rf-al-range').value = al.range || '';
  11036. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11037. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11038. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11039. }
  11040. function closeASListModal() {
  11041. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11042. }
  11043. async function submitASList(e) {
  11044. e.preventDefault();
  11045. const payload = {
  11046. id: document.getElementById('modal-rf-al-id').value,
  11047. name: document.getElementById('modal-rf-al-name').value.trim(),
  11048. range: document.getElementById('modal-rf-al-range').value.trim(),
  11049. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11050. disabled: document.getElementById('modal-rf-al-disabled').checked
  11051. };
  11052. try {
  11053. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11054. method: 'POST',
  11055. headers: { 'Content-Type': 'application/json' },
  11056. body: JSON.stringify(payload)
  11057. });
  11058. if (res.ok) {
  11059. closeASListModal();
  11060. showToast('Success', 'AS number list saved', 'success');
  11061. loadDynamicRouting();
  11062. } else {
  11063. const err = await res.json();
  11064. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11065. }
  11066. } catch (err) {
  11067. showToast('Error', err.message, 'error');
  11068. }
  11069. }
  11070. async function deleteASList(id) {
  11071. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11072. try {
  11073. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11074. if (res.ok) {
  11075. showToast('Deleted', 'AS list removed', 'info');
  11076. loadDynamicRouting();
  11077. } else {
  11078. const err = await res.json();
  11079. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11080. }
  11081. } catch (err) {
  11082. showToast('Error', err.message, 'error');
  11083. }
  11084. }
  11085. async function toggleASListState(id, disabled) {
  11086. try {
  11087. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11088. method: 'POST',
  11089. headers: { 'Content-Type': 'application/json' },
  11090. body: JSON.stringify({ disabled })
  11091. });
  11092. if (res.ok) {
  11093. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11094. loadDynamicRouting();
  11095. } else {
  11096. const err = await res.json();
  11097. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11098. }
  11099. } catch (err) {
  11100. showToast('Error', err.message, 'error');
  11101. }
  11102. }
  11103. // ==========================================
  11104. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11105. // ==========================================
  11106. function loadToolsView() {
  11107. populateToolsInterfaces();
  11108. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11109. }
  11110. function populateToolsInterfaces() {
  11111. const pingSel = document.getElementById('tools-ping-iface');
  11112. const traceSel = document.getElementById('tools-tr-iface');
  11113. let opts = '<option value="">Auto (Default Route)</option>';
  11114. if (Array.isArray(state.interfaces)) {
  11115. state.interfaces.forEach(iface => {
  11116. if (iface.name) {
  11117. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11118. }
  11119. });
  11120. }
  11121. if (pingSel) {
  11122. const cur = pingSel.value;
  11123. pingSel.innerHTML = opts;
  11124. if (cur) pingSel.value = cur;
  11125. }
  11126. if (traceSel) {
  11127. const cur = traceSel.value;
  11128. traceSel.innerHTML = opts;
  11129. if (cur) traceSel.value = cur;
  11130. }
  11131. }
  11132. function switchToolsSubTab(subTab) {
  11133. state.activeToolsSubTab = subTab;
  11134. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11135. tabs.forEach(t => {
  11136. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11137. const view = document.getElementById(`tools-view-${t}`);
  11138. if (btn) {
  11139. if (t === subTab) {
  11140. 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';
  11141. } else {
  11142. 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';
  11143. }
  11144. }
  11145. if (view) {
  11146. if (t === subTab) {
  11147. view.classList.remove('hidden');
  11148. } else {
  11149. view.classList.add('hidden');
  11150. }
  11151. }
  11152. });
  11153. }
  11154. function setPortPreset(port) {
  11155. const input = document.getElementById('tools-port-num');
  11156. if (input) input.value = port;
  11157. }
  11158. let pingAbortController = null;
  11159. let tracerouteAbortController = null;
  11160. function clearPingTable() {
  11161. const tbody = document.getElementById('tools-ping-tbody');
  11162. if (tbody) tbody.innerHTML = '';
  11163. const rawEl = document.getElementById('tools-ping-raw');
  11164. if (rawEl) rawEl.innerText = '';
  11165. const sentEl = document.getElementById('tools-ping-stat-sent');
  11166. if (sentEl) sentEl.innerText = '0';
  11167. const recvEl = document.getElementById('tools-ping-stat-recv');
  11168. if (recvEl) recvEl.innerText = '0';
  11169. const lossEl = document.getElementById('tools-ping-stat-loss');
  11170. if (lossEl) lossEl.innerText = '0%';
  11171. const avgEl = document.getElementById('tools-ping-stat-avg');
  11172. if (avgEl) avgEl.innerText = '0 ms';
  11173. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11174. if (minMaxEl) minMaxEl.innerText = '-';
  11175. const badge = document.getElementById('tools-ping-status-badge');
  11176. if (badge) {
  11177. badge.className = '';
  11178. badge.innerText = '';
  11179. }
  11180. }
  11181. function clearTracerouteTable() {
  11182. const tbody = document.getElementById('tools-tr-tbody');
  11183. if (tbody) tbody.innerHTML = '';
  11184. const rawEl = document.getElementById('tools-tr-raw');
  11185. if (rawEl) rawEl.innerText = '';
  11186. const statHops = document.getElementById('tools-tr-hops-count');
  11187. if (statHops) statHops.innerText = '0 Hops';
  11188. }
  11189. function resetPingButton() {
  11190. const btn = document.getElementById('tools-ping-btn');
  11191. const btnText = document.getElementById('tools-ping-btn-text');
  11192. const spinner = document.getElementById('tools-ping-spinner');
  11193. if (btn) {
  11194. btn.disabled = false;
  11195. 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';
  11196. }
  11197. if (btnText) btnText.innerText = 'Start Ping';
  11198. if (spinner) spinner.classList.add('hidden');
  11199. }
  11200. function setPingRunningButton() {
  11201. const btn = document.getElementById('tools-ping-btn');
  11202. const btnText = document.getElementById('tools-ping-btn-text');
  11203. const spinner = document.getElementById('tools-ping-spinner');
  11204. if (btn) {
  11205. btn.disabled = false;
  11206. 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';
  11207. }
  11208. if (btnText) btnText.innerText = 'Stop Ping';
  11209. if (spinner) spinner.classList.remove('hidden');
  11210. }
  11211. function resetTracerouteButton() {
  11212. const btn = document.getElementById('tools-tr-btn');
  11213. const btnText = document.getElementById('tools-tr-btn-text');
  11214. const spinner = document.getElementById('tools-tr-spinner');
  11215. if (btn) {
  11216. btn.disabled = false;
  11217. 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';
  11218. }
  11219. if (btnText) btnText.innerText = 'Start Traceroute';
  11220. if (spinner) spinner.classList.add('hidden');
  11221. }
  11222. function setTracerouteRunningButton() {
  11223. const btn = document.getElementById('tools-tr-btn');
  11224. const btnText = document.getElementById('tools-tr-btn-text');
  11225. const spinner = document.getElementById('tools-tr-spinner');
  11226. if (btn) {
  11227. btn.disabled = false;
  11228. 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';
  11229. }
  11230. if (btnText) btnText.innerText = 'Stop Traceroute';
  11231. if (spinner) spinner.classList.remove('hidden');
  11232. }
  11233. async function executePing(e) {
  11234. if (e) e.preventDefault();
  11235. // If already running, clicking the button stops the stream!
  11236. if (pingAbortController) {
  11237. pingAbortController.abort();
  11238. pingAbortController = null;
  11239. resetPingButton();
  11240. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11241. return;
  11242. }
  11243. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11244. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11245. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11246. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11247. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11248. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11249. if (!target) {
  11250. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11251. return;
  11252. }
  11253. clearPingTable();
  11254. const resCard = document.getElementById('tools-ping-results');
  11255. if (resCard) resCard.classList.remove('hidden');
  11256. pingAbortController = new AbortController();
  11257. setPingRunningButton();
  11258. try {
  11259. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11260. method: 'POST',
  11261. headers: { 'Content-Type': 'application/json' },
  11262. body: JSON.stringify({
  11263. target,
  11264. count,
  11265. size,
  11266. timeout,
  11267. interface: iface,
  11268. dont_frag: dontFrag
  11269. }),
  11270. signal: pingAbortController.signal
  11271. });
  11272. if (!res.ok) {
  11273. const errText = await res.text();
  11274. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11275. resetPingButton();
  11276. pingAbortController = null;
  11277. return;
  11278. }
  11279. const reader = res.body.getReader();
  11280. const decoder = new TextDecoder('utf-8');
  11281. let buffer = '';
  11282. while (true) {
  11283. const { done, value } = await reader.read();
  11284. if (done) break;
  11285. buffer += decoder.decode(value, { stream: true });
  11286. const blocks = buffer.split('\n\n');
  11287. buffer = blocks.pop() || '';
  11288. for (const block of blocks) {
  11289. const trimmed = block.trim();
  11290. if (!trimmed) continue;
  11291. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11292. try {
  11293. const evt = JSON.parse(line);
  11294. handleLivePingEvent(evt);
  11295. } catch (parseErr) {
  11296. console.warn('Ping SSE parse error:', parseErr, line);
  11297. }
  11298. }
  11299. }
  11300. } catch (err) {
  11301. if (err.name === 'AbortError') {
  11302. // User aborted normally
  11303. } else {
  11304. showToast('Ping Error', err.message, 'error');
  11305. }
  11306. } finally {
  11307. pingAbortController = null;
  11308. resetPingButton();
  11309. }
  11310. }
  11311. function handleLivePingEvent(evt) {
  11312. const sentEl = document.getElementById('tools-ping-stat-sent');
  11313. const recvEl = document.getElementById('tools-ping-stat-recv');
  11314. const lossEl = document.getElementById('tools-ping-stat-loss');
  11315. const avgEl = document.getElementById('tools-ping-stat-avg');
  11316. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11317. const badge = document.getElementById('tools-ping-status-badge');
  11318. const tbody = document.getElementById('tools-ping-tbody');
  11319. const rawEl = document.getElementById('tools-ping-raw');
  11320. if (evt.raw && rawEl) {
  11321. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11322. rawEl.scrollTop = rawEl.scrollHeight;
  11323. }
  11324. if (evt.type === 'reply') {
  11325. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11326. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11327. if (lossEl && evt.packet_loss_pct !== undefined) {
  11328. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11329. lossEl.className = evt.packet_loss_pct === 0
  11330. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11331. : (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');
  11332. }
  11333. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11334. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11335. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11336. }
  11337. if (badge) {
  11338. if (evt.packet_loss_pct === 0) {
  11339. 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';
  11340. badge.innerText = '100% OK';
  11341. } else {
  11342. 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';
  11343. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11344. }
  11345. }
  11346. if (tbody) {
  11347. const tr = document.createElement('tr');
  11348. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11349. tr.innerHTML = `
  11350. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11351. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11352. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11353. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11354. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11355. <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>
  11356. `;
  11357. tbody.appendChild(tr);
  11358. }
  11359. } else if (evt.type === 'timeout') {
  11360. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11361. if (lossEl && evt.packet_loss_pct !== undefined) {
  11362. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11363. 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';
  11364. }
  11365. if (badge) {
  11366. 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';
  11367. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11368. }
  11369. if (tbody) {
  11370. const tr = document.createElement('tr');
  11371. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11372. tr.innerHTML = `
  11373. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11374. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11375. <td class="py-2 px-3 text-slate-600">--</td>
  11376. <td class="py-2 px-3 text-slate-600">--</td>
  11377. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11378. <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>
  11379. `;
  11380. tbody.appendChild(tr);
  11381. }
  11382. } else if (evt.type === 'unreach') {
  11383. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11384. if (lossEl && evt.packet_loss_pct !== undefined) {
  11385. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11386. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11387. }
  11388. if (badge) {
  11389. 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';
  11390. badge.innerText = 'UNREACHABLE';
  11391. }
  11392. if (tbody) {
  11393. const tr = document.createElement('tr');
  11394. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11395. tr.innerHTML = `
  11396. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11397. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11398. <td class="py-2 px-3 text-slate-600">--</td>
  11399. <td class="py-2 px-3 text-slate-600">--</td>
  11400. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11401. <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>
  11402. `;
  11403. tbody.appendChild(tr);
  11404. }
  11405. } else if (evt.type === 'stats') {
  11406. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11407. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11408. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11409. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11410. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11411. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11412. }
  11413. } else if (evt.type === 'done') {
  11414. 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');
  11415. }
  11416. }
  11417. async function executeTraceroute(e) {
  11418. if (e) e.preventDefault();
  11419. if (tracerouteAbortController) {
  11420. tracerouteAbortController.abort();
  11421. tracerouteAbortController = null;
  11422. resetTracerouteButton();
  11423. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11424. return;
  11425. }
  11426. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11427. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11428. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11429. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11430. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11431. if (!target) {
  11432. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11433. return;
  11434. }
  11435. clearTracerouteTable();
  11436. const resCard = document.getElementById('tools-tr-results');
  11437. if (resCard) resCard.classList.remove('hidden');
  11438. tracerouteAbortController = new AbortController();
  11439. setTracerouteRunningButton();
  11440. try {
  11441. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11442. method: 'POST',
  11443. headers: { 'Content-Type': 'application/json' },
  11444. body: JSON.stringify({
  11445. target,
  11446. max_hops: maxHops,
  11447. protocol,
  11448. interface: iface,
  11449. resolve
  11450. }),
  11451. signal: tracerouteAbortController.signal
  11452. });
  11453. if (!res.ok) {
  11454. const errText = await res.text();
  11455. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11456. resetTracerouteButton();
  11457. tracerouteAbortController = null;
  11458. return;
  11459. }
  11460. const reader = res.body.getReader();
  11461. const decoder = new TextDecoder('utf-8');
  11462. let buffer = '';
  11463. while (true) {
  11464. const { done, value } = await reader.read();
  11465. if (done) break;
  11466. buffer += decoder.decode(value, { stream: true });
  11467. const blocks = buffer.split('\n\n');
  11468. buffer = blocks.pop() || '';
  11469. for (const block of blocks) {
  11470. const trimmed = block.trim();
  11471. if (!trimmed) continue;
  11472. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11473. try {
  11474. const evt = JSON.parse(line);
  11475. handleLiveTracerouteEvent(evt);
  11476. } catch (parseErr) {
  11477. console.warn('Traceroute SSE parse error:', parseErr, line);
  11478. }
  11479. }
  11480. }
  11481. } catch (err) {
  11482. if (err.name === 'AbortError') {
  11483. // User aborted normally
  11484. } else {
  11485. showToast('Traceroute Error', err.message, 'error');
  11486. }
  11487. } finally {
  11488. tracerouteAbortController = null;
  11489. resetTracerouteButton();
  11490. }
  11491. }
  11492. function handleLiveTracerouteEvent(evt) {
  11493. const statHops = document.getElementById('tools-tr-hops-count');
  11494. const tbody = document.getElementById('tools-tr-tbody');
  11495. const rawEl = document.getElementById('tools-tr-raw');
  11496. if (evt.raw && rawEl) {
  11497. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11498. rawEl.scrollTop = rawEl.scrollHeight;
  11499. }
  11500. if (evt.hops_count !== undefined && statHops) {
  11501. statHops.innerText = `${evt.hops_count} Hops`;
  11502. }
  11503. if (evt.type === 'hop' && evt.hop && tbody) {
  11504. const h = evt.hop;
  11505. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11506. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11507. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11508. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11509. const tr = document.createElement('tr');
  11510. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11511. tr.innerHTML = `
  11512. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11513. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11514. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11515. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11516. <td class="py-2.5 px-3 text-right">
  11517. ${isTimeout
  11518. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11519. : '<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>'}
  11520. </td>
  11521. `;
  11522. tbody.appendChild(tr);
  11523. } else if (evt.type === 'done') {
  11524. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11525. }
  11526. }
  11527. async function executeMTR(e) {
  11528. if (e) e.preventDefault();
  11529. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11530. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11531. if (!target) {
  11532. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11533. return;
  11534. }
  11535. const btn = document.getElementById('tools-mtr-btn');
  11536. const spinner = document.getElementById('tools-mtr-spinner');
  11537. if (btn) btn.disabled = true;
  11538. if (spinner) spinner.classList.remove('hidden');
  11539. try {
  11540. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11541. method: 'POST',
  11542. headers: { 'Content-Type': 'application/json' },
  11543. body: JSON.stringify({ target, count: cycles })
  11544. });
  11545. const data = await res.json();
  11546. if (!res.ok) {
  11547. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11548. return;
  11549. }
  11550. const resCard = document.getElementById('tools-mtr-results');
  11551. if (resCard) resCard.classList.remove('hidden');
  11552. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11553. const statHops = document.getElementById('tools-mtr-hops-count');
  11554. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11555. const tbody = document.getElementById('tools-mtr-tbody');
  11556. if (tbody) {
  11557. if (hopsCount > 0) {
  11558. tbody.innerHTML = data.hops.map(h => {
  11559. 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');
  11560. return `
  11561. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11562. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11563. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11564. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11565. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11566. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11567. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11568. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11569. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11570. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11571. </tr>
  11572. `;
  11573. }).join('');
  11574. } else {
  11575. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11576. }
  11577. }
  11578. const rawEl = document.getElementById('tools-mtr-raw');
  11579. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11580. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11581. } catch (err) {
  11582. showToast('MTR Error', err.message, 'error');
  11583. } finally {
  11584. if (btn) btn.disabled = false;
  11585. if (spinner) spinner.classList.add('hidden');
  11586. }
  11587. }
  11588. async function executeDNS(e) {
  11589. if (e) e.preventDefault();
  11590. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11591. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11592. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11593. if (!domain) {
  11594. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11595. return;
  11596. }
  11597. const btn = document.getElementById('tools-dns-btn');
  11598. const spinner = document.getElementById('tools-dns-spinner');
  11599. if (btn) btn.disabled = true;
  11600. if (spinner) spinner.classList.remove('hidden');
  11601. try {
  11602. const res = await fetch(`${API_BASE}/tools/dns`, {
  11603. method: 'POST',
  11604. headers: { 'Content-Type': 'application/json' },
  11605. body: JSON.stringify({ domain, type, server })
  11606. });
  11607. const data = await res.json();
  11608. if (!res.ok) {
  11609. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11610. return;
  11611. }
  11612. const resCard = document.getElementById('tools-dns-results');
  11613. if (resCard) resCard.classList.remove('hidden');
  11614. const metaEl = document.getElementById('tools-dns-meta');
  11615. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11616. const tbody = document.getElementById('tools-dns-tbody');
  11617. if (tbody) {
  11618. if (Array.isArray(data.records) && data.records.length > 0) {
  11619. tbody.innerHTML = data.records.map(r => `
  11620. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11621. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11622. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11623. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11624. <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>
  11625. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11626. </tr>
  11627. `).join('');
  11628. } else {
  11629. 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>`;
  11630. }
  11631. }
  11632. const rawEl = document.getElementById('tools-dns-raw');
  11633. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11634. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11635. } catch (err) {
  11636. showToast('DNS Error', err.message, 'error');
  11637. } finally {
  11638. if (btn) btn.disabled = false;
  11639. if (spinner) spinner.classList.add('hidden');
  11640. }
  11641. }
  11642. async function executePortProbe(e) {
  11643. if (e) e.preventDefault();
  11644. const target = document.getElementById('tools-port-target')?.value?.trim();
  11645. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11646. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11647. if (!target || !port) {
  11648. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11649. return;
  11650. }
  11651. const btn = document.getElementById('tools-port-btn');
  11652. const spinner = document.getElementById('tools-port-spinner');
  11653. if (btn) btn.disabled = true;
  11654. if (spinner) spinner.classList.remove('hidden');
  11655. try {
  11656. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11657. method: 'POST',
  11658. headers: { 'Content-Type': 'application/json' },
  11659. body: JSON.stringify({ target, port, timeout })
  11660. });
  11661. const data = await res.json();
  11662. if (!res.ok) {
  11663. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11664. return;
  11665. }
  11666. const resCard = document.getElementById('tools-port-results');
  11667. if (resCard) resCard.classList.remove('hidden');
  11668. const banner = document.getElementById('tools-port-banner');
  11669. const icon = document.getElementById('tools-port-icon');
  11670. const title = document.getElementById('tools-port-title');
  11671. const sub = document.getElementById('tools-port-sub');
  11672. const latency = document.getElementById('tools-port-latency');
  11673. if (data.open) {
  11674. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11675. if (icon) {
  11676. 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';
  11677. icon.innerText = '✓';
  11678. }
  11679. if (title) {
  11680. title.className = 'text-sm font-bold text-emerald-300';
  11681. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11682. }
  11683. if (sub) {
  11684. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11685. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11686. }
  11687. if (latency) {
  11688. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11689. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11690. }
  11691. } else {
  11692. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11693. if (icon) {
  11694. 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';
  11695. icon.innerText = '✕';
  11696. }
  11697. if (title) {
  11698. title.className = 'text-sm font-bold text-rose-300';
  11699. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11700. }
  11701. if (sub) {
  11702. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11703. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11704. }
  11705. if (latency) {
  11706. latency.className = 'text-base font-bold font-mono text-slate-500';
  11707. latency.innerText = '--';
  11708. }
  11709. }
  11710. const rawEl = document.getElementById('tools-port-raw');
  11711. 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'}`);
  11712. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11713. } catch (err) {
  11714. showToast('Probe Error', err.message, 'error');
  11715. } finally {
  11716. if (btn) btn.disabled = false;
  11717. if (spinner) spinner.classList.add('hidden');
  11718. }
  11719. }
  11720. // ==========================================
  11721. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11722. // ==========================================
  11723. async function loadDHCPClients(showToastMsg = false) {
  11724. try {
  11725. const [clientsRes, sumRes] = await Promise.all([
  11726. fetch(`${API_BASE}/dhcp/clients`),
  11727. fetch(`${API_BASE}/dhcp/clients/summary`)
  11728. ]);
  11729. if (clientsRes.ok) {
  11730. state.dhcpClients = await clientsRes.json();
  11731. }
  11732. if (sumRes.ok) {
  11733. state.dhcpSummary = await sumRes.json();
  11734. }
  11735. renderDHCPClients();
  11736. updateDHCPSummaryCards();
  11737. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11738. if (bDhcp && state.dhcpSummary) {
  11739. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11740. }
  11741. if (showToastMsg) {
  11742. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11743. }
  11744. } catch (err) {
  11745. console.error('Failed to load DHCP clients:', err);
  11746. if (showToastMsg) {
  11747. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11748. }
  11749. }
  11750. }
  11751. function updateDHCPSummaryCards() {
  11752. const sum = state.dhcpSummary || {
  11753. total_clients: (state.dhcpClients || []).length,
  11754. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11755. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11756. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11757. };
  11758. const totalEl = document.getElementById('dhcp-stat-total');
  11759. const boundEl = document.getElementById('dhcp-stat-bound');
  11760. const searchEl = document.getElementById('dhcp-stat-searching');
  11761. const disEl = document.getElementById('dhcp-stat-disabled');
  11762. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11763. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11764. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11765. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11766. }
  11767. function renderDHCPClients() {
  11768. const tbody = document.getElementById('dhcp-clients-tbody');
  11769. const emptyState = document.getElementById('dhcp-clients-empty');
  11770. if (!tbody) return;
  11771. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11772. if (clients.length === 0) {
  11773. tbody.innerHTML = '';
  11774. if (emptyState) emptyState.classList.remove('hidden');
  11775. return;
  11776. }
  11777. if (emptyState) emptyState.classList.add('hidden');
  11778. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11779. if (tbody.dataset.sig === sig) return;
  11780. tbody.dataset.sig = sig;
  11781. tbody.innerHTML = clients.map(c => {
  11782. let statusBadge = '';
  11783. if (!c.enabled) {
  11784. 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>';
  11785. } else if (c.status === 'bound') {
  11786. 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>';
  11787. } else if (c.status === 'searching') {
  11788. 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>';
  11789. } else if (c.status === 'stopped') {
  11790. 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>';
  11791. } else {
  11792. 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>`;
  11793. }
  11794. 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>';
  11795. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11796. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11797. 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>';
  11798. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11799. // Option flags
  11800. const flags = [];
  11801. 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>');
  11802. 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>');
  11803. 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>');
  11804. 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>`);
  11805. return `
  11806. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11807. <td class="py-3 px-4">
  11808. <div class="flex items-center gap-2">
  11809. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11810. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11811. </div>
  11812. </td>
  11813. <td class="py-3 px-4">${statusBadge}</td>
  11814. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11815. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11816. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11817. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11818. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11819. <td class="py-3 px-4">
  11820. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11821. </td>
  11822. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11823. ${c.enabled ? `
  11824. <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>
  11825. <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>
  11826. <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>
  11827. ` : `
  11828. <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>
  11829. `}
  11830. <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>
  11831. <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>
  11832. </td>
  11833. </tr>
  11834. `;
  11835. }).join('');
  11836. }
  11837. function openDHCPClientModal(clientId = null) {
  11838. const modal = document.getElementById('modal-dhcp-client');
  11839. if (!modal) return;
  11840. const title = document.getElementById('modal-dhcp-title');
  11841. const idInput = document.getElementById('modal-dhcp-id');
  11842. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11843. const distInput = document.getElementById('modal-dhcp-distance');
  11844. const commentInput = document.getElementById('modal-dhcp-comment');
  11845. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11846. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11847. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11848. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11849. // Populate interfaces
  11850. if (ifaceSelect) {
  11851. let opts = '<option value="">Select interface...</option>';
  11852. const allIfaces = state.interfaces || [];
  11853. const allVlans = state.vlans || [];
  11854. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11855. // Group 1: Physical & Bridge Interfaces
  11856. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11857. allIfaces.forEach(i => {
  11858. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11859. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11860. });
  11861. opts += '</optgroup>';
  11862. // Group 2: VLAN Interfaces
  11863. if (allVlans.length > 0) {
  11864. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11865. allVlans.forEach(v => {
  11866. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11867. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11868. });
  11869. opts += '</optgroup>';
  11870. }
  11871. ifaceSelect.innerHTML = opts;
  11872. }
  11873. if (clientId) {
  11874. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11875. if (client) {
  11876. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11877. if (idInput) idInput.value = client.id;
  11878. if (ifaceSelect) {
  11879. ifaceSelect.value = client.interface;
  11880. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11881. }
  11882. if (distInput) distInput.value = client.default_route_distance || 1;
  11883. if (commentInput) commentInput.value = client.comment || '';
  11884. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11885. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11886. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11887. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11888. }
  11889. } else {
  11890. if (title) title.innerText = 'Add DHCP Client';
  11891. if (idInput) idInput.value = '';
  11892. if (ifaceSelect) {
  11893. ifaceSelect.value = '';
  11894. ifaceSelect.disabled = false;
  11895. }
  11896. if (distInput) distInput.value = 1;
  11897. if (commentInput) commentInput.value = '';
  11898. if (defRouteCheck) defRouteCheck.checked = true;
  11899. if (peerDnsCheck) peerDnsCheck.checked = true;
  11900. if (peerNtpCheck) peerNtpCheck.checked = true;
  11901. if (enabledCheck) enabledCheck.checked = true;
  11902. }
  11903. modal.classList.remove('hidden');
  11904. }
  11905. function openDHCPClientModalForIface(ifaceName) {
  11906. openDHCPClientModal();
  11907. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11908. if (ifaceSelect && ifaceName) {
  11909. ifaceSelect.value = ifaceName;
  11910. }
  11911. }
  11912. function closeDHCPClientModal() {
  11913. const modal = document.getElementById('modal-dhcp-client');
  11914. if (modal) modal.classList.add('hidden');
  11915. }
  11916. async function submitSaveDHCPClient(e) {
  11917. if (e) e.preventDefault();
  11918. const id = document.getElementById('modal-dhcp-id')?.value;
  11919. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11920. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11921. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11922. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11923. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11924. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11925. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11926. if (!id && !iface) {
  11927. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11928. return;
  11929. }
  11930. try {
  11931. let res;
  11932. if (id) {
  11933. // PUT update
  11934. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11935. method: 'PUT',
  11936. headers: { 'Content-Type': 'application/json' },
  11937. body: JSON.stringify({
  11938. enabled,
  11939. add_default_route: defRoute,
  11940. default_route_distance: distance,
  11941. use_peer_dns: peerDns,
  11942. use_peer_ntp: peerNtp,
  11943. comment
  11944. })
  11945. });
  11946. } else {
  11947. // POST create
  11948. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11949. method: 'POST',
  11950. headers: { 'Content-Type': 'application/json' },
  11951. body: JSON.stringify({
  11952. interface: iface,
  11953. enabled,
  11954. add_default_route: defRoute,
  11955. default_route_distance: distance,
  11956. use_peer_dns: peerDns,
  11957. use_peer_ntp: peerNtp,
  11958. comment
  11959. })
  11960. });
  11961. }
  11962. const data = await res.json();
  11963. if (!res.ok) {
  11964. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11965. return;
  11966. }
  11967. closeDHCPClientModal();
  11968. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11969. await loadDHCPClients();
  11970. fetchData(); // refresh interfaces list with new lease/status
  11971. } catch (err) {
  11972. showToast('Error', err.message, 'error');
  11973. }
  11974. }
  11975. async function toggleDHCPClientState(id, enabled) {
  11976. try {
  11977. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11978. method: 'POST',
  11979. headers: { 'Content-Type': 'application/json' },
  11980. body: JSON.stringify({ enabled })
  11981. });
  11982. const data = await res.json();
  11983. if (!res.ok) {
  11984. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11985. return;
  11986. }
  11987. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11988. await loadDHCPClients();
  11989. fetchData();
  11990. } catch (err) {
  11991. showToast('Error', err.message, 'error');
  11992. }
  11993. }
  11994. async function renewDHCPClient(id) {
  11995. try {
  11996. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11997. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11998. method: 'POST'
  11999. });
  12000. const data = await res.json();
  12001. if (!res.ok) {
  12002. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12003. return;
  12004. }
  12005. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12006. setTimeout(() => {
  12007. loadDHCPClients();
  12008. fetchData();
  12009. }, 1500);
  12010. } catch (err) {
  12011. showToast('Error', err.message, 'error');
  12012. }
  12013. }
  12014. async function releaseDHCPClient(id) {
  12015. try {
  12016. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12017. method: 'POST'
  12018. });
  12019. const data = await res.json();
  12020. if (!res.ok) {
  12021. showToast('Error', data.error || 'Failed to release lease', 'error');
  12022. return;
  12023. }
  12024. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12025. await loadDHCPClients();
  12026. fetchData();
  12027. } catch (err) {
  12028. showToast('Error', err.message, 'error');
  12029. }
  12030. }
  12031. async function deleteDHCPClient(id, ifaceName) {
  12032. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12033. return;
  12034. }
  12035. try {
  12036. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12037. method: 'DELETE'
  12038. });
  12039. const data = await res.json();
  12040. if (!res.ok) {
  12041. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12042. return;
  12043. }
  12044. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12045. await loadDHCPClients();
  12046. fetchData();
  12047. } catch (err) {
  12048. showToast('Error', err.message, 'error');
  12049. }
  12050. }
  12051. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12052. async function loadDHCPServer(populate = true) {
  12053. try {
  12054. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12055. fetch(`${API_BASE}/dhcp-server/summary`),
  12056. fetch(`${API_BASE}/dhcp-server/servers`),
  12057. fetch(`${API_BASE}/dhcp-server/networks`),
  12058. fetch(`${API_BASE}/dhcp-server/leases`),
  12059. fetch(`${API_BASE}/dhcp-server/options`)
  12060. ]);
  12061. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12062. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12063. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12064. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12065. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12066. const sum = state.dhcpServerSummary || {};
  12067. const srvs = state.dhcpServers || [];
  12068. const nets = state.dhcpNetworks || [];
  12069. const leases = state.dhcpLeases || [];
  12070. const opts = state.dhcpOptions || [];
  12071. // KPI Cards
  12072. const statActive = document.getElementById('dhcp-server-stat-active');
  12073. if (statActive) {
  12074. const activeCount = srvs.filter(s => s.running).length;
  12075. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12076. }
  12077. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12078. if (statLeases) {
  12079. statLeases.innerText = leases.length;
  12080. }
  12081. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12082. if (statLeasesSub) {
  12083. const dyn = leases.filter(l => l.dynamic).length;
  12084. const st = leases.filter(l => !l.dynamic).length;
  12085. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12086. }
  12087. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12088. if (statNetworks) {
  12089. statNetworks.innerText = nets.length;
  12090. }
  12091. // Subtab Badges
  12092. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12093. if (bSrv) bSrv.innerText = srvs.length;
  12094. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12095. if (bNet) bNet.innerText = nets.length;
  12096. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12097. if (bLease) bLease.innerText = leases.length;
  12098. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12099. if (bOpt) bOpt.innerText = opts.length;
  12100. // Sidebar Badge
  12101. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12102. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12103. renderCurrentDHCPServerTab();
  12104. } catch (err) {
  12105. console.error('Failed to load DHCP Server:', err);
  12106. }
  12107. }
  12108. function switchDHCPServerTab(tab) {
  12109. state.dhcpServerTab = tab;
  12110. const tabs = ['servers', 'networks', 'leases', 'options'];
  12111. tabs.forEach(t => {
  12112. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12113. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12114. if (panel) {
  12115. if (t === tab) panel.classList.remove('hidden');
  12116. else panel.classList.add('hidden');
  12117. }
  12118. if (btn) {
  12119. if (t === tab) {
  12120. 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';
  12121. } else {
  12122. 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';
  12123. }
  12124. }
  12125. });
  12126. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12127. if (addBtn) {
  12128. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12129. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12130. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12131. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12132. }
  12133. renderCurrentDHCPServerTab();
  12134. }
  12135. function handleDHCPServerPrimaryAdd() {
  12136. const tab = state.dhcpServerTab || 'servers';
  12137. if (tab === 'servers') openAddDHCPServerModal();
  12138. else if (tab === 'networks') openAddDHCPNetworkModal();
  12139. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12140. else if (tab === 'options') openAddDHCPOptionModal();
  12141. }
  12142. function renderCurrentDHCPServerTab() {
  12143. const tab = state.dhcpServerTab || 'servers';
  12144. if (tab === 'servers') renderDHCPServers();
  12145. else if (tab === 'networks') renderDHCPNetworks();
  12146. else if (tab === 'leases') renderDHCPLeases();
  12147. else if (tab === 'options') renderDHCPOptions();
  12148. }
  12149. function renderDHCPServers() {
  12150. const tbody = document.getElementById('dhcp-server-tbody');
  12151. const empty = document.getElementById('dhcp-server-empty');
  12152. if (!tbody) return;
  12153. const servers = state.dhcpServers || [];
  12154. if (servers.length === 0) {
  12155. tbody.innerHTML = '';
  12156. empty?.classList.remove('hidden');
  12157. return;
  12158. }
  12159. empty?.classList.add('hidden');
  12160. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12161. if (tbody.dataset.sig === sig) return;
  12162. tbody.dataset.sig = sig;
  12163. tbody.innerHTML = '';
  12164. servers.forEach(s => {
  12165. const tr = document.createElement('tr');
  12166. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12167. tr.innerHTML = `
  12168. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12169. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12170. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12171. <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>
  12172. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12173. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12174. <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>
  12175. <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>
  12176. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12177. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12178. <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>
  12179. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12180. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12181. </td>
  12182. `;
  12183. tbody.appendChild(tr);
  12184. });
  12185. }
  12186. function renderDHCPNetworks() {
  12187. const tbody = document.getElementById('dhcp-networks-tbody');
  12188. const empty = document.getElementById('dhcp-networks-empty');
  12189. if (!tbody) return;
  12190. tbody.innerHTML = '';
  12191. const networks = state.dhcpNetworks || [];
  12192. if (networks.length === 0) {
  12193. empty?.classList.remove('hidden');
  12194. return;
  12195. }
  12196. empty?.classList.add('hidden');
  12197. networks.forEach(n => {
  12198. const tr = document.createElement('tr');
  12199. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12200. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12201. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  12202. tr.innerHTML = `
  12203. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12204. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12205. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12206. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12207. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12208. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  12209. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  12210. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  12211. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12212. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12213. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12214. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12215. </td>
  12216. `;
  12217. tbody.appendChild(tr);
  12218. });
  12219. }
  12220. function renderDHCPLeases() {
  12221. const tbody = document.getElementById('dhcp-leases-tbody');
  12222. const empty = document.getElementById('dhcp-leases-empty');
  12223. if (!tbody) return;
  12224. tbody.innerHTML = '';
  12225. const leases = state.dhcpLeases || [];
  12226. if (leases.length === 0) {
  12227. empty?.classList.remove('hidden');
  12228. return;
  12229. }
  12230. empty?.classList.add('hidden');
  12231. leases.forEach(l => {
  12232. const tr = document.createElement('tr');
  12233. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12234. 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>';
  12235. const statusBadge = l.status === 'bound'
  12236. ? '<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>'
  12237. : l.status === 'static'
  12238. ? '<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>'
  12239. : '<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>';
  12240. const makeStaticBtn = l.dynamic
  12241. ? `<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>`
  12242. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12243. tr.innerHTML = `
  12244. <td class="py-2.5 px-3 text-center">${flag}</td>
  12245. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12246. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12247. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12248. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12249. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12250. <td class="py-2.5 px-3">${statusBadge}</td>
  12251. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12252. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12253. ${makeStaticBtn}
  12254. </td>
  12255. `;
  12256. tbody.appendChild(tr);
  12257. });
  12258. }
  12259. function renderDHCPOptions() {
  12260. const tbody = document.getElementById('dhcp-options-tbody');
  12261. const empty = document.getElementById('dhcp-options-empty');
  12262. if (!tbody) return;
  12263. tbody.innerHTML = '';
  12264. const options = state.dhcpOptions || [];
  12265. if (options.length === 0) {
  12266. empty?.classList.remove('hidden');
  12267. return;
  12268. }
  12269. empty?.classList.add('hidden');
  12270. options.forEach(o => {
  12271. const tr = document.createElement('tr');
  12272. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12273. tr.innerHTML = `
  12274. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12275. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12276. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12277. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12278. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12279. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12280. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12281. </td>
  12282. `;
  12283. tbody.appendChild(tr);
  12284. });
  12285. }
  12286. // ==================== MODALS & ACTIONS: SERVER ====================
  12287. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12288. const sel = document.getElementById(elemId);
  12289. if (!sel) return;
  12290. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12291. const networks = state.dhcpNetworks || [];
  12292. networks.forEach(n => {
  12293. const opt = document.createElement('option');
  12294. opt.value = n.address;
  12295. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12296. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12297. opt.selected = true;
  12298. }
  12299. sel.appendChild(opt);
  12300. });
  12301. }
  12302. function onDHCPServerNetworkChange() {
  12303. const netSel = document.getElementById('dhcp-server-modal-network');
  12304. if (!netSel) return;
  12305. const netVal = netSel.value;
  12306. if (!netVal) return;
  12307. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12308. if (!poolInput) return;
  12309. // Auto-calculate suggested address pool based on subnet CIDR
  12310. const parts = netVal.split('/');
  12311. const ip = parts[0];
  12312. const cidr = parseInt(parts[1] || '24', 10);
  12313. if (cidr === 24) {
  12314. const octets = ip.split('.');
  12315. if (octets.length === 4) {
  12316. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12317. poolInput.value = `${base}.10-${base}.254`;
  12318. }
  12319. }
  12320. }
  12321. function openAddDHCPServerModal() {
  12322. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12323. document.getElementById('dhcp-server-modal-id').value = '';
  12324. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12325. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12326. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12327. document.getElementById('dhcp-server-modal-comment').value = '';
  12328. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12329. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12330. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12331. const networks = state.dhcpNetworks || [];
  12332. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12333. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12334. if (defaultNet) {
  12335. onDHCPServerNetworkChange();
  12336. }
  12337. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12338. }
  12339. function openEditDHCPServerModal(id) {
  12340. const s = (state.dhcpServers || []).find(item => item.id === id);
  12341. if (!s) return;
  12342. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12343. document.getElementById('dhcp-server-modal-id').value = s.id;
  12344. document.getElementById('dhcp-server-modal-name').value = s.name;
  12345. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12346. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12347. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12348. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12349. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12350. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12351. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12352. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12353. }
  12354. function closeDHCPServerModal() {
  12355. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12356. }
  12357. async function submitSaveDHCPServer(e) {
  12358. e.preventDefault();
  12359. const id = document.getElementById('dhcp-server-modal-id').value;
  12360. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12361. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12362. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12363. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12364. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12365. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12366. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12367. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12368. try {
  12369. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12370. method: 'POST',
  12371. headers: { 'Content-Type': 'application/json' },
  12372. body: JSON.stringify({
  12373. id,
  12374. name,
  12375. interface: iface,
  12376. network,
  12377. address_pool: pool,
  12378. lease_time: leaseTime,
  12379. authoritative,
  12380. disabled,
  12381. comment
  12382. })
  12383. });
  12384. if (res.ok) {
  12385. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12386. closeDHCPServerModal();
  12387. loadDHCPServer(false);
  12388. fetchData(false);
  12389. } else {
  12390. const err = await res.text();
  12391. showToast('Error', err, 'error');
  12392. }
  12393. } catch (err) {
  12394. showToast('Error', err.message, 'error');
  12395. }
  12396. }
  12397. async function toggleDHCPServerState(id, disabled) {
  12398. try {
  12399. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12400. method: 'POST',
  12401. headers: { 'Content-Type': 'application/json' },
  12402. body: JSON.stringify({ disabled })
  12403. });
  12404. if (res.ok) {
  12405. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12406. loadDHCPServer(false);
  12407. fetchData(false);
  12408. }
  12409. } catch (err) {
  12410. showToast('Error', err.message, 'error');
  12411. }
  12412. }
  12413. async function deleteDHCPServer(id, name) {
  12414. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12415. try {
  12416. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12417. if (res.ok) {
  12418. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12419. loadDHCPServer(false);
  12420. fetchData(false);
  12421. }
  12422. } catch (err) {
  12423. showToast('Error', err.message, 'error');
  12424. }
  12425. }
  12426. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12427. function openAddDHCPNetworkModal() {
  12428. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12429. document.getElementById('dhcp-network-modal-id').value = '';
  12430. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12431. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12432. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12433. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12434. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  12435. document.getElementById('dhcp-network-modal-tftp').value = '';
  12436. document.getElementById('dhcp-network-modal-bootfile').value = '';
  12437. document.getElementById('dhcp-network-modal-wins').value = '';
  12438. document.getElementById('dhcp-network-modal-netmask').value = '';
  12439. document.getElementById('dhcp-network-modal-comment').value = '';
  12440. renderDHCPNetworkOptionsCheckboxes([]);
  12441. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12442. }
  12443. function openEditDHCPNetworkModal(id) {
  12444. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12445. if (!n) return;
  12446. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12447. document.getElementById('dhcp-network-modal-id').value = n.id;
  12448. document.getElementById('dhcp-network-modal-address').value = n.address;
  12449. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12450. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12451. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12452. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  12453. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  12454. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  12455. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  12456. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12457. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12458. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12459. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12460. }
  12461. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12462. const container = document.getElementById('dhcp-network-modal-options-list');
  12463. if (!container) return;
  12464. container.innerHTML = '';
  12465. const opts = state.dhcpOptions || [];
  12466. if (opts.length === 0) {
  12467. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12468. return;
  12469. }
  12470. opts.forEach(o => {
  12471. const isChecked = selectedIds.includes(o.id);
  12472. const label = document.createElement('label');
  12473. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12474. label.innerHTML = `
  12475. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12476. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12477. `;
  12478. container.appendChild(label);
  12479. });
  12480. }
  12481. function closeDHCPNetworkModal() {
  12482. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12483. }
  12484. async function submitSaveDHCPNetwork(e) {
  12485. e.preventDefault();
  12486. const id = document.getElementById('dhcp-network-modal-id').value;
  12487. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12488. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12489. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12490. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12491. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  12492. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  12493. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  12494. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  12495. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12496. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12497. const selectedOpts = [];
  12498. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12499. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12500. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12501. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12502. try {
  12503. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12504. method: 'POST',
  12505. headers: { 'Content-Type': 'application/json' },
  12506. body: JSON.stringify({
  12507. id,
  12508. address,
  12509. gateway,
  12510. netmask,
  12511. dns_servers: dnsServers,
  12512. domain,
  12513. ntp_servers: ntpServers,
  12514. next_server: tftp,
  12515. boot_file_name: bootfile,
  12516. wins_servers: winsServers,
  12517. dhcp_options: selectedOpts,
  12518. comment
  12519. })
  12520. });
  12521. if (res.ok) {
  12522. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12523. closeDHCPNetworkModal();
  12524. loadDHCPServer(false);
  12525. fetchData(false);
  12526. } else {
  12527. const err = await res.text();
  12528. showToast('Error', err, 'error');
  12529. }
  12530. } catch (err) {
  12531. showToast('Error', err.message, 'error');
  12532. }
  12533. }
  12534. async function deleteDHCPNetwork(id, addr) {
  12535. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12536. try {
  12537. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12538. if (res.ok) {
  12539. showToast('Deleted', `Network ${addr} removed`, 'success');
  12540. loadDHCPServer(false);
  12541. fetchData(false);
  12542. }
  12543. } catch (err) {
  12544. showToast('Error', err.message, 'error');
  12545. }
  12546. }
  12547. // ==================== MODALS & ACTIONS: LEASES ====================
  12548. function openAddDHCPStaticLeaseModal() {
  12549. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12550. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12551. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12552. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12553. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12554. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12555. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12556. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12557. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12558. }
  12559. function closeDHCPStaticLeaseModal() {
  12560. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12561. }
  12562. async function submitSaveDHCPStaticLease(e) {
  12563. e.preventDefault();
  12564. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12565. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12566. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12567. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12568. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12569. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12570. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12571. try {
  12572. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12573. method: 'POST',
  12574. headers: { 'Content-Type': 'application/json' },
  12575. body: JSON.stringify({
  12576. id,
  12577. mac_address: mac,
  12578. address: ip,
  12579. hostname,
  12580. server,
  12581. comment,
  12582. disabled
  12583. })
  12584. });
  12585. if (res.ok) {
  12586. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12587. closeDHCPStaticLeaseModal();
  12588. loadDHCPServer(false);
  12589. fetchData(false);
  12590. } else {
  12591. const err = await res.text();
  12592. showToast('Error', err, 'error');
  12593. }
  12594. } catch (err) {
  12595. showToast('Error', err.message, 'error');
  12596. }
  12597. }
  12598. async function deleteDHCPStaticLease(id) {
  12599. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12600. try {
  12601. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12602. if (res.ok) {
  12603. showToast('Deleted', 'Static lease removed', 'success');
  12604. loadDHCPServer(false);
  12605. fetchData(false);
  12606. }
  12607. } catch (err) {
  12608. showToast('Error', err.message, 'error');
  12609. }
  12610. }
  12611. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12612. try {
  12613. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12614. method: 'POST',
  12615. headers: { 'Content-Type': 'application/json' },
  12616. body: JSON.stringify({
  12617. mac_address: mac,
  12618. address: ip,
  12619. hostname,
  12620. comment: comment || 'Converted to static'
  12621. })
  12622. });
  12623. if (res.ok) {
  12624. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12625. loadDHCPServer(false);
  12626. fetchData(false);
  12627. } else {
  12628. const err = await res.text();
  12629. showToast('Error', err, 'error');
  12630. }
  12631. } catch (err) {
  12632. showToast('Error', err.message, 'error');
  12633. }
  12634. }
  12635. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12636. function openAddDHCPOptionModal() {
  12637. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12638. document.getElementById('dhcp-option-modal-id').value = '';
  12639. document.getElementById('dhcp-option-modal-name').value = '';
  12640. document.getElementById('dhcp-option-modal-code').value = '';
  12641. document.getElementById('dhcp-option-modal-value').value = '';
  12642. document.getElementById('dhcp-option-modal-comment').value = '';
  12643. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12644. }
  12645. function openEditDHCPOptionModal(id) {
  12646. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12647. if (!o) return;
  12648. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12649. document.getElementById('dhcp-option-modal-id').value = o.id;
  12650. document.getElementById('dhcp-option-modal-name').value = o.name;
  12651. document.getElementById('dhcp-option-modal-code').value = o.code;
  12652. document.getElementById('dhcp-option-modal-value').value = o.value;
  12653. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12654. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12655. }
  12656. function closeDHCPOptionModal() {
  12657. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12658. }
  12659. async function submitSaveDHCPOption(e) {
  12660. e.preventDefault();
  12661. const id = document.getElementById('dhcp-option-modal-id').value;
  12662. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12663. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12664. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12665. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12666. try {
  12667. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12668. method: 'POST',
  12669. headers: { 'Content-Type': 'application/json' },
  12670. body: JSON.stringify({ id, name, code, value, comment })
  12671. });
  12672. if (res.ok) {
  12673. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12674. closeDHCPOptionModal();
  12675. loadDHCPServer(false);
  12676. fetchData(false);
  12677. } else {
  12678. const err = await res.text();
  12679. showToast('Error', err, 'error');
  12680. }
  12681. } catch (err) {
  12682. showToast('Error', err.message, 'error');
  12683. }
  12684. }
  12685. async function deleteDHCPOption(id, name) {
  12686. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12687. try {
  12688. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12689. if (res.ok) {
  12690. showToast('Deleted', `Option ${name} removed`, 'success');
  12691. loadDHCPServer(false);
  12692. fetchData(false);
  12693. }
  12694. } catch (err) {
  12695. showToast('Error', err.message, 'error');
  12696. }
  12697. }
  12698. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12699. function openDHCPServerSetupModal() {
  12700. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12701. onDHCPWizardIfaceChange();
  12702. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12703. }
  12704. function closeDHCPServerSetupModal() {
  12705. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12706. }
  12707. function onDHCPWizardIfaceChange() {
  12708. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12709. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12710. let ip = '192.168.88.1';
  12711. let prefix = '24';
  12712. if (iface && iface.ip_address) {
  12713. const parts = iface.ip_address.split('/');
  12714. ip = parts[0];
  12715. if (parts.length > 1) prefix = parts[1];
  12716. }
  12717. // Calculate subnet base (e.g. 192.168.88.0/24)
  12718. const ipParts = ip.split('.');
  12719. if (ipParts.length === 4) {
  12720. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12721. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12722. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12723. document.getElementById('dhcp-wizard-gateway').value = ip;
  12724. document.getElementById('dhcp-wizard-pool').value = pool;
  12725. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12726. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12727. }
  12728. }
  12729. async function submitDHCPServerSetupWizard(e) {
  12730. e.preventDefault();
  12731. const iface = document.getElementById('dhcp-wizard-iface').value;
  12732. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12733. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12734. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12735. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12736. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12737. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12738. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12739. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12740. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12741. try {
  12742. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12743. method: 'POST',
  12744. headers: { 'Content-Type': 'application/json' },
  12745. body: JSON.stringify({
  12746. interface: iface,
  12747. address_space: space,
  12748. gateway: gw,
  12749. address_pool: pool,
  12750. dns_servers: dnsServers,
  12751. lease_time: leaseTime,
  12752. ntp_servers: ntpServers,
  12753. next_server: tftp
  12754. })
  12755. });
  12756. if (res.ok) {
  12757. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12758. closeDHCPServerSetupModal();
  12759. loadDHCPServer(false);
  12760. fetchData(false);
  12761. } else {
  12762. const err = await res.text();
  12763. showToast('Error', err, 'error');
  12764. }
  12765. } catch (err) {
  12766. showToast('Error', err.message, 'error');
  12767. }
  12768. }
  12769. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12770. const sel = document.getElementById(elemId);
  12771. if (!sel) return;
  12772. sel.innerHTML = '<option value="">Select interface...</option>';
  12773. const ifaces = state.interfaces || [];
  12774. ifaces.forEach(i => {
  12775. if (i.name === 'lo') return;
  12776. const opt = document.createElement('option');
  12777. opt.value = i.name;
  12778. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12779. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12780. if (i.name === selectedVal) opt.selected = true;
  12781. sel.appendChild(opt);
  12782. });
  12783. }
  12784. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12785. function initTableSorting() {
  12786. document.querySelectorAll('table').forEach(setupSortableTable);
  12787. }
  12788. function setupSortableTable(table) {
  12789. const thead = table.querySelector('thead');
  12790. const tbody = table.querySelector('tbody');
  12791. if (!thead || !tbody) return;
  12792. const headerRows = thead.querySelectorAll('tr');
  12793. if (headerRows.length === 0) return;
  12794. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12795. ths.forEach((th, colIdx) => {
  12796. if (th._sortBound) return;
  12797. th._sortBound = true;
  12798. const rawText = th.innerText.trim().toLowerCase();
  12799. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12800. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12801. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12802. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12803. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12804. return;
  12805. }
  12806. th.classList.add('table-sortable', 'group');
  12807. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12808. let icon = th.querySelector('.table-sort-icon');
  12809. if (!icon) {
  12810. icon = document.createElement('span');
  12811. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12812. icon.innerHTML = '⇅';
  12813. th.appendChild(icon);
  12814. }
  12815. th.addEventListener('click', (e) => {
  12816. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12817. handleHeaderClick(table, th, colIdx);
  12818. });
  12819. });
  12820. if (!tbody._sortObserved) {
  12821. tbody._sortObserved = true;
  12822. let sortDebounceTimer = null;
  12823. const observer = new MutationObserver((mutations) => {
  12824. if (tbody._isSorting) return;
  12825. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12826. if (!hasChildChanges) return;
  12827. clearTimeout(sortDebounceTimer);
  12828. sortDebounceTimer = setTimeout(() => {
  12829. if (tbody._isSorting) return;
  12830. if (table._activeSort && table._activeSort.dir !== 'none') {
  12831. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12832. } else {
  12833. tagOriginalRowOrder(tbody);
  12834. }
  12835. }, 10);
  12836. });
  12837. observer.observe(tbody, { childList: true });
  12838. }
  12839. tagOriginalRowOrder(tbody);
  12840. }
  12841. function tagOriginalRowOrder(tbody) {
  12842. let idx = 0;
  12843. Array.from(tbody.children).forEach(tr => {
  12844. if (!tr.querySelector('td[colspan]')) {
  12845. if (!tr.hasAttribute('data-orig-idx')) {
  12846. tr.setAttribute('data-orig-idx', idx++);
  12847. }
  12848. }
  12849. });
  12850. }
  12851. function handleHeaderClick(table, th, colIdx) {
  12852. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12853. let newDir = 'asc';
  12854. if (currentSort.colIdx === colIdx) {
  12855. if (currentSort.dir === 'asc') newDir = 'desc';
  12856. else if (currentSort.dir === 'desc') newDir = 'none';
  12857. else newDir = 'asc';
  12858. } else {
  12859. newDir = 'asc';
  12860. }
  12861. table._activeSort = { colIdx, dir: newDir };
  12862. updateHeaderIcons(table, colIdx, newDir);
  12863. applyTableSort(table, colIdx, newDir, true);
  12864. }
  12865. function updateHeaderIcons(table, activeColIdx, dir) {
  12866. const thead = table.querySelector('thead');
  12867. if (!thead) return;
  12868. const ths = thead.querySelectorAll('th');
  12869. ths.forEach((th, idx) => {
  12870. const icon = th.querySelector('.table-sort-icon');
  12871. if (!icon) return;
  12872. if (idx === activeColIdx && dir !== 'none') {
  12873. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12874. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12875. th.classList.add('table-sorted-active');
  12876. } else {
  12877. icon.innerHTML = '⇅';
  12878. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12879. th.classList.remove('table-sorted-active');
  12880. }
  12881. });
  12882. }
  12883. function applyTableSort(table, colIdx, dir, userInitiated) {
  12884. const tbody = table.querySelector('tbody');
  12885. if (!tbody || tbody.children.length <= 1) return;
  12886. tbody._isSorting = true;
  12887. tagOriginalRowOrder(tbody);
  12888. // Group parent rows and any attached drawer/sub-rows
  12889. const groups = [];
  12890. let currentGroup = null;
  12891. Array.from(tbody.children).forEach(tr => {
  12892. if (tr.querySelector('td[colspan]')) {
  12893. if (currentGroup) {
  12894. currentGroup.subRows.push(tr);
  12895. } else {
  12896. groups.push({ mainRow: tr, subRows: [] });
  12897. }
  12898. } else {
  12899. currentGroup = { mainRow: tr, subRows: [] };
  12900. groups.push(currentGroup);
  12901. }
  12902. });
  12903. if (dir === 'none') {
  12904. groups.sort((a, b) => {
  12905. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12906. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12907. return idxA - idxB;
  12908. });
  12909. } else {
  12910. groups.sort((a, b) => {
  12911. const cellA = a.mainRow.children[colIdx];
  12912. const cellB = b.mainRow.children[colIdx];
  12913. const res = compareTableCells(cellA, cellB);
  12914. return dir === 'asc' ? res : -res;
  12915. });
  12916. }
  12917. // Re-append rows in sorted order
  12918. groups.forEach(g => {
  12919. tbody.appendChild(g.mainRow);
  12920. g.subRows.forEach(sub => tbody.appendChild(sub));
  12921. });
  12922. tbody._isSorting = false;
  12923. }
  12924. function getCellRawText(cell) {
  12925. if (!cell) return '';
  12926. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12927. const input = cell.querySelector('input, select');
  12928. if (input) {
  12929. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12930. return input.value;
  12931. }
  12932. return cell.innerText.trim();
  12933. }
  12934. function parseTrafficToNumber(str) {
  12935. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12936. if (!m) return null;
  12937. const num = parseFloat(m[1].replace(/,/g, ''));
  12938. if (isNaN(num)) return null;
  12939. const unit = m[2].toUpperCase();
  12940. let mult = 1;
  12941. if (unit.startsWith('K')) mult = 1024;
  12942. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12943. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12944. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12945. return num * mult;
  12946. }
  12947. function parseIpToNumber(str) {
  12948. const clean = str.replace(/^[!~]/, '').trim();
  12949. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12950. if (!m) return null;
  12951. const o1 = parseInt(m[1], 10);
  12952. const o2 = parseInt(m[2], 10);
  12953. const o3 = parseInt(m[3], 10);
  12954. const o4 = parseInt(m[4], 10);
  12955. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12956. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12957. }
  12958. function parseCompoundPackets(str) {
  12959. const m = str.match(/^([\d,]+)p/);
  12960. if (!m) return null;
  12961. return parseInt(m[1].replace(/,/g, ''), 10);
  12962. }
  12963. function compareTableCells(cellA, cellB) {
  12964. const a = getCellRawText(cellA);
  12965. const b = getCellRawText(cellB);
  12966. if (a === '' && b !== '') return 1;
  12967. if (b === '' && a !== '') return -1;
  12968. if (a === b) return 0;
  12969. // 1. IP Addresses / CIDR
  12970. const ipA = parseIpToNumber(a);
  12971. const ipB = parseIpToNumber(b);
  12972. if (ipA !== null && ipB !== null) return ipA - ipB;
  12973. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12974. const pktA = parseCompoundPackets(a);
  12975. const pktB = parseCompoundPackets(b);
  12976. if (pktA !== null && pktB !== null) return pktA - pktB;
  12977. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12978. const trafA = parseTrafficToNumber(a);
  12979. const trafB = parseTrafficToNumber(b);
  12980. if (trafA !== null && trafB !== null) return trafA - trafB;
  12981. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12982. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12983. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12984. const numA = Number(cleanNumA);
  12985. const numB = Number(cleanNumB);
  12986. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12987. return numA - numB;
  12988. }
  12989. // 5. Natural case-insensitive string compare
  12990. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12991. }
  12992. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  12993. async function loadVRRP(showToastNotification = false) {
  12994. try {
  12995. const [instRes, sumRes] = await Promise.all([
  12996. fetch(`${API_BASE}/vrrp/instances`),
  12997. fetch(`${API_BASE}/vrrp/summary`)
  12998. ]);
  12999. if (instRes.ok) {
  13000. state.vrrpInstances = await instRes.json();
  13001. renderVRRP();
  13002. }
  13003. if (sumRes.ok) {
  13004. state.vrrpSummary = await sumRes.json();
  13005. renderVRRPSummary();
  13006. }
  13007. if (showToastNotification) {
  13008. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13009. }
  13010. } catch (err) {
  13011. console.error('Failed to load VRRP:', err);
  13012. }
  13013. }
  13014. function renderVRRPSummary() {
  13015. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13016. const elTotal = document.getElementById('vrrp-stat-total');
  13017. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13018. const elMaster = document.getElementById('vrrp-stat-master');
  13019. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13020. const elBackup = document.getElementById('vrrp-stat-backup');
  13021. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13022. const bCount = document.getElementById('badge-vrrp-count');
  13023. if (bCount) bCount.innerText = s.total_instances || 0;
  13024. const dot = document.getElementById('badge-vrrp-dot');
  13025. if (dot) {
  13026. if (s.master_instances > 0) {
  13027. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13028. } else if (s.backup_instances > 0) {
  13029. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13030. } else {
  13031. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13032. }
  13033. }
  13034. }
  13035. function renderVRRP() {
  13036. const tbody = document.getElementById('vrrp-table-tbody');
  13037. const empty = document.getElementById('vrrp-table-empty');
  13038. if (!tbody) return;
  13039. tbody.innerHTML = '';
  13040. const instances = state.vrrpInstances || [];
  13041. if (instances.length === 0) {
  13042. empty?.classList.remove('hidden');
  13043. return;
  13044. }
  13045. empty?.classList.add('hidden');
  13046. instances.forEach(inst => {
  13047. const tr = document.createElement('tr');
  13048. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13049. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13050. let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
  13051. if (inst.disabled) {
  13052. flagHtml = `<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>`;
  13053. } else if (inst.state === 'MASTER') {
  13054. flagHtml = `<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="Master (Holding VIP)">M</span>`;
  13055. } else if (inst.state === 'BACKUP') {
  13056. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
  13057. } else if (inst.state === 'FAULT') {
  13058. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
  13059. }
  13060. // Render State Badge
  13061. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13062. if (!inst.disabled) {
  13063. if (inst.state === 'MASTER') {
  13064. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
  13065. } else if (inst.state === 'BACKUP') {
  13066. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
  13067. } else if (inst.state === 'FAULT') {
  13068. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
  13069. }
  13070. }
  13071. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13072. tr.innerHTML = `
  13073. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13074. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13075. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13076. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13077. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13078. <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
  13079. <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  13080. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13081. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13082. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13083. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13084. <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
  13085. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13086. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13087. </td>
  13088. `;
  13089. tbody.appendChild(tr);
  13090. });
  13091. }
  13092. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13093. const sel = document.getElementById(elemId);
  13094. if (!sel) return;
  13095. sel.innerHTML = '<option value="">Select interface...</option>';
  13096. const ifaces = state.interfaces || [];
  13097. ifaces.forEach(i => {
  13098. const opt = document.createElement('option');
  13099. opt.value = i.name;
  13100. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13101. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13102. sel.appendChild(opt);
  13103. });
  13104. }
  13105. function openAddVRRPModal() {
  13106. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13107. document.getElementById('modal-vrrp-id').value = '';
  13108. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13109. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13110. document.getElementById('modal-vrrp-priority').value = 100;
  13111. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13112. document.getElementById('modal-vrrp-version').value = '3';
  13113. document.getElementById('modal-vrrp-interval').value = 1;
  13114. document.getElementById('modal-vrrp-authtype').value = 'none';
  13115. document.getElementById('modal-vrrp-authpass').value = '';
  13116. document.getElementById('modal-vrrp-comment').value = '';
  13117. document.getElementById('modal-vrrp-preempt').checked = true;
  13118. document.getElementById('modal-vrrp-disabled').checked = false;
  13119. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13120. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13121. }
  13122. function openEditVRRPModal(id) {
  13123. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13124. if (!inst) return;
  13125. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13126. document.getElementById('modal-vrrp-id').value = inst.id;
  13127. document.getElementById('modal-vrrp-name').value = inst.name;
  13128. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13129. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13130. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13131. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13132. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13133. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13134. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13135. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13136. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13137. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13138. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13139. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13140. }
  13141. function closeVRRPModal() {
  13142. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13143. }
  13144. async function submitSaveVRRP(e) {
  13145. e.preventDefault();
  13146. const id = document.getElementById('modal-vrrp-id').value;
  13147. const name = document.getElementById('modal-vrrp-name').value.trim();
  13148. const iface = document.getElementById('modal-vrrp-iface').value;
  13149. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13150. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13151. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13152. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13153. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13154. const authType = document.getElementById('modal-vrrp-authtype').value;
  13155. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13156. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13157. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13158. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13159. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13160. try {
  13161. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13162. method: 'POST',
  13163. headers: { 'Content-Type': 'application/json' },
  13164. body: JSON.stringify({
  13165. id,
  13166. name,
  13167. interface: iface,
  13168. vrid,
  13169. priority,
  13170. virtual_ips: vips,
  13171. version,
  13172. interval,
  13173. auth_type: authType,
  13174. auth_password: authPass,
  13175. comment,
  13176. preempt,
  13177. disabled
  13178. })
  13179. });
  13180. if (res.ok) {
  13181. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13182. closeVRRPModal();
  13183. loadVRRP(false);
  13184. fetchData(false);
  13185. } else {
  13186. const err = await res.text();
  13187. showToast('Error', err, 'error');
  13188. }
  13189. } catch (err) {
  13190. showToast('Error', err.message, 'error');
  13191. }
  13192. }
  13193. async function deleteVRRP(id, name) {
  13194. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13195. try {
  13196. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13197. if (res.ok) {
  13198. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13199. loadVRRP(false);
  13200. fetchData(false);
  13201. } else {
  13202. const err = await res.text();
  13203. showToast('Error', err, 'error');
  13204. }
  13205. } catch (err) {
  13206. showToast('Error', err.message, 'error');
  13207. }
  13208. }
  13209. async function toggleVRRPState(id, disabled) {
  13210. try {
  13211. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13212. method: 'POST',
  13213. headers: { 'Content-Type': 'application/json' },
  13214. body: JSON.stringify({ disabled })
  13215. });
  13216. if (res.ok) {
  13217. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13218. loadVRRP(false);
  13219. fetchData(false);
  13220. } else {
  13221. const err = await res.text();
  13222. showToast('Error', err, 'error');
  13223. }
  13224. } catch (err) {
  13225. showToast('Error', err.message, 'error');
  13226. }
  13227. }
  13228. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13229. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13230. const docTableObserver = new MutationObserver((mutations) => {
  13231. let needsInit = false;
  13232. for (const m of mutations) {
  13233. for (const node of m.addedNodes) {
  13234. if (node.nodeType === 1) {
  13235. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  13236. needsInit = true;
  13237. break;
  13238. }
  13239. }
  13240. }
  13241. if (needsInit) break;
  13242. }
  13243. if (needsInit) {
  13244. initTableSorting();
  13245. }
  13246. });
  13247. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13248. }
  13249. // =========================================================================
  13250. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13251. // =========================================================================
  13252. const bwtestState = {
  13253. running: false,
  13254. pollTimer: null,
  13255. eventSource: null,
  13256. chartPoints: [],
  13257. maxChartPoints: 60,
  13258. serverConfig: null,
  13259. peakTx: 0,
  13260. peakRx: 0,
  13261. targetDuration: 10,
  13262. lastSampleIndex: 0
  13263. };
  13264. async function loadBwTestView() {
  13265. fetchBwTestServerStatus();
  13266. loadBwTestHistory();
  13267. resizeBwTestCanvas();
  13268. checkActiveBwTest();
  13269. }
  13270. async function fetchBwTestServerStatus() {
  13271. try {
  13272. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13273. if (!res.ok) return;
  13274. const s = await res.json();
  13275. bwtestState.serverConfig = s;
  13276. // Update indicator and badges
  13277. const indicator = document.getElementById('bwtest-server-indicator');
  13278. const badge = document.getElementById('bwtest-server-badge');
  13279. const sideBadge = document.getElementById('badge-bwtest-server');
  13280. if (s.enabled && s.running) {
  13281. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13282. if (badge) {
  13283. badge.innerText = `Port ${s.port} (Active)`;
  13284. badge.className = 'text-emerald-400 font-bold';
  13285. }
  13286. if (sideBadge) {
  13287. sideBadge.innerText = s.port;
  13288. sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
  13289. }
  13290. } else {
  13291. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13292. if (badge) {
  13293. badge.innerText = `Disabled`;
  13294. badge.className = 'text-slate-500 font-bold';
  13295. }
  13296. if (sideBadge) {
  13297. sideBadge.innerText = 'Off';
  13298. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13299. }
  13300. }
  13301. // Modal fields
  13302. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13303. if (toggle) toggle.checked = !!s.enabled;
  13304. const portInp = document.getElementById('bwtest-server-port-input');
  13305. if (portInp) portInp.value = s.port || 2000;
  13306. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13307. if (actSess) actSess.innerText = s.active_sessions || 0;
  13308. const totServ = document.getElementById('bwtest-modal-total-served');
  13309. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13310. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13311. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13312. } catch (err) {
  13313. console.error('Failed to fetch BwTest server status:', err);
  13314. }
  13315. }
  13316. function openBwTestServerModal() {
  13317. fetchBwTestServerStatus();
  13318. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13319. }
  13320. function closeBwTestServerModal() {
  13321. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13322. }
  13323. async function submitBwTestServerSettings(e) {
  13324. e.preventDefault();
  13325. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13326. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13327. try {
  13328. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13329. method: 'POST',
  13330. headers: { 'Content-Type': 'application/json' },
  13331. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13332. });
  13333. if (!res.ok) {
  13334. const err = await res.json();
  13335. throw new Error(err.error || 'Failed to update server configuration');
  13336. }
  13337. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13338. closeBwTestServerModal();
  13339. fetchBwTestServerStatus();
  13340. } catch (err) {
  13341. showToast('Server Configuration Error', err.message, 'error');
  13342. }
  13343. }
  13344. function setBwTestTarget(target) {
  13345. const inp = document.getElementById('bwtest-input-target');
  13346. if (inp) inp.value = target;
  13347. }
  13348. function setBwTestProtocol(proto) {
  13349. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13350. if (hiddenInp) hiddenInp.value = proto;
  13351. const btnUdp = document.getElementById('bwtest-proto-udp');
  13352. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13353. const badge = document.getElementById('bwtest-proto-badge');
  13354. const pktField = document.getElementById('bwtest-field-pktsize');
  13355. const activeUdpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm flex items-center justify-center gap-2';
  13356. const activeTcpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-blue-600/20 border-blue-500/50 text-blue-300 shadow-sm flex items-center justify-center gap-2';
  13357. const inactiveCls = 'py-2.5 px-3 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center flex items-center justify-center gap-2';
  13358. if (proto === 'udp') {
  13359. if (btnUdp) {
  13360. btnUdp.className = activeUdpCls;
  13361. const dot = btnUdp.querySelector('span');
  13362. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13363. }
  13364. if (btnTcp) {
  13365. btnTcp.className = inactiveCls;
  13366. const dot = btnTcp.querySelector('span');
  13367. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13368. }
  13369. if (badge) {
  13370. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13371. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13372. }
  13373. if (pktField) pktField.classList.remove('opacity-40');
  13374. } else {
  13375. if (btnUdp) {
  13376. btnUdp.className = inactiveCls;
  13377. const dot = btnUdp.querySelector('span');
  13378. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13379. }
  13380. if (btnTcp) {
  13381. btnTcp.className = activeTcpCls;
  13382. const dot = btnTcp.querySelector('span');
  13383. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13384. }
  13385. if (badge) {
  13386. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13387. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13388. }
  13389. if (pktField) pktField.classList.add('opacity-40');
  13390. }
  13391. }
  13392. function setBwTestDirection(dir) {
  13393. const hiddenInp = document.getElementById('bwtest-input-direction');
  13394. if (hiddenInp) hiddenInp.value = dir;
  13395. const btnBoth = document.getElementById('bwtest-dir-both');
  13396. const btnTx = document.getElementById('bwtest-dir-tx');
  13397. const btnRx = document.getElementById('bwtest-dir-rx');
  13398. const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
  13399. const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
  13400. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13401. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13402. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13403. }
  13404. function setBwTestLimit(bps) {
  13405. const sel = document.getElementById('bwtest-input-limit');
  13406. if (sel) sel.value = String(bps);
  13407. }
  13408. async function checkActiveBwTest() {
  13409. try {
  13410. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13411. if (!res.ok) return;
  13412. const st = await res.json();
  13413. if (st.running) {
  13414. setBwTestRunningUI(true);
  13415. if (st.current_sample) handleBwTestSample(st.current_sample);
  13416. startBwTestTelemetry();
  13417. }
  13418. } catch (err) {
  13419. console.error('Failed to check active BwTest:', err);
  13420. }
  13421. }
  13422. async function startBwTest(e) {
  13423. if (e && e.preventDefault) e.preventDefault();
  13424. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13425. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13426. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13427. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13428. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13429. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13430. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13431. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13432. bwtestState.targetDuration = duration;
  13433. bwtestState.chartPoints = [];
  13434. bwtestState.peakTx = 0;
  13435. bwtestState.peakRx = 0;
  13436. bwtestState.lastSampleIndex = 0;
  13437. // Clear UI elements
  13438. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13439. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13440. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13441. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13442. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13443. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13444. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13445. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13446. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13447. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13448. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13449. const tbody = document.getElementById('bwtest-samples-tbody');
  13450. if (tbody) tbody.innerHTML = '';
  13451. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13452. setBwTestRunningUI(true);
  13453. try {
  13454. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13455. method: 'POST',
  13456. headers: { 'Content-Type': 'application/json' },
  13457. body: JSON.stringify({
  13458. target,
  13459. port,
  13460. direction,
  13461. protocol,
  13462. bandwidth_limit,
  13463. packet_size,
  13464. streams,
  13465. duration
  13466. })
  13467. });
  13468. if (!res.ok) {
  13469. const err = await res.json();
  13470. throw new Error(err.error || 'Failed to start bandwidth test');
  13471. }
  13472. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13473. startBwTestTelemetry();
  13474. } catch (err) {
  13475. setBwTestRunningUI(false);
  13476. showToast('Start Failed', err.message, 'error');
  13477. }
  13478. }
  13479. function setBwTestRunningUI(running) {
  13480. bwtestState.running = running;
  13481. const startBtn = document.getElementById('bwtest-btn-start');
  13482. const stopBtn = document.getElementById('bwtest-btn-stop');
  13483. const badge = document.getElementById('bwtest-run-status-badge');
  13484. const ph = document.getElementById('bwtest-chart-placeholder');
  13485. if (running) {
  13486. if (startBtn) {
  13487. startBtn.disabled = true;
  13488. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13489. }
  13490. if (stopBtn) {
  13491. stopBtn.disabled = false;
  13492. stopBtn.classList.remove('opacity-40');
  13493. }
  13494. if (badge) {
  13495. badge.innerText = 'TESTING...';
  13496. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
  13497. }
  13498. if (ph) ph.style.display = 'none';
  13499. } else {
  13500. if (startBtn) {
  13501. startBtn.disabled = false;
  13502. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13503. }
  13504. if (stopBtn) {
  13505. stopBtn.disabled = true;
  13506. stopBtn.classList.add('opacity-40');
  13507. }
  13508. if (badge) {
  13509. badge.innerText = 'IDLE';
  13510. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13511. }
  13512. }
  13513. }
  13514. async function stopBwTest() {
  13515. try {
  13516. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13517. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13518. } catch (err) {
  13519. console.error('Failed to stop test:', err);
  13520. }
  13521. }
  13522. function startBwTestTelemetry() {
  13523. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13524. bwtestState.pollTimer = setInterval(async () => {
  13525. try {
  13526. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13527. if (!res.ok) return;
  13528. const st = await res.json();
  13529. if (st.recent_samples && st.recent_samples.length > 0) {
  13530. // Process new samples
  13531. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13532. newSamples.forEach(s => handleBwTestSample(s));
  13533. bwtestState.lastSampleIndex = st.recent_samples.length;
  13534. }
  13535. if (!st.running) {
  13536. clearInterval(bwtestState.pollTimer);
  13537. bwtestState.pollTimer = null;
  13538. setBwTestRunningUI(false);
  13539. handleBwTestFinish(st.summary, st.error);
  13540. }
  13541. } catch (err) {
  13542. console.error('BwTest polling error:', err);
  13543. }
  13544. }, 400);
  13545. }
  13546. function handleBwTestSample(s) {
  13547. if (!s) return;
  13548. const txMbps = s.tx_mbps || 0;
  13549. const rxMbps = s.rx_mbps || 0;
  13550. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13551. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13552. // KPI updates
  13553. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13554. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13555. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13556. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13557. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13558. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13559. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13560. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13561. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13562. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13563. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13564. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13565. const elLoss = document.getElementById('bwtest-stat-loss');
  13566. if (elLoss) {
  13567. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13568. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13569. }
  13570. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13571. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13572. const elJitter = document.getElementById('bwtest-stat-jitter');
  13573. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13574. const elTime = document.getElementById('bwtest-stat-time');
  13575. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13576. const elData = document.getElementById('bwtest-stat-data');
  13577. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13578. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13579. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13580. // Append point to chart buffer
  13581. bwtestState.chartPoints.push({
  13582. elapsed: s.elapsed_sec || 0,
  13583. tx: txMbps,
  13584. rx: rxMbps
  13585. });
  13586. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13587. bwtestState.chartPoints.shift();
  13588. }
  13589. drawBwTestChart();
  13590. // Add row to breakdown table
  13591. const tbody = document.getElementById('bwtest-samples-tbody');
  13592. if (tbody) {
  13593. const tr = document.createElement('tr');
  13594. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13595. tr.innerHTML = `
  13596. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13597. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13598. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13599. <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
  13600. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13601. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13602. `;
  13603. tbody.insertBefore(tr, tbody.firstChild);
  13604. const countEl = document.getElementById('bwtest-sample-count');
  13605. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13606. }
  13607. }
  13608. function handleBwTestFinish(summary, error) {
  13609. const badge = document.getElementById('bwtest-run-status-badge');
  13610. if (error) {
  13611. showToast('Benchmark Error', error, 'error');
  13612. if (badge) {
  13613. badge.innerText = 'ERROR';
  13614. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
  13615. }
  13616. } else if (summary) {
  13617. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13618. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13619. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13620. if (badge) {
  13621. badge.innerText = 'COMPLETED';
  13622. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
  13623. }
  13624. }
  13625. loadBwTestHistory();
  13626. fetchBwTestServerStatus();
  13627. }
  13628. function resizeBwTestCanvas() {
  13629. const canvas = document.getElementById('bwtest-chart');
  13630. if (!canvas || !canvas.parentElement) return;
  13631. const rect = canvas.parentElement.getBoundingClientRect();
  13632. const dpr = window.devicePixelRatio || 1;
  13633. canvas.width = rect.width * dpr;
  13634. canvas.height = rect.height * dpr;
  13635. const ctx = canvas.getContext('2d');
  13636. ctx.scale(dpr, dpr);
  13637. drawBwTestChart();
  13638. }
  13639. window.addEventListener('resize', () => {
  13640. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13641. });
  13642. function drawBwTestChart() {
  13643. const canvas = document.getElementById('bwtest-chart');
  13644. if (!canvas) return;
  13645. const ctx = canvas.getContext('2d');
  13646. const dpr = window.devicePixelRatio || 1;
  13647. const width = canvas.width / dpr;
  13648. const height = canvas.height / dpr;
  13649. ctx.clearRect(0, 0, width, height);
  13650. const points = bwtestState.chartPoints;
  13651. if (!points || points.length === 0) return;
  13652. // Determine scale ceiling
  13653. let maxRate = 10;
  13654. for (const p of points) {
  13655. if (p.tx > maxRate) maxRate = p.tx;
  13656. if (p.rx > maxRate) maxRate = p.rx;
  13657. }
  13658. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13659. const paddingLeft = 55;
  13660. const paddingBottom = 24;
  13661. const paddingTop = 12;
  13662. const paddingRight = 16;
  13663. const chartW = width - paddingLeft - paddingRight;
  13664. const chartH = height - paddingTop - paddingBottom;
  13665. // Grid Lines and Y-Axis labels
  13666. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13667. ctx.lineWidth = 1;
  13668. ctx.fillStyle = '#94a3b8';
  13669. ctx.font = '10px monospace';
  13670. ctx.textAlign = 'right';
  13671. const gridSteps = 4;
  13672. for (let i = 0; i <= gridSteps; i++) {
  13673. const val = (maxRate / gridSteps) * i;
  13674. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13675. ctx.beginPath();
  13676. ctx.moveTo(paddingLeft, y);
  13677. ctx.lineTo(width - paddingRight, y);
  13678. ctx.stroke();
  13679. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13680. }
  13681. // Draw TX Line (Cyan #22d3ee)
  13682. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13683. // Draw RX Line (Purple #a855f7)
  13684. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13685. }
  13686. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13687. if (points.length < 2) return;
  13688. const stepX = w / Math.max(points.length - 1, 1);
  13689. // Gradient area fill
  13690. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13691. grad.addColorStop(0, fillColor);
  13692. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13693. ctx.beginPath();
  13694. points.forEach((p, idx) => {
  13695. const x = left + idx * stepX;
  13696. const val = valFn(p);
  13697. const y = top + h - (val / maxVal) * h;
  13698. if (idx === 0) {
  13699. ctx.moveTo(x, y);
  13700. } else {
  13701. ctx.lineTo(x, y);
  13702. }
  13703. });
  13704. // Complete path for fill
  13705. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13706. ctx.lineTo(left, top + h);
  13707. ctx.closePath();
  13708. ctx.fillStyle = grad;
  13709. ctx.fill();
  13710. // Draw line stroke
  13711. ctx.beginPath();
  13712. ctx.lineWidth = 2.5;
  13713. ctx.strokeStyle = strokeColor;
  13714. points.forEach((p, idx) => {
  13715. const x = left + idx * stepX;
  13716. const val = valFn(p);
  13717. const y = top + h - (val / maxVal) * h;
  13718. if (idx === 0) {
  13719. ctx.moveTo(x, y);
  13720. } else {
  13721. ctx.lineTo(x, y);
  13722. }
  13723. });
  13724. ctx.stroke();
  13725. // Draw end point halo
  13726. const lastP = points[points.length - 1];
  13727. const lastX = left + (points.length - 1) * stepX;
  13728. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13729. ctx.fillStyle = strokeColor;
  13730. ctx.beginPath();
  13731. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13732. ctx.fill();
  13733. }
  13734. async function loadBwTestHistory() {
  13735. try {
  13736. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13737. if (!res.ok) return;
  13738. const list = await res.json();
  13739. renderBwTestHistory(Array.isArray(list) ? list : []);
  13740. } catch (err) {
  13741. console.error('Failed to load BwTest history:', err);
  13742. }
  13743. }
  13744. function renderBwTestHistory(list) {
  13745. const tbody = document.getElementById('bwtest-history-tbody');
  13746. if (!tbody) return;
  13747. if (list.length === 0) {
  13748. tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
  13749. return;
  13750. }
  13751. tbody.innerHTML = '';
  13752. list.forEach(item => {
  13753. const s = item.summary || {};
  13754. const tr = document.createElement('tr');
  13755. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13756. const dirBadge = item.direction === 'both'
  13757. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
  13758. : item.direction === 'tx'
  13759. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
  13760. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
  13761. const protoBadge = item.protocol === 'tcp'
  13762. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
  13763. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
  13764. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13765. tr.innerHTML = `
  13766. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13767. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13768. <td class="py-2.5 px-4">${protoBadge}</td>
  13769. <td class="py-2.5 px-4">${dirBadge}</td>
  13770. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13771. <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13772. <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13773. <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
  13774. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13775. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13776. `;
  13777. tbody.appendChild(tr);
  13778. });
  13779. }
  13780. // ======================== SETTINGS & ROUTER DNS ========================
  13781. state.settingsSubTab = 'dns';
  13782. state.dnsSettings = null;
  13783. state.dnsStaticRecords = [];
  13784. state.dnsStatus = null;
  13785. function switchSettingsSubTab(sub) {
  13786. state.settingsSubTab = sub;
  13787. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13788. const btnSys = document.getElementById('btn-settings-subtab-system');
  13789. const tabDns = document.getElementById('settings-subtab-dns');
  13790. const tabSys = document.getElementById('settings-subtab-system');
  13791. if (sub === 'dns') {
  13792. if (btnDns) {
  13793. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13794. }
  13795. if (btnSys) {
  13796. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13797. }
  13798. tabDns?.classList.remove('hidden');
  13799. tabSys?.classList.add('hidden');
  13800. loadDNSSettings();
  13801. } else {
  13802. if (btnSys) {
  13803. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13804. }
  13805. if (btnDns) {
  13806. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13807. }
  13808. tabSys?.classList.remove('hidden');
  13809. tabDns?.classList.add('hidden');
  13810. loadSystemSettings();
  13811. }
  13812. }
  13813. async function loadSettingsData(showLoading = false) {
  13814. if (state.settingsSubTab === 'system') {
  13815. await loadSystemSettings();
  13816. } else {
  13817. await loadDNSSettings();
  13818. }
  13819. }
  13820. async function loadDNSSettings() {
  13821. try {
  13822. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13823. fetch(`${API_BASE}/dns/settings`),
  13824. fetch(`${API_BASE}/dns/static`),
  13825. fetch(`${API_BASE}/dns/status`)
  13826. ]);
  13827. if (settingsRes.ok) {
  13828. state.dnsSettings = await settingsRes.json();
  13829. populateDNSSettingsForm(state.dnsSettings);
  13830. }
  13831. if (staticRes.ok) {
  13832. state.dnsStaticRecords = await staticRes.json();
  13833. renderStaticDNSList();
  13834. }
  13835. if (statusRes.ok) {
  13836. state.dnsStatus = await statusRes.json();
  13837. updateDNSStatusView(state.dnsStatus);
  13838. }
  13839. } catch (err) {
  13840. console.error('Failed to load DNS settings:', err);
  13841. }
  13842. }
  13843. function populateDNSSettingsForm(s) {
  13844. if (!s) return;
  13845. const dnsForm = document.getElementById('form-dns-settings');
  13846. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13847. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13848. if (dynamicEl) {
  13849. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13850. dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
  13851. } else {
  13852. dynamicEl.innerText = 'None';
  13853. }
  13854. }
  13855. // If user is actively typing or editing in the form, do not overwrite their inputs!
  13856. if (isEditing) return;
  13857. const serversInput = document.getElementById('dns-servers-input');
  13858. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  13859. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  13860. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  13861. const domainInput = document.getElementById('dns-domain-input');
  13862. if (domainInput) domainInput.value = s.domain || '';
  13863. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  13864. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  13865. }
  13866. function updateDNSStatusView(st) {
  13867. if (!st) return;
  13868. const preview = document.getElementById('dns-resolv-preview');
  13869. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  13870. const pillText = document.getElementById('dns-live-status-text');
  13871. const pill = document.getElementById('dns-live-status-pill');
  13872. if (pill && pillText) {
  13873. if (st.service_running) {
  13874. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
  13875. pillText.innerText = 'DNS Service Active';
  13876. } else {
  13877. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
  13878. pillText.innerText = 'DNS Service Inactive';
  13879. }
  13880. }
  13881. }
  13882. function appendDNSPreset(preset) {
  13883. const input = document.getElementById('dns-servers-input');
  13884. if (!input) return;
  13885. const dnsForm = document.getElementById('form-dns-settings');
  13886. if (dnsForm) dnsForm.dataset.dirty = 'true';
  13887. const current = input.value.trim();
  13888. if (!current) {
  13889. input.value = preset;
  13890. } else {
  13891. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13892. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13893. toAdd.forEach(ip => {
  13894. if (!existing.includes(ip)) existing.push(ip);
  13895. });
  13896. input.value = existing.join(', ');
  13897. }
  13898. }
  13899. async function saveDNSSettings(e) {
  13900. e.preventDefault();
  13901. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  13902. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  13903. if (servers.length === 0) {
  13904. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  13905. return;
  13906. }
  13907. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  13908. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  13909. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  13910. try {
  13911. const res = await fetch(`${API_BASE}/dns/settings`, {
  13912. method: 'POST',
  13913. headers: { 'Content-Type': 'application/json' },
  13914. body: JSON.stringify({
  13915. servers: servers,
  13916. cache_size: cacheSize,
  13917. domain: domain,
  13918. allow_remote_requests: allowRemote
  13919. })
  13920. });
  13921. const data = await res.json();
  13922. if (res.ok) {
  13923. const dnsForm = document.getElementById('form-dns-settings');
  13924. if (dnsForm) dnsForm.dataset.dirty = 'false';
  13925. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  13926. loadDNSSettings();
  13927. } else {
  13928. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  13929. }
  13930. } catch (err) {
  13931. showToast('Error', err.message, 'error');
  13932. }
  13933. }
  13934. async function flushDNSCache() {
  13935. try {
  13936. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  13937. if (res.ok) {
  13938. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  13939. loadDNSSettings();
  13940. } else {
  13941. const err = await res.json();
  13942. showToast('Error', err.error || 'Failed to flush cache', 'error');
  13943. }
  13944. } catch (err) {
  13945. showToast('Error', err.message, 'error');
  13946. }
  13947. }
  13948. function renderStaticDNSList() {
  13949. const tbody = document.getElementById('dns-static-tbody');
  13950. const empty = document.getElementById('dns-static-empty');
  13951. const badge = document.getElementById('dns-static-count-badge');
  13952. if (!tbody) return;
  13953. tbody.innerHTML = '';
  13954. const records = state.dnsStaticRecords || [];
  13955. if (badge) badge.innerText = `${records.length} Records`;
  13956. if (records.length === 0) {
  13957. empty?.classList.remove('hidden');
  13958. return;
  13959. }
  13960. empty?.classList.add('hidden');
  13961. records.forEach(rec => {
  13962. const tr = document.createElement('tr');
  13963. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  13964. tr.innerHTML = `
  13965. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  13966. <td class="py-2.5 px-4">
  13967. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  13968. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  13969. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  13970. }">
  13971. ${rec.type || 'A'}
  13972. </span>
  13973. </td>
  13974. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  13975. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  13976. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  13977. <td class="py-2.5 px-4">
  13978. <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
  13979. ${rec.disabled ? 'Disabled' : 'Active'}
  13980. </span>
  13981. </td>
  13982. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  13983. <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
  13984. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  13985. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  13986. </td>
  13987. `;
  13988. tbody.appendChild(tr);
  13989. });
  13990. }
  13991. function openStaticDNSModal(id = null) {
  13992. const modal = document.getElementById('modal-static-dns');
  13993. const title = document.getElementById('modal-static-dns-title');
  13994. const form = document.getElementById('form-static-dns');
  13995. if (!modal || !form) return;
  13996. form.reset();
  13997. document.getElementById('modal-static-dns-id').value = '';
  13998. if (id) {
  13999. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14000. if (rec) {
  14001. if (title) title.innerText = 'Edit Static DNS Record';
  14002. document.getElementById('modal-static-dns-id').value = rec.id;
  14003. document.getElementById('modal-static-dns-name').value = rec.name;
  14004. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14005. document.getElementById('modal-static-dns-addr').value = rec.address;
  14006. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14007. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14008. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14009. }
  14010. } else {
  14011. if (title) title.innerText = 'Add Static DNS Record';
  14012. }
  14013. modal.classList.remove('hidden');
  14014. }
  14015. function closeStaticDNSModal() {
  14016. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14017. }
  14018. async function submitSaveStaticDNS(e) {
  14019. e.preventDefault();
  14020. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14021. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14022. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14023. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14024. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14025. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14026. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14027. if (!name || !address) {
  14028. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14029. return;
  14030. }
  14031. try {
  14032. const res = await fetch(`${API_BASE}/dns/static`, {
  14033. method: 'POST',
  14034. headers: { 'Content-Type': 'application/json' },
  14035. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14036. });
  14037. const data = await res.json();
  14038. if (res.ok) {
  14039. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14040. closeStaticDNSModal();
  14041. loadDNSSettings();
  14042. } else {
  14043. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14044. }
  14045. } catch (err) {
  14046. showToast('Error', err.message, 'error');
  14047. }
  14048. }
  14049. async function deleteStaticDNS(id) {
  14050. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14051. try {
  14052. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14053. if (res.ok) {
  14054. showToast('Deleted', 'Static DNS record deleted', 'success');
  14055. loadDNSSettings();
  14056. }
  14057. } catch (err) {
  14058. showToast('Error', err.message, 'error');
  14059. }
  14060. }
  14061. async function toggleStaticDNS(id, disabled) {
  14062. try {
  14063. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14064. method: 'POST',
  14065. headers: { 'Content-Type': 'application/json' },
  14066. body: JSON.stringify({ disabled })
  14067. });
  14068. if (res.ok) {
  14069. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14070. loadDNSSettings();
  14071. }
  14072. } catch (err) {
  14073. showToast('Error', err.message, 'error');
  14074. }
  14075. }
  14076. async function loadSystemSettings() {
  14077. try {
  14078. const sysForm = document.getElementById('form-system-settings');
  14079. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14080. const res = await fetch(`${API_BASE}/system/settings`);
  14081. if (res.ok) {
  14082. const data = await res.json();
  14083. if (!isEditing) {
  14084. const hostInput = document.getElementById('system-hostname-input');
  14085. if (hostInput) hostInput.value = data.hostname || '';
  14086. const tzInput = document.getElementById('system-timezone-input');
  14087. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14088. }
  14089. }
  14090. } catch (err) {
  14091. console.error('Failed to load system settings:', err);
  14092. }
  14093. }
  14094. async function saveSystemSettings(e) {
  14095. e.preventDefault();
  14096. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14097. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14098. try {
  14099. const res = await fetch(`${API_BASE}/system/settings`, {
  14100. method: 'POST',
  14101. headers: { 'Content-Type': 'application/json' },
  14102. body: JSON.stringify({ hostname, timezone })
  14103. });
  14104. const data = await res.json();
  14105. if (res.ok) {
  14106. const sysForm = document.getElementById('form-system-settings');
  14107. if (sysForm) sysForm.dataset.dirty = 'false';
  14108. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14109. const sideH = document.getElementById('side-hostname');
  14110. if (sideH) sideH.innerText = data.hostname;
  14111. } else {
  14112. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14113. }
  14114. } catch (err) {
  14115. showToast('Error', err.message, 'error');
  14116. }
  14117. }