app.js 938 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. vxlanTunnels: [],
  109. vxlanVteps: [],
  110. pppSecrets: [],
  111. pppProfiles: [],
  112. pppActiveSessions: [],
  113. pppoeServer: null,
  114. pptpServer: null,
  115. l2tpServer: null,
  116. ipsecServer: null,
  117. ifaceFilter: 'all',
  118. currentModalIface: null,
  119. isPolling: false,
  120. expandedParents: new Set(['eth0']),
  121. pppoeData: null,
  122. wgData: null,
  123. ipsecData: null,
  124. l2tpData: null,
  125. pptpData: null,
  126. fwSummary: null,
  127. filterRules: [],
  128. natRules: [],
  129. mangleRules: [],
  130. addressLists: [],
  131. connections: [],
  132. policyRules: [],
  133. routingTables: [],
  134. routingFilters: [],
  135. filterChainSelected: 'all',
  136. activeToolsSubTab: 'ping',
  137. dhcpClients: [],
  138. dhcpSummary: null,
  139. dhcpServerTab: 'servers',
  140. dhcpServers: [],
  141. dhcpNetworks: [],
  142. dhcpLeases: [],
  143. dhcpOptions: [],
  144. dhcpServerSummary: null,
  145. sdwanGroups: [],
  146. sdwanTelemetry: null
  147. };
  148. const API_BASE = '/api';
  149. function escapeHtml(str) {
  150. if (str === null || str === undefined) return '';
  151. return String(str)
  152. .replace(/&/g, '&')
  153. .replace(/</g, '&lt;')
  154. .replace(/>/g, '&gt;')
  155. .replace(/"/g, '&quot;')
  156. .replace(/'/g, '&#039;');
  157. }
  158. function formatBytes(bytes) {
  159. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  160. const k = 1024;
  161. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  162. const i = Math.floor(Math.log(bytes) / Math.log(k));
  163. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  164. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  165. }
  166. // Initialize on page load
  167. document.addEventListener('DOMContentLoaded', async () => {
  168. initTableSorting();
  169. // Verify authentication before bootstrapping telemetry and views
  170. const isAuthenticated = await checkAuthStatus();
  171. if (isAuthenticated) {
  172. const hash = window.location.hash.replace('#', '') || 'dashboard';
  173. navigate(hash);
  174. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  175. if (!window._telemetryInterval) {
  176. window._telemetryInterval = setInterval(() => {
  177. if (state.isPolling && state.currentUser && !document.hidden) {
  178. fetchData(false);
  179. }
  180. }, 5000);
  181. }
  182. }
  183. });
  184. let trafficEventSource = null;
  185. let trafficPollFallback = null;
  186. function initLiveTrafficStream() {
  187. if (trafficEventSource) {
  188. try { trafficEventSource.close(); } catch(e) {}
  189. trafficEventSource = null;
  190. }
  191. if (trafficPollFallback) {
  192. clearInterval(trafficPollFallback);
  193. trafficPollFallback = null;
  194. }
  195. if (window.EventSource) {
  196. try {
  197. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  198. trafficEventSource.onmessage = (event) => {
  199. try {
  200. const data = JSON.parse(event.data);
  201. updateLiveInterfaceTraffic(data);
  202. } catch (e) {
  203. console.error('Error parsing live traffic event:', e);
  204. }
  205. };
  206. trafficEventSource.onerror = () => {
  207. // Fallback polling if SSE disconnects
  208. if (!trafficPollFallback) {
  209. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  210. }
  211. };
  212. trafficEventSource.onopen = () => {
  213. if (trafficPollFallback) {
  214. clearInterval(trafficPollFallback);
  215. trafficPollFallback = null;
  216. }
  217. };
  218. return;
  219. } catch (e) {
  220. console.warn('EventSource failed, using 1s polling fallback:', e);
  221. }
  222. }
  223. // Fallback if EventSource is unavailable
  224. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  225. }
  226. async function pollLiveTrafficSnapshot() {
  227. try {
  228. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  229. if (res.ok) {
  230. const data = await res.json();
  231. updateLiveInterfaceTraffic(data);
  232. }
  233. } catch (e) {}
  234. }
  235. function updateLiveInterfaceTraffic(data) {
  236. if (!data || !data.interfaces) return;
  237. state.latestTraffic = data;
  238. // 1. Update Top & Dashboard Total Bandwidth Indicators
  239. const rxHuman = data.total_rx_human || '0 B/s';
  240. const txHuman = data.total_tx_human || '0 B/s';
  241. const statRx = document.getElementById('stat-traffic-rx');
  242. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  243. const statTx = document.getElementById('stat-traffic-tx');
  244. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  245. // 2. Update state.interfaces rates in-memory
  246. if (Array.isArray(state.interfaces)) {
  247. state.interfaces.forEach(i => {
  248. const live = data.interfaces[i.name];
  249. if (live) {
  250. i.rate = {
  251. rx_bytes_sec: live.rx_bytes_sec,
  252. tx_bytes_sec: live.tx_bytes_sec,
  253. rx_human: live.rx_human,
  254. tx_human: live.tx_human
  255. };
  256. i.stats = {
  257. rx_bytes: live.rx_bytes,
  258. tx_bytes: live.tx_bytes,
  259. rx_packets: live.rx_packets,
  260. tx_packets: live.tx_packets,
  261. rx_errors: live.rx_errors,
  262. tx_errors: live.tx_errors,
  263. rx_dropped: live.rx_dropped,
  264. tx_dropped: live.tx_dropped
  265. };
  266. }
  267. });
  268. }
  269. // 3. Update all live UI rate spans in-place (ZERO flicker)
  270. Object.keys(data.interfaces).forEach(name => {
  271. const live = data.interfaces[name];
  272. // Dashboard Port Matrix Card
  273. const cardRate = document.getElementById(`port-card-rate-${name}`);
  274. if (cardRate && cardRate.innerText !== live.rx_human) {
  275. cardRate.innerText = live.rx_human;
  276. }
  277. // Dashboard Quick Interfaces Table
  278. const quickRx = document.getElementById(`quick-rx-${name}`);
  279. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  280. const quickTx = document.getElementById(`quick-tx-${name}`);
  281. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  282. // Main Interfaces Tree Table
  283. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  284. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  285. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  286. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  287. // VLAN Sub-interfaces Table
  288. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  289. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  290. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  291. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  292. // VLAN Page Table
  293. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  294. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  295. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  296. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  297. });
  298. }
  299. // Navigation Handler
  300. function navigate(tabName) {
  301. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  302. navigate('bgp');
  303. return;
  304. }
  305. if (tabName === 'vlans') {
  306. navigate('interfaces');
  307. return;
  308. }
  309. if (tabName === 'persistence') {
  310. navigate('dashboard');
  311. return;
  312. }
  313. stopFwStatPolling();
  314. stopNATStatPolling();
  315. stopMangleStatPolling();
  316. state.activeTab = tabName;
  317. window.location.hash = tabName;
  318. // Update nav links styling
  319. document.querySelectorAll('.nav-link').forEach(link => {
  320. 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';
  321. });
  322. const activeNav = document.getElementById(`nav-${tabName}`);
  323. if (activeNav) {
  324. 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';
  325. }
  326. // Update page headers
  327. const titles = {
  328. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  329. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  330. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  331. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  332. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  333. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  334. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  335. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  336. sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
  337. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  338. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  339. rip: { title: 'RIP Dynamic Routing', sub: 'Routing Information Protocol (RIPv2 IPv4 & RIPng IPv6) hop-count distance-vector routing' },
  340. bfd: { title: 'BFD Fast Session Detection', sub: 'Bidirectional Forwarding Detection (BFD) sub-second link failure detection for BGP and OSPF' },
  341. babel: { title: 'Babel Dynamic Routing', sub: 'Babel loop-avoiding distance-vector routing for wired and wireless mesh networks (RFC 8966)' },
  342. radv: { title: 'IPv6 Router Advertisements (RAdv)', sub: 'BIRD 2 ICMPv6 Router Advertisement daemon for IPv6 SLAAC autoconfiguration and RDNSS' },
  343. eigrp: { title: 'EIGRP Dynamic Routing', sub: 'Enhanced Interior Gateway Routing Protocol (RFC 7868) DUAL routing, neighbors and topology' },
  344. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  345. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  346. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  347. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  348. vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
  349. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  350. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  351. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  352. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  353. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  354. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  355. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  356. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  357. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  358. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  359. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  360. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  361. reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
  362. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  363. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  364. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  365. };
  366. const header = titles[tabName] || titles.dashboard;
  367. const pTitle = document.getElementById('page-title');
  368. if (pTitle) pTitle.innerText = header.title;
  369. const pSub = document.getElementById('page-subtitle');
  370. if (pSub) pSub.innerText = header.sub;
  371. // Toggle sections dynamically for all section elements
  372. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  373. if (el.id === `section-${tabName}`) {
  374. el.classList.remove('hidden');
  375. } else {
  376. el.classList.add('hidden');
  377. }
  378. });
  379. if (tabName === 'interfaces') {
  380. loadRoles();
  381. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  382. else switchIfaceSubTab('tree');
  383. }
  384. if (tabName === 'bridge') loadBridge();
  385. if (tabName === 'firewall') loadFirewall();
  386. if (tabName === 'routes') loadRoutes();
  387. if (tabName === 'sdwan') loadSDWAN();
  388. if (tabName === 'bgp') {
  389. loadDynamicRouting();
  390. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  391. }
  392. if (tabName === 'ospf') {
  393. loadDynamicRouting();
  394. switchOspfTab(state.activeOspfTab || 'instances');
  395. }
  396. if (tabName === 'rip') {
  397. loadDynamicRouting();
  398. switchRipTab(state.activeRipTab || 'instances');
  399. }
  400. if (tabName === 'bfd') {
  401. loadDynamicRouting();
  402. switchBfdTab(state.activeBfdTab || 'config');
  403. }
  404. if (tabName === 'babel') {
  405. loadDynamicRouting();
  406. switchBabelTab(state.activeBabelTab || 'instances');
  407. }
  408. if (tabName === 'radv') {
  409. loadDynamicRouting();
  410. switchRadvTab(state.activeRadvTab || 'instances');
  411. }
  412. if (tabName === 'eigrp') {
  413. loadDynamicRouting();
  414. switchEigrpTab(state.activeEigrpTab || 'instances');
  415. }
  416. if (tabName === 'routing-filters') loadDynamicRouting();
  417. if (tabName === 'dynamic-routing') loadDynamicRouting();
  418. if (tabName === 'ppp') loadPPP();
  419. if (tabName === 'eoip') loadEoIP();
  420. if (tabName === 'vxlan') loadVXLAN();
  421. if (tabName === 'aerotun') loadAeroTUN();
  422. if (tabName === 'pppoe') loadPPPoE();
  423. if (tabName === 'wireguard') loadWireGuard();
  424. if (tabName === 'ipsec') loadIPSec();
  425. if (tabName === 'l2tp') loadL2TP();
  426. if (tabName === 'pptp') loadPPTP();
  427. if (tabName === 'tools') loadToolsView();
  428. if (tabName === 'dhcp-client') loadDHCPClients();
  429. if (tabName === 'dhcp-server') loadDHCPServer();
  430. if (tabName === 'vrrp') loadVRRP();
  431. if (tabName === 'bwtest') loadBwTestView();
  432. if (tabName === 'settings') loadSettingsData();
  433. if (tabName === 'users') loadUsers();
  434. if (tabName === 'certificates') loadCertificates();
  435. if (tabName === 'reverse_proxy') loadReverseProxy();
  436. if (tabName === 'services') loadServices();
  437. if (tabName === 'updates') loadUpdateStatus();
  438. if (tabName === 'logs') loadLogs();
  439. setTimeout(initTableSorting, 50);
  440. }
  441. // Fetch all core system, network and VPN telemetry
  442. function fetchData(isManual = false) {
  443. if (coreRefreshPromise) return coreRefreshPromise;
  444. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  445. return coreRefreshPromise;
  446. }
  447. async function refreshCoreData(isManual = false) {
  448. const spinner = document.getElementById('refresh-spinner');
  449. if (isManual && spinner) spinner.classList.add('animate-spin');
  450. try {
  451. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  452. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  453. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  454. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  455. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  456. summaryFetch('/vlans'),
  457. summaryFetch('/vpn/status'),
  458. summaryFetch('/firewall/summary'),
  459. summaryFetch('/routing/dynamic/summary'),
  460. summaryFetch('/bridge/summary'),
  461. summaryFetch('/dhcp/clients/summary'),
  462. summaryFetch('/dhcp/clients'),
  463. summaryFetch('/vrrp/summary').catch(() => null),
  464. summaryFetch('/roles').catch(() => null)
  465. ]);
  466. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  467. if (rolesRes && rolesRes.ok) {
  468. state.roles = await rolesRes.json();
  469. const countEl = document.getElementById('badge-roles-count');
  470. if (countEl) countEl.innerText = (state.roles || []).length;
  471. }
  472. if (vrrpSumRes && vrrpSumRes.ok) {
  473. state.vrrpSummary = await vrrpSumRes.json();
  474. renderVRRPSummary();
  475. }
  476. if (dhcpSumRes && dhcpSumRes.ok) {
  477. state.dhcpSummary = await dhcpSumRes.json();
  478. const bDhcp = document.getElementById('badge-dhcp-client-count');
  479. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  480. }
  481. if (dhcpClientsRes && dhcpClientsRes.ok) {
  482. state.dhcpClients = await dhcpClientsRes.json();
  483. }
  484. if (brSummaryRes.ok) {
  485. state.bridgeSummary = await brSummaryRes.json();
  486. const bBridge = document.getElementById('badge-bridge-count');
  487. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  488. const sBr = document.getElementById('bridge-stat-bridges');
  489. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  490. const sPorts = document.getElementById('bridge-stat-ports');
  491. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  492. const sHosts = document.getElementById('bridge-stat-hosts');
  493. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  494. }
  495. if (statusRes.ok) state.systemStatus = await statusRes.json();
  496. if (ifacesRes.ok) {
  497. const ifacesData = await ifacesRes.json();
  498. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  499. state.interfaces = rawIfaces.filter(i => {
  500. if (!i.name) return false;
  501. if (i.name.startsWith('ep_')) return false;
  502. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  503. });
  504. try { populateToolsInterfaces(); } catch (e) {}
  505. }
  506. if (vlansRes.ok) {
  507. const vlansData = await vlansRes.json();
  508. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  509. }
  510. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  511. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  512. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  513. updateSystemMetrics();
  514. updateBadges();
  515. if (state.activeTab === 'dashboard') renderDashboard();
  516. if (state.activeTab === 'interfaces') {
  517. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  518. else renderInterfacesList();
  519. }
  520. if (state.activeTab === 'vlans') renderVlansList();
  521. if (state.activeTab === 'firewall') await loadFirewall(false);
  522. if (state.activeTab === 'routes') await loadRoutes(false);
  523. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf' || state.activeTab === 'rip' || state.activeTab === 'bfd' || state.activeTab === 'babel' || state.activeTab === 'radv') await loadDynamicRouting(false);
  524. if (state.activeTab === 'ppp') await loadPPP(false);
  525. if (state.activeTab === 'eoip') await loadEoIP(false);
  526. if (state.activeTab === 'vxlan') await loadVXLAN(false);
  527. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  528. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  529. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  530. if (state.activeTab === 'ipsec') await loadIPSec(false);
  531. if (state.activeTab === 'l2tp') await loadL2TP(false);
  532. if (state.activeTab === 'pptp') await loadPPTP(false);
  533. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  534. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  535. if (state.activeTab === 'vrrp') await loadVRRP(false);
  536. if (state.activeTab === 'settings') await loadSettingsData(false);
  537. if (state.activeTab === 'users') await loadUsers(false);
  538. if (state.activeTab === 'certificates') await loadCertificates(false);
  539. if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
  540. if (state.activeTab === 'sdwan') await loadSDWAN(false);
  541. if (state.activeTab === 'services') await loadServices(false);
  542. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  543. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  544. } catch (err) {
  545. console.error('Failed to fetch router state:', err);
  546. } finally {
  547. if (isManual && spinner) {
  548. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  549. }
  550. }
  551. }
  552. // Update Top KPI and Sidebar Telemetry
  553. function updateSystemMetrics() {
  554. const s = state.systemStatus;
  555. const v = state.vpnStatus;
  556. if (!s) return;
  557. // Sidebar Host & Uptime
  558. const sideHost = document.getElementById('side-hostname');
  559. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  560. const sideUp = document.getElementById('side-uptime');
  561. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  562. const sideGw = document.getElementById('side-gateway-ip');
  563. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  564. // Compute CPU Metrics
  565. let cpuPct = 0;
  566. if (s.cpu_pct !== undefined) {
  567. cpuPct = s.cpu_pct;
  568. } else if (s.cpu_load && s.cpu_load.length > 0) {
  569. const cores = s.cpu_cores || 1;
  570. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  571. }
  572. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  573. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  574. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  575. // Sidebar CPU
  576. const sideCpuVal = document.getElementById('side-cpu-val');
  577. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  578. const sideCpuBar = document.getElementById('side-cpu-bar');
  579. if (sideCpuBar) {
  580. sideCpuBar.style.width = cpuWidth;
  581. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  582. }
  583. // Dashboard CPU Card
  584. const dashCpuVal = document.getElementById('dash-cpu-val');
  585. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  586. const dashCpuBar = document.getElementById('dash-cpu-bar');
  587. if (dashCpuBar) {
  588. dashCpuBar.style.width = cpuWidth;
  589. if (cpuPct > 85) {
  590. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  591. } else if (cpuPct > 65) {
  592. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  593. } else {
  594. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  595. }
  596. }
  597. const dashCpuCores = document.getElementById('dash-cpu-cores');
  598. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  599. const dashCpuLoad = document.getElementById('dash-cpu-load');
  600. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  601. const dashCpuStatus = document.getElementById('dash-cpu-status');
  602. if (dashCpuStatus) {
  603. if (cpuPct > 85) {
  604. dashCpuStatus.innerText = 'High';
  605. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  606. } else if (cpuPct > 65) {
  607. dashCpuStatus.innerText = 'Heavy';
  608. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  609. } else {
  610. dashCpuStatus.innerText = 'Normal';
  611. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  612. }
  613. }
  614. // Compute RAM Metrics
  615. const memPct = Math.round(s.mem_usage_pct || 0);
  616. const memPctStr = `${memPct}%`;
  617. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  618. const usedMB = s.mem_used_mb || 0;
  619. const totalMB = s.mem_total_mb || 0;
  620. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  621. function fmtMemMB(mb) {
  622. if (mb >= 1024) {
  623. return `${(mb / 1024).toFixed(1)} GB`;
  624. }
  625. return `${mb} MB`;
  626. }
  627. // Sidebar RAM
  628. const sideRamVal = document.getElementById('side-ram-val');
  629. if (sideRamVal) sideRamVal.innerText = memPctStr;
  630. const sideRamBar = document.getElementById('side-ram-bar');
  631. if (sideRamBar) sideRamBar.style.width = memWidth;
  632. // Dashboard RAM Card
  633. const dashRamVal = document.getElementById('dash-ram-val');
  634. if (dashRamVal) dashRamVal.innerText = memPctStr;
  635. const dashRamBar = document.getElementById('dash-ram-bar');
  636. if (dashRamBar) {
  637. dashRamBar.style.width = memWidth;
  638. if (memPct > 85) {
  639. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  640. } else if (memPct > 70) {
  641. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  642. } else {
  643. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  644. }
  645. }
  646. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  647. if (dashRamUsedTotal) {
  648. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  649. }
  650. const dashRamFree = document.getElementById('dash-ram-free');
  651. if (dashRamFree) {
  652. dashRamFree.innerText = fmtMemMB(freeMB);
  653. }
  654. const dashRamStatus = document.getElementById('dash-ram-status');
  655. if (dashRamStatus) {
  656. if (memPct > 85) {
  657. dashRamStatus.innerText = 'High';
  658. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  659. } else {
  660. dashRamStatus.innerText = 'Active';
  661. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  662. }
  663. }
  664. // Legacy Dashboard Stats (Safe checks)
  665. const elIfacesUp = document.getElementById('stat-ifaces-up');
  666. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  667. const elIfacesTot = document.getElementById('stat-ifaces-total');
  668. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  669. const elIfacesDown = document.getElementById('stat-ifaces-down');
  670. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  671. const elVlans = document.getElementById('stat-vlans-count');
  672. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  673. // VPN Status Indicators
  674. if (v) {
  675. const totalActive = v.total_active_tunnels || 0;
  676. const statVpnActive = document.getElementById('stat-vpn-active');
  677. if (statVpnActive) statVpnActive.innerText = totalActive;
  678. const tunnelsDot = document.getElementById('tunnels-dot');
  679. const tunnelsLabel = document.getElementById('tunnels-label');
  680. if (tunnelsDot && tunnelsLabel) {
  681. if (totalActive > 0) {
  682. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  683. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  684. } else {
  685. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  686. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  687. }
  688. }
  689. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  690. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  691. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  692. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  693. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  694. }
  695. // Total Live Bandwidth Rate
  696. let totalRx = 0;
  697. let totalTx = 0;
  698. (state.interfaces || []).forEach(i => {
  699. if (i.rate) {
  700. totalRx += i.rate.rx_bytes_sec || 0;
  701. totalTx += i.rate.tx_bytes_sec || 0;
  702. }
  703. });
  704. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  705. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  706. }
  707. function setDotBadge(id, active) {
  708. const el = document.getElementById(id);
  709. if (!el) return;
  710. if (active) {
  711. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  712. } else {
  713. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  714. }
  715. }
  716. function updateBadges() {
  717. const bIfaces = document.getElementById('badge-ifaces-count');
  718. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  719. const bVlans = document.getElementById('badge-vlans-count');
  720. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  721. if (state.fwSummary) {
  722. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  723. const badgeFw = document.getElementById('badge-firewall-count');
  724. if (badgeFw) badgeFw.innerText = totalFwRules;
  725. }
  726. if (state.vpnStatus) {
  727. const v = state.vpnStatus;
  728. const bEoIP = document.getElementById('badge-eoip-count');
  729. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  730. const bVXLAN = document.getElementById('badge-vxlan-count');
  731. if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
  732. const bAero = document.getElementById('badge-aerotun-count');
  733. if (bAero) bAero.innerText = v.total_aerotun || 0;
  734. const bPPPSess = document.getElementById('badge-ppp-sessions');
  735. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  736. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  737. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  738. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  739. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  740. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  741. }
  742. if (state.dynSummary) {
  743. const d = state.dynSummary;
  744. setDotBadge('badge-bgp-dot', d.bgp_running);
  745. setDotBadge('badge-ospf-dot', d.ospf_running);
  746. setDotBadge('badge-rip-dot', d.rip_running);
  747. setDotBadge('badge-bfd-dot', d.bfd_running);
  748. setDotBadge('badge-babel-dot', d.babel_running);
  749. setDotBadge('badge-radv-dot', d.radv_running);
  750. setDotBadge('badge-eigrp-dot', d.eigrp_running);
  751. const bBgp = document.getElementById('badge-bgp-count');
  752. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  753. const bOspf = document.getElementById('badge-ospf-count');
  754. if (bOspf) bOspf.innerText = (state.ospfLiveInterfaces || state.ospfTemplates || []).length;
  755. const bRip = document.getElementById('badge-rip-count');
  756. if (bRip) bRip.innerText = (state.ripInterfaces || []).length;
  757. const bBfd = document.getElementById('badge-bfd-count');
  758. if (bBfd) bBfd.innerText = (state.bfdInterfaces || []).length;
  759. const bBabel = document.getElementById('badge-babel-count');
  760. if (bBabel) bBabel.innerText = (state.babelInterfaces || []).length;
  761. const bRadv = document.getElementById('badge-radv-count');
  762. if (bRadv) bRadv.innerText = (state.radvInterfaces || []).length;
  763. const bEigrp = document.getElementById('badge-eigrp-count');
  764. if (bEigrp) bEigrp.innerText = (state.eigrpInterfaces || []).length || (state.eigrpNetworks || []).length || (state.eigrpInstances || []).length;
  765. const bFilters = document.getElementById('badge-filters-count');
  766. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  767. }
  768. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  769. if (bDhcpServer) {
  770. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  771. }
  772. }
  773. // Render Dashboard View
  774. function renderDashboard() {
  775. const matrix = document.getElementById('port-matrix');
  776. if (!matrix) return;
  777. const ifaces = state.interfaces || [];
  778. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  779. if (matrix.dataset.sig === sig) {
  780. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  781. }
  782. matrix.dataset.sig = sig;
  783. matrix.innerHTML = '';
  784. (state.interfaces || []).forEach(iface => {
  785. const isUp = iface.state === 'UP';
  786. const isVlan = iface.is_vlan;
  787. const portCard = document.createElement('div');
  788. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  789. isUp
  790. ? (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')
  791. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  792. }`;
  793. portCard.onclick = () => openIfaceModal(iface.name);
  794. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  795. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  796. portCard.innerHTML = `
  797. <div class="flex items-center justify-between mb-2">
  798. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  799. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  800. </div>
  801. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  802. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  803. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  804. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  805. </div>
  806. `;
  807. matrix.appendChild(portCard);
  808. });
  809. const ifaceTbody = document.getElementById('quick-interfaces-table');
  810. if (ifaceTbody) {
  811. ifaceTbody.innerHTML = '';
  812. (state.interfaces || []).forEach(i => {
  813. const isUp = i.state === 'UP';
  814. const tr = document.createElement('tr');
  815. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  816. tr.onclick = () => openIfaceModal(i.name);
  817. const rxStr = i.rate?.rx_human || '0 B/s';
  818. const txStr = i.rate?.tx_human || '0 B/s';
  819. tr.innerHTML = `
  820. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  821. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  822. <span>${i.name}</span>
  823. </td>
  824. <td class="py-2.5 text-slate-300 font-sans">
  825. ${getRoleBadge(i.role || 'LAN')}
  826. </td>
  827. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  828. <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>
  829. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  830. <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>
  831. </td>
  832. <td class="py-2.5 text-right font-sans font-semibold">
  833. <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>
  834. </td>
  835. `;
  836. ifaceTbody.appendChild(tr);
  837. });
  838. }
  839. const vlanTbody = document.getElementById('quick-vlans-table');
  840. if (vlanTbody) {
  841. vlanTbody.innerHTML = '';
  842. }
  843. }
  844. // Expand / Collapse Handlers
  845. function toggleExpand(parentName) {
  846. if (state.expandedParents.has(parentName)) {
  847. state.expandedParents.delete(parentName);
  848. } else {
  849. state.expandedParents.add(parentName);
  850. }
  851. renderInterfacesList();
  852. }
  853. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  854. function supportsVLAN(iface) {
  855. if (!iface) return false;
  856. if (iface.is_vlan) return false;
  857. const name = (iface.name || '').toLowerCase();
  858. const type = (iface.type || '').toLowerCase();
  859. const role = (iface.role || '').toLowerCase();
  860. // Exclude loopback
  861. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  862. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  863. if (type === 'wireguard' || name.startsWith('wg')) return false;
  864. // Exclude PPP / PPPoE
  865. if (type === 'ppp' || name.startsWith('ppp')) return false;
  866. // Exclude other Layer 3 tunnels and dummy devices
  867. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  868. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  869. return false;
  870. }
  871. // If name already contains a dot, it's already a sub-interface
  872. if (name.includes('.')) return false;
  873. return true;
  874. }
  875. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  876. function supportsDHCPClient(iface) {
  877. if (!iface) return false;
  878. const name = (iface.name || '').toLowerCase();
  879. const type = (iface.type || '').toLowerCase();
  880. const role = (iface.role || '').toLowerCase();
  881. // Exclude loopback
  882. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  883. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  884. if (type === 'wireguard' || name.startsWith('wg')) return false;
  885. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  886. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  887. // Exclude other Layer 3 tunnels and dummy devices
  888. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  889. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  890. return false;
  891. }
  892. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  893. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  894. if (isBridgePort) return false;
  895. return true;
  896. }
  897. // Expand / Collapse Handlers
  898. function toggleExpand(parentName) {
  899. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  900. if (childVlans.length === 0) {
  901. // Cannot expand an interface with no VLANs
  902. state.expandedParents.delete(parentName);
  903. return;
  904. }
  905. if (state.expandedParents.has(parentName)) {
  906. state.expandedParents.delete(parentName);
  907. } else {
  908. state.expandedParents.add(parentName);
  909. }
  910. renderInterfacesList();
  911. }
  912. function expandAllIfaces(expand) {
  913. if (expand) {
  914. (state.interfaces || []).forEach(i => {
  915. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  916. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  917. });
  918. } else {
  919. state.expandedParents.clear();
  920. }
  921. renderInterfacesList();
  922. }
  923. // =========================================================================
  924. // INTERFACE ROLE TAGS MANAGEMENT
  925. // =========================================================================
  926. const ROLE_COLORS = {
  927. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  928. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  929. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  930. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  931. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  932. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  933. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  934. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  935. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  936. };
  937. function getRoleBadge(roleName) {
  938. const name = roleName || 'LAN';
  939. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  940. const colorKey = (role?.color || 'blue').toLowerCase();
  941. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  942. 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>`;
  943. }
  944. function switchIfaceSubTab(subTab) {
  945. state.activeIfaceSubTab = subTab;
  946. const treeTab = document.getElementById('ifaces-subtab-tree');
  947. const rolesTab = document.getElementById('ifaces-subtab-roles');
  948. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  949. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  950. if (subTab === 'roles') {
  951. treeTab?.classList.add('hidden');
  952. rolesTab?.classList.remove('hidden');
  953. if (btnRoles) {
  954. 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';
  955. }
  956. if (btnTree) {
  957. 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';
  958. }
  959. loadRoles();
  960. } else {
  961. rolesTab?.classList.add('hidden');
  962. treeTab?.classList.remove('hidden');
  963. if (btnTree) {
  964. 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';
  965. }
  966. if (btnRoles) {
  967. 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';
  968. }
  969. renderInterfacesList();
  970. }
  971. }
  972. async function loadRoles() {
  973. try {
  974. const res = await fetch(`${API_BASE}/roles`);
  975. if (res.ok) {
  976. state.roles = await res.json();
  977. const countEl = document.getElementById('badge-roles-count');
  978. if (countEl) countEl.innerText = (state.roles || []).length;
  979. renderRolesTable();
  980. populateRoleSelects();
  981. }
  982. } catch (err) {
  983. console.error('Failed to load role tags:', err);
  984. }
  985. }
  986. function renderRolesTable() {
  987. const tbody = document.getElementById('roles-table-body');
  988. const empty = document.getElementById('roles-empty-state');
  989. if (!tbody) return;
  990. const roles = state.roles || [];
  991. if (roles.length === 0) {
  992. tbody.innerHTML = '';
  993. empty?.classList.remove('hidden');
  994. return;
  995. }
  996. empty?.classList.add('hidden');
  997. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  998. if (tbody.dataset.sig === sig) return;
  999. tbody.dataset.sig = sig;
  1000. tbody.innerHTML = roles.map(r => {
  1001. const colorKey = (r.color || 'blue').toLowerCase();
  1002. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1003. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  1004. const ifacesChips = ifaces.length > 0
  1005. ? 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('')
  1006. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  1007. return `
  1008. <tr class="hover:bg-slate-800/40 transition">
  1009. <td class="py-3 px-4">
  1010. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  1011. ${escapeHtml(r.name)}
  1012. </span>
  1013. </td>
  1014. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  1015. <span>${escapeHtml(r.name)}</span>
  1016. ${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>' : ''}
  1017. </td>
  1018. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  1019. <span class="inline-flex items-center gap-1.5">
  1020. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  1021. <span>${escapeHtml(r.color || 'blue')}</span>
  1022. </span>
  1023. </td>
  1024. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  1025. <td class="py-3 px-4 font-sans">
  1026. <div class="flex flex-wrap items-center">
  1027. ${ifacesChips}
  1028. </div>
  1029. </td>
  1030. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  1031. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  1032. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1033. Edit
  1034. </button>
  1035. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  1036. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1037. Delete
  1038. </button>
  1039. </td>
  1040. </tr>
  1041. `;
  1042. }).join('');
  1043. }
  1044. function openRoleModal(id = null) {
  1045. const modal = document.getElementById('role-modal');
  1046. if (!modal) return;
  1047. const idInput = document.getElementById('role-modal-id');
  1048. const nameInput = document.getElementById('role-modal-name');
  1049. const colorSelect = document.getElementById('role-modal-color');
  1050. const descInput = document.getElementById('role-modal-desc');
  1051. const title = document.getElementById('role-modal-title');
  1052. if (id) {
  1053. const role = (state.roles || []).find(r => r.id === id);
  1054. if (role) {
  1055. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1056. if (idInput) idInput.value = role.id;
  1057. if (nameInput) nameInput.value = role.name;
  1058. if (colorSelect) colorSelect.value = role.color || 'blue';
  1059. if (descInput) descInput.value = role.description || '';
  1060. }
  1061. } else {
  1062. if (title) title.innerText = 'Add Role Tag';
  1063. if (idInput) idInput.value = '';
  1064. if (nameInput) nameInput.value = '';
  1065. if (colorSelect) colorSelect.value = 'blue';
  1066. if (descInput) descInput.value = '';
  1067. }
  1068. updateRoleModalPreview();
  1069. modal.classList.remove('hidden');
  1070. }
  1071. function closeRoleModal() {
  1072. const modal = document.getElementById('role-modal');
  1073. if (modal) modal.classList.add('hidden');
  1074. }
  1075. function updateRoleModalPreview() {
  1076. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1077. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1078. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1079. const preview = document.getElementById('role-modal-preview');
  1080. if (preview) {
  1081. preview.innerText = name;
  1082. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1083. }
  1084. }
  1085. async function submitSaveRole(e) {
  1086. e.preventDefault();
  1087. const id = document.getElementById('role-modal-id')?.value;
  1088. const name = document.getElementById('role-modal-name')?.value.trim();
  1089. const color = document.getElementById('role-modal-color')?.value;
  1090. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1091. if (!name) return;
  1092. try {
  1093. const payload = { id, name, color, description: desc };
  1094. const method = id ? 'PUT' : 'POST';
  1095. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1096. const res = await fetch(url, {
  1097. method,
  1098. headers: { 'Content-Type': 'application/json' },
  1099. body: JSON.stringify(payload)
  1100. });
  1101. if (res.ok) {
  1102. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1103. closeRoleModal();
  1104. await loadRoles();
  1105. fetchData(false);
  1106. } else {
  1107. const err = await res.json();
  1108. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1109. }
  1110. } catch (err) {
  1111. showToast('Error', err.message, 'error');
  1112. }
  1113. }
  1114. async function deleteRoleTag(id, name) {
  1115. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1116. try {
  1117. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1118. method: 'DELETE'
  1119. });
  1120. if (res.ok) {
  1121. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1122. await loadRoles();
  1123. fetchData(false);
  1124. } else {
  1125. const err = await res.json();
  1126. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1127. }
  1128. } catch (err) {
  1129. showToast('Error', err.message, 'error');
  1130. }
  1131. }
  1132. function populateRoleSelects(selectedRole = '') {
  1133. const ifaceSelect = document.getElementById('modal-iface-role');
  1134. const vlanSelect = document.getElementById('vlan-role');
  1135. const roles = state.roles || [];
  1136. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1137. if (ifaceSelect) {
  1138. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1139. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1140. ifaceSelect.innerHTML = optionsHtml;
  1141. ifaceSelect.dataset.optionsSig = optionsHtml;
  1142. }
  1143. if (currentVal) ifaceSelect.value = currentVal;
  1144. }
  1145. if (vlanSelect) {
  1146. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1147. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1148. vlanSelect.innerHTML = optionsHtml;
  1149. vlanSelect.dataset.optionsSig = optionsHtml;
  1150. }
  1151. if (currentVal) vlanSelect.value = currentVal;
  1152. }
  1153. }
  1154. // Filter and Render Hierarchical Interfaces List
  1155. function filterIfaces(filter) {
  1156. state.ifaceFilter = filter || 'all';
  1157. renderInterfacesList();
  1158. }
  1159. function renderInterfacesList() {
  1160. const tbody = document.getElementById('interfaces-tree-tbody');
  1161. const emptyState = document.getElementById('interfaces-empty-state');
  1162. const summary = document.getElementById('ifaces-list-summary');
  1163. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1164. const allIfaces = state.interfaces || [];
  1165. const allVlans = state.vlans || [];
  1166. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1167. const filteredParents = parentIfaces.filter(parent => {
  1168. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1169. if (query) {
  1170. const matchName = parent.name.toLowerCase().includes(query);
  1171. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1172. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1173. const matchType = (parent.type || '').toLowerCase().includes(query);
  1174. const matchVlan = childVlans.some(v =>
  1175. v.name.toLowerCase().includes(query) ||
  1176. String(v.vlan_id).includes(query) ||
  1177. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1178. (v.description || '').toLowerCase().includes(query)
  1179. );
  1180. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1181. }
  1182. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1183. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1184. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1185. return true;
  1186. });
  1187. if (summary) {
  1188. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1189. }
  1190. if (filteredParents.length === 0) {
  1191. emptyState?.classList.remove('hidden');
  1192. tbody.innerHTML = '';
  1193. return;
  1194. }
  1195. emptyState?.classList.add('hidden');
  1196. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1197. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1198. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1199. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1200. }).join(';');
  1201. if (tbody.dataset.sig === sig) {
  1202. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1203. }
  1204. tbody.dataset.sig = sig;
  1205. tbody.innerHTML = '';
  1206. filteredParents.forEach(parent => {
  1207. const isUp = parent.state === 'UP';
  1208. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1209. const hasVlans = childVlans.length > 0;
  1210. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1211. const canHaveVlan = supportsVLAN(parent);
  1212. const parentRow = document.createElement('tr');
  1213. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1214. parentRow.innerHTML = `
  1215. <td class="py-3 px-3 text-center">
  1216. ${hasVlans ? `
  1217. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1218. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1219. <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">
  1220. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1221. </svg>
  1222. </button>
  1223. ` : `
  1224. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1225. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1226. </div>
  1227. `}
  1228. </td>
  1229. <td class="py-3 px-4">
  1230. <div class="flex items-center space-x-2.5">
  1231. <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">
  1232. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1233. </div>
  1234. <div>
  1235. <div class="flex items-center gap-2">
  1236. <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'}">
  1237. <span>${parent.name}</span>
  1238. <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>
  1239. </span>
  1240. ${hasVlans ? `
  1241. <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>
  1242. ` : `
  1243. <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>
  1244. `}
  1245. </div>
  1246. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1247. </div>
  1248. </div>
  1249. </td>
  1250. <td class="py-3 px-4 font-sans">
  1251. <div class="flex items-center gap-1.5">
  1252. ${getRoleBadge(parent.role || 'LAN')}
  1253. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1254. </div>
  1255. </td>
  1256. <td class="py-3 px-4">
  1257. ${parent.ipv4 && parent.ipv4.length > 0
  1258. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1259. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1260. }
  1261. ${(() => {
  1262. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1263. if (!c) return '';
  1264. 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');
  1265. 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>`;
  1266. })()}
  1267. </td>
  1268. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1269. <div>${parent.mac || 'N/A'}</div>
  1270. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1271. </td>
  1272. <td class="py-3 px-4 text-[11px]">
  1273. <div class="flex items-center space-x-2">
  1274. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1275. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1276. </div>
  1277. </td>
  1278. <td class="py-3 px-4 font-sans">
  1279. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1280. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1281. 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'
  1282. }" title="Click to toggle link status">
  1283. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1284. <span>${parent.state}</span>
  1285. </button>
  1286. </td>
  1287. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1288. ${(() => {
  1289. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1290. if (c) {
  1291. 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>`;
  1292. }
  1293. if (!supportsDHCPClient(parent)) {
  1294. return '';
  1295. }
  1296. 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>`;
  1297. })()}
  1298. ${canHaveVlan ? `
  1299. <button onclick="openVlanModal('${parent.name}')"
  1300. 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">
  1301. + Add VLAN
  1302. </button>
  1303. ` : ''}
  1304. <button onclick="openIfaceModal('${parent.name}')"
  1305. 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">
  1306. Edit
  1307. </button>
  1308. </td>
  1309. `;
  1310. tbody.appendChild(parentRow);
  1311. if (isExpanded) {
  1312. const drawerRow = document.createElement('tr');
  1313. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1314. const drawerCell = document.createElement('td');
  1315. drawerCell.colSpan = 8;
  1316. drawerCell.className = 'p-0';
  1317. drawerCell.innerHTML = `
  1318. <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">
  1319. <div class="flex items-center justify-between mb-3">
  1320. <div class="flex items-center space-x-3">
  1321. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1322. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1323. </span>
  1324. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1325. ${childVlans.length} Attached
  1326. </span>
  1327. </div>
  1328. <button onclick="openVlanModal('${parent.name}')"
  1329. 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">
  1330. <span>+ Create VLAN on ${parent.name}</span>
  1331. </button>
  1332. </div>
  1333. ${childVlans.length === 0 ? `
  1334. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1335. <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>
  1336. <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">
  1337. <span>+ Create Your First VLAN on ${parent.name}</span>
  1338. </button>
  1339. </div>
  1340. ` : `
  1341. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1342. <table class="w-full text-left text-xs font-mono">
  1343. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1344. <tr>
  1345. <th class="py-2.5 px-4">VLAN ID</th>
  1346. <th class="py-2.5 px-4">Interface Device</th>
  1347. <th class="py-2.5 px-4">Subnet Gateway</th>
  1348. <th class="py-2.5 px-4">Role / Alias</th>
  1349. <th class="py-2.5 px-4">MTU</th>
  1350. <th class="py-2.5 px-4">Throughput</th>
  1351. <th class="py-2.5 px-4">Status</th>
  1352. <th class="py-2.5 px-4 text-right">Actions</th>
  1353. </tr>
  1354. </thead>
  1355. <tbody class="divide-y divide-slate-800/70">
  1356. ${childVlans.map(v => {
  1357. const isVlanUp = v.state === 'UP';
  1358. return `
  1359. <tr class="hover:bg-slate-800/40 transition">
  1360. <td class="py-2.5 px-4">
  1361. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1362. VLAN ${v.vlan_id}
  1363. </span>
  1364. </td>
  1365. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1366. <span class="text-cyan-500">└─</span>
  1367. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1368. <span>${v.name}</span>
  1369. <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>
  1370. </span>
  1371. </td>
  1372. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1373. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1374. ${(() => {
  1375. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1376. if (!c) return '';
  1377. 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';
  1378. 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>`;
  1379. })()}
  1380. </td>
  1381. <td class="py-2.5 px-4 font-sans text-slate-300">
  1382. <div class="flex items-center gap-1.5">
  1383. ${getRoleBadge(v.role || 'LAN')}
  1384. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1385. </div>
  1386. </td>
  1387. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1388. <td class="py-2.5 px-4 text-[11px]">
  1389. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1390. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1391. </td>
  1392. <td class="py-2.5 px-4 font-sans">
  1393. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1394. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1395. 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'
  1396. }">
  1397. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1398. <span>${v.state}</span>
  1399. </button>
  1400. </td>
  1401. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1402. ${(() => {
  1403. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1404. if (c) {
  1405. 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>`;
  1406. }
  1407. if (!supportsDHCPClient(v)) {
  1408. return '';
  1409. }
  1410. 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>`;
  1411. })()}
  1412. <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>
  1413. <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>
  1414. </td>
  1415. </tr>
  1416. `;
  1417. }).join('')}
  1418. </tbody>
  1419. </table>
  1420. </div>
  1421. `}
  1422. </div>
  1423. `;
  1424. drawerRow.appendChild(drawerCell);
  1425. tbody.appendChild(drawerRow);
  1426. }
  1427. });
  1428. }
  1429. // Render VLANs Dedicated View
  1430. function renderVlansList() {
  1431. const tbody = document.getElementById('vlans-table-body');
  1432. if (!tbody) return;
  1433. const emptyState = document.getElementById('vlans-empty-state');
  1434. const countBadge = document.getElementById('vlans-table-count');
  1435. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1436. const allVlans = state.vlans || [];
  1437. if (countBadge) countBadge.innerText = allVlans.length;
  1438. const filtered = allVlans.filter(v => {
  1439. if (!query) return true;
  1440. return v.name.toLowerCase().includes(query) ||
  1441. String(v.vlan_id).includes(query) ||
  1442. (v.description || '').toLowerCase().includes(query) ||
  1443. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1444. });
  1445. if (allVlans.length === 0) {
  1446. emptyState.classList.remove('hidden');
  1447. tbody.innerHTML = '';
  1448. return;
  1449. }
  1450. emptyState.classList.add('hidden');
  1451. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1452. if (tbody.dataset.sig === sig) return;
  1453. tbody.dataset.sig = sig;
  1454. tbody.innerHTML = '';
  1455. filtered.forEach(v => {
  1456. const isUp = v.state === 'UP';
  1457. const tr = document.createElement('tr');
  1458. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1459. tr.innerHTML = `
  1460. <td class="py-3 px-4">
  1461. <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">
  1462. VLAN ${v.vlan_id}
  1463. </span>
  1464. </td>
  1465. <td class="py-3 px-4 font-bold text-white">
  1466. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1467. <span>${v.name}</span>
  1468. <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>
  1469. </span>
  1470. </td>
  1471. <td class="py-3 px-4 text-slate-300">
  1472. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1473. </td>
  1474. <td class="py-3 px-4 text-emerald-400 font-medium">
  1475. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1476. </td>
  1477. <td class="py-3 px-4 text-slate-300 font-sans">
  1478. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1479. </td>
  1480. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1481. <td class="py-3 px-4 font-sans">
  1482. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1483. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1484. 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'
  1485. }">
  1486. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1487. <span>${v.state}</span>
  1488. </button>
  1489. </td>
  1490. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1491. <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>
  1492. <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>
  1493. </td>
  1494. `;
  1495. tbody.appendChild(tr);
  1496. });
  1497. }
  1498. // Toggle interface UP / DOWN
  1499. async function toggleInterfaceState(name, newState) {
  1500. try {
  1501. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1502. method: 'POST',
  1503. headers: { 'Content-Type': 'application/json' },
  1504. body: JSON.stringify({ state: newState })
  1505. });
  1506. const data = await res.json();
  1507. if (res.ok) {
  1508. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1509. fetchData(false);
  1510. } else {
  1511. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1512. }
  1513. } catch (err) {
  1514. showToast('Error', err.message, 'error');
  1515. }
  1516. }
  1517. // ---------------- MikroTik Flag & Utilities ----------------
  1518. function renderMikroTikFlag(running, disabled) {
  1519. if (running) {
  1520. 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>`;
  1521. }
  1522. if (disabled) {
  1523. 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>`;
  1524. }
  1525. 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>`;
  1526. }
  1527. function copyToClipboard(text, label = 'Text') {
  1528. navigator.clipboard.writeText(text).then(() => {
  1529. showToast('Copied', `${label} copied to clipboard`, 'success');
  1530. }).catch(() => {
  1531. prompt('Copy value:', text);
  1532. });
  1533. }
  1534. // ======================== PPP Profiles Shared Helper ========================
  1535. async function fetchPPPProfilesList() {
  1536. try {
  1537. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1538. if (res.ok) {
  1539. state.pppProfiles = await res.json();
  1540. }
  1541. } catch (err) {
  1542. console.error('Failed to load PPP profiles:', err);
  1543. }
  1544. }
  1545. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1546. const sel = document.getElementById(selectId);
  1547. if (!sel) return;
  1548. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1549. { name: 'default', use_encryption: 'no' },
  1550. { name: 'default-encryption', use_encryption: 'required' }
  1551. ];
  1552. sel.innerHTML = '';
  1553. profiles.forEach(p => {
  1554. const opt = document.createElement('option');
  1555. opt.value = p.name;
  1556. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1557. opt.innerText = `${p.name}${encBadge}`;
  1558. sel.appendChild(opt);
  1559. });
  1560. if (selectedVal) {
  1561. sel.value = selectedVal;
  1562. } else {
  1563. sel.value = defaultVal;
  1564. }
  1565. if (!sel.value && sel.options.length > 0) {
  1566. sel.selectedIndex = 0;
  1567. }
  1568. }
  1569. // ======================== PPPoE Multi-Instance ========================
  1570. async function loadPPPoE(populateInputs = true) {
  1571. try {
  1572. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1573. await fetchPPPProfilesList();
  1574. }
  1575. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1576. const list = await res.json();
  1577. state.pppoeList = Array.isArray(list) ? list : [];
  1578. const badge = document.getElementById('pppoe-count-badge');
  1579. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1580. const tbody = document.getElementById('pppoe-table-body');
  1581. const empty = document.getElementById('pppoe-empty');
  1582. if (!tbody) return;
  1583. tbody.innerHTML = '';
  1584. if (state.pppoeList.length === 0) {
  1585. if (empty) empty.classList.remove('hidden');
  1586. } else {
  1587. if (empty) empty.classList.add('hidden');
  1588. state.pppoeList.forEach(inst => {
  1589. const tr = document.createElement('tr');
  1590. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1591. tr.innerHTML = `
  1592. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1593. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1594. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1595. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1596. <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>
  1597. <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>
  1598. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1599. <td class="py-2.5 px-3 text-center">
  1600. <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'}">
  1601. ${inst.default_route ? 'Yes' : 'No'}
  1602. </span>
  1603. </td>
  1604. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1605. ${inst.running ? `
  1606. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1607. ` : `
  1608. <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>
  1609. `}
  1610. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1611. ${inst.disabled ? 'Enable' : 'Disable'}
  1612. </button>
  1613. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1614. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1615. </td>
  1616. `;
  1617. tbody.appendChild(tr);
  1618. });
  1619. }
  1620. } catch (err) {
  1621. console.error('Failed to load PPPoE:', err);
  1622. }
  1623. }
  1624. function openAddPPPoEModal() {
  1625. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1626. document.getElementById('pppoe-modal-edit-orig').value = '';
  1627. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1628. document.getElementById('pppoe-modal-name').readOnly = false;
  1629. document.getElementById('pppoe-modal-user').value = '';
  1630. document.getElementById('pppoe-modal-pass').value = '';
  1631. document.getElementById('pppoe-modal-service').value = '';
  1632. document.getElementById('pppoe-modal-mtu').value = '1492';
  1633. document.getElementById('pppoe-modal-defroute').checked = true;
  1634. document.getElementById('pppoe-modal-reconnect').checked = true;
  1635. document.getElementById('pppoe-modal-disabled').checked = false;
  1636. // Populate profiles
  1637. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1638. // Populate interfaces
  1639. const sel = document.getElementById('pppoe-modal-iface');
  1640. sel.innerHTML = '';
  1641. (state.interfaces || []).forEach(i => {
  1642. if (i.name === 'lo') return;
  1643. const opt = document.createElement('option');
  1644. opt.value = i.name;
  1645. opt.innerText = `${i.name} (${i.role || i.type})`;
  1646. sel.appendChild(opt);
  1647. });
  1648. document.getElementById('pppoe-modal').classList.remove('hidden');
  1649. }
  1650. function openEditPPPoEModal(name) {
  1651. const inst = (state.pppoeList || []).find(i => i.name === name);
  1652. if (!inst) return;
  1653. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1654. document.getElementById('pppoe-modal-edit-orig').value = name;
  1655. document.getElementById('pppoe-modal-name').value = inst.name;
  1656. document.getElementById('pppoe-modal-name').readOnly = true;
  1657. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1658. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1659. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1660. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1661. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1662. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1663. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1664. // Populate profiles
  1665. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1666. const sel = document.getElementById('pppoe-modal-iface');
  1667. sel.innerHTML = '';
  1668. (state.interfaces || []).forEach(i => {
  1669. if (i.name === 'lo') return;
  1670. const opt = document.createElement('option');
  1671. opt.value = i.name;
  1672. opt.innerText = `${i.name} (${i.role || i.type})`;
  1673. if (i.name === inst.interface) opt.selected = true;
  1674. sel.appendChild(opt);
  1675. });
  1676. document.getElementById('pppoe-modal').classList.remove('hidden');
  1677. }
  1678. function closePPPoEModal() {
  1679. document.getElementById('pppoe-modal').classList.add('hidden');
  1680. }
  1681. async function submitSavePPPoE(e) {
  1682. e.preventDefault();
  1683. const name = document.getElementById('pppoe-modal-name').value.trim();
  1684. const iface = document.getElementById('pppoe-modal-iface').value;
  1685. const user = document.getElementById('pppoe-modal-user').value.trim();
  1686. const pass = document.getElementById('pppoe-modal-pass').value;
  1687. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1688. const service = document.getElementById('pppoe-modal-service').value.trim();
  1689. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1690. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1691. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1692. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1693. try {
  1694. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1695. method: 'POST',
  1696. headers: { 'Content-Type': 'application/json' },
  1697. body: JSON.stringify({
  1698. name,
  1699. interface: iface,
  1700. username: user,
  1701. password: pass,
  1702. profile: profile,
  1703. service_name: service,
  1704. mtu,
  1705. default_route: defRoute,
  1706. auto_reconnect: reconnect,
  1707. disabled
  1708. })
  1709. });
  1710. if (res.ok) {
  1711. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1712. closePPPoEModal();
  1713. loadPPPoE(false);
  1714. fetchData(false);
  1715. } else {
  1716. const err = await res.json();
  1717. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1718. }
  1719. } catch (err) {
  1720. showToast('Error', err.message, 'error');
  1721. }
  1722. }
  1723. async function connectPPPoEInstance(name) {
  1724. try {
  1725. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1726. if (res.ok) {
  1727. showToast('Connecting', `Dialing ${name}...`, 'info');
  1728. setTimeout(() => loadPPPoE(false), 2000);
  1729. }
  1730. } catch (err) {
  1731. showToast('Error', err.message, 'error');
  1732. }
  1733. }
  1734. async function disconnectPPPoEInstance(name) {
  1735. try {
  1736. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1737. if (res.ok) {
  1738. showToast('Disconnected', `${name} session terminated`, 'info');
  1739. setTimeout(() => loadPPPoE(false), 1000);
  1740. }
  1741. } catch (err) {
  1742. showToast('Error', err.message, 'error');
  1743. }
  1744. }
  1745. async function togglePPPoEState(name, enable) {
  1746. try {
  1747. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1748. method: 'POST',
  1749. headers: { 'Content-Type': 'application/json' },
  1750. body: JSON.stringify({ enabled: enable })
  1751. });
  1752. if (res.ok) {
  1753. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1754. loadPPPoE(false);
  1755. }
  1756. } catch (err) {
  1757. showToast('Error', err.message, 'error');
  1758. }
  1759. }
  1760. async function deletePPPoEInstance(name) {
  1761. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1762. try {
  1763. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1764. if (res.ok) {
  1765. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1766. loadPPPoE(false);
  1767. fetchData(false);
  1768. }
  1769. } catch (err) {
  1770. showToast('Error', err.message, 'error');
  1771. }
  1772. }
  1773. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1774. state.wgSubTab = 'ifaces';
  1775. function switchWGSubTab(tab) {
  1776. state.wgSubTab = tab;
  1777. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1778. const peersPanel = document.getElementById('wg-subtab-peers');
  1779. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1780. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1781. if (tab === 'ifaces') {
  1782. ifacesPanel?.classList.remove('hidden');
  1783. peersPanel?.classList.add('hidden');
  1784. 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';
  1785. 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';
  1786. } else {
  1787. ifacesPanel?.classList.add('hidden');
  1788. peersPanel?.classList.remove('hidden');
  1789. 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';
  1790. 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';
  1791. renderWGPeers();
  1792. }
  1793. }
  1794. async function loadWireGuard(populateInputs = true) {
  1795. try {
  1796. const [ifacesRes, peersRes] = await Promise.all([
  1797. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1798. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1799. ]);
  1800. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1801. const peers = peersRes.ok ? await peersRes.json() : [];
  1802. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1803. state.wgPeers = Array.isArray(peers) ? peers : [];
  1804. // Badges
  1805. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1806. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1807. const peersCountBadge = document.getElementById('wg-peers-count');
  1808. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1809. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1810. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1811. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1812. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1813. // Render Interfaces
  1814. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1815. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1816. if (ifacesTbody) {
  1817. ifacesTbody.innerHTML = '';
  1818. if (state.wgInterfaces.length === 0) {
  1819. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1820. } else {
  1821. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1822. state.wgInterfaces.forEach(iface => {
  1823. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1824. const tr = document.createElement('tr');
  1825. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1826. tr.innerHTML = `
  1827. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1828. <td class="py-2.5 px-3">
  1829. <div class="flex items-center gap-1.5">
  1830. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1831. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1832. </div>
  1833. </td>
  1834. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1835. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1836. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1837. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1838. ${(iface.public_key || '').substring(0, 10)}... 📋
  1839. </span>
  1840. </td>
  1841. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1842. <td class="py-2.5 px-3 text-center">
  1843. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1844. </td>
  1845. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1846. ${iface.running ? `
  1847. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1848. ` : `
  1849. <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>
  1850. `}
  1851. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1852. ${iface.disabled ? 'Enable' : 'Disable'}
  1853. </button>
  1854. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1855. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1856. </td>
  1857. `;
  1858. ifacesTbody.appendChild(tr);
  1859. });
  1860. }
  1861. }
  1862. // Populate filter dropdown in peers tab
  1863. const filterSel = document.getElementById('wg-peers-filter-iface');
  1864. if (filterSel) {
  1865. const currentVal = filterSel.value;
  1866. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1867. state.wgInterfaces.forEach(i => {
  1868. const opt = document.createElement('option');
  1869. opt.value = i.name;
  1870. opt.innerText = i.name;
  1871. if (i.name === currentVal) opt.selected = true;
  1872. filterSel.appendChild(opt);
  1873. });
  1874. }
  1875. renderWGPeers();
  1876. } catch (err) {
  1877. console.error('Failed to load WireGuard:', err);
  1878. }
  1879. }
  1880. function formatWGPeerEndpoint(address, port) {
  1881. if (!address || address === '(none)') return '--';
  1882. let addr = address.trim();
  1883. let p = port || 0;
  1884. while (addr.includes(':') && !addr.startsWith('[')) {
  1885. const lastColon = addr.lastIndexOf(':');
  1886. const maybePort = addr.substring(lastColon + 1);
  1887. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1888. if (!p) p = parseInt(maybePort, 10);
  1889. addr = addr.substring(0, lastColon);
  1890. } else {
  1891. break;
  1892. }
  1893. }
  1894. return p ? `${addr}:${p}` : addr;
  1895. }
  1896. function renderWGPeers() {
  1897. const filterSel = document.getElementById('wg-peers-filter-iface');
  1898. const selectedIface = filterSel ? filterSel.value : '';
  1899. const tbody = document.getElementById('wg-peers-table-body');
  1900. const empty = document.getElementById('wg-peers-empty');
  1901. if (!tbody) return;
  1902. tbody.innerHTML = '';
  1903. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1904. if (filtered.length === 0) {
  1905. if (empty) empty.classList.remove('hidden');
  1906. } else {
  1907. if (empty) empty.classList.add('hidden');
  1908. filtered.forEach(p => {
  1909. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1910. const tr = document.createElement('tr');
  1911. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1912. tr.innerHTML = `
  1913. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1914. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1915. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1916. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1917. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1918. ${(p.public_key || '').substring(0, 10)}... 📋
  1919. </span>
  1920. </td>
  1921. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1922. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1923. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1924. <td class="py-2.5 px-3 font-mono text-[11px]">
  1925. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1926. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1927. </td>
  1928. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1929. <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">
  1930. ${p.disabled ? 'Enable' : 'Disable'}
  1931. </button>
  1932. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1933. <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>
  1934. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1935. </td>
  1936. `;
  1937. tbody.appendChild(tr);
  1938. });
  1939. }
  1940. }
  1941. function openAddWGInterfaceModal() {
  1942. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1943. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1944. const nameEl = document.getElementById('wg-iface-modal-name');
  1945. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1946. nameEl.readOnly = false;
  1947. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1948. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1949. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1950. document.getElementById('wg-iface-modal-comment').value = '';
  1951. document.getElementById('wg-iface-modal-pubkey').value = '';
  1952. document.getElementById('wg-iface-modal-privkey').value = '';
  1953. document.getElementById('wg-iface-modal-disabled').checked = false;
  1954. generateWGInterfaceKeys();
  1955. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1956. }
  1957. function openEditWGInterfaceModal(name) {
  1958. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1959. if (!iface) return;
  1960. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1961. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1962. const nameEl = document.getElementById('wg-iface-modal-name');
  1963. nameEl.value = iface.name;
  1964. nameEl.readOnly = false; // ALLOW RENAMING
  1965. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1966. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1967. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1968. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1969. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1970. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1971. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1972. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1973. }
  1974. function closeAddWGInterfaceModal() {
  1975. document.getElementById('wg-iface-modal').classList.add('hidden');
  1976. }
  1977. async function generateWGInterfaceKeys() {
  1978. try {
  1979. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1980. const keys = await res.json();
  1981. if (res.ok) {
  1982. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1983. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1984. }
  1985. } catch (err) {
  1986. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1987. }
  1988. }
  1989. async function onWGInterfacePrivKeyInput() {
  1990. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1991. if (!privKey) return;
  1992. try {
  1993. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1994. method: 'POST',
  1995. headers: { 'Content-Type': 'application/json' },
  1996. body: JSON.stringify({ private_key: privKey })
  1997. });
  1998. if (res.ok) {
  1999. const data = await res.json();
  2000. if (data.public_key) {
  2001. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  2002. }
  2003. }
  2004. } catch (err) {
  2005. // Ignore while typing
  2006. }
  2007. }
  2008. function toggleWGPrivKeyVisibility() {
  2009. const el = document.getElementById('wg-iface-modal-privkey');
  2010. const btn = document.getElementById('btn-toggle-wg-privkey');
  2011. if (el.type === 'password') {
  2012. el.type = 'text';
  2013. btn.innerText = '🙈 Hide';
  2014. } else {
  2015. el.type = 'password';
  2016. btn.innerText = '👁️ Show';
  2017. }
  2018. }
  2019. function copyWGInterfacePubKey() {
  2020. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  2021. if (pub) copyToClipboard(pub, 'Interface Public Key');
  2022. }
  2023. async function submitSaveWGInterface(e) {
  2024. e.preventDefault();
  2025. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  2026. const name = document.getElementById('wg-iface-modal-name').value.trim();
  2027. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  2028. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  2029. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  2030. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  2031. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  2032. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  2033. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  2034. try {
  2035. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  2036. method: 'POST',
  2037. headers: { 'Content-Type': 'application/json' },
  2038. body: JSON.stringify({
  2039. orig_name: origName,
  2040. name,
  2041. listen_port: port,
  2042. address: addr,
  2043. mtu,
  2044. comment,
  2045. public_key: pub,
  2046. private_key: priv,
  2047. disabled
  2048. })
  2049. });
  2050. const data = await res.json();
  2051. if (res.ok) {
  2052. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  2053. closeAddWGInterfaceModal();
  2054. loadWireGuard(false);
  2055. fetchData(false);
  2056. } else {
  2057. showToast('Error', data.error || 'Failed to save interface', 'error');
  2058. }
  2059. } catch (err) {
  2060. showToast('Error', err.message, 'error');
  2061. }
  2062. }
  2063. async function startWGInterface(name) {
  2064. try {
  2065. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2066. if (res.ok) {
  2067. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2068. loadWireGuard(false);
  2069. fetchData(false);
  2070. }
  2071. } catch (err) {
  2072. showToast('Error', err.message, 'error');
  2073. }
  2074. }
  2075. async function stopWGInterface(name) {
  2076. try {
  2077. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2078. if (res.ok) {
  2079. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2080. loadWireGuard(false);
  2081. fetchData(false);
  2082. }
  2083. } catch (err) {
  2084. showToast('Error', err.message, 'error');
  2085. }
  2086. }
  2087. async function toggleWGInterfaceState(name, enable) {
  2088. try {
  2089. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2090. method: 'POST',
  2091. headers: { 'Content-Type': 'application/json' },
  2092. body: JSON.stringify({ enabled: enable })
  2093. });
  2094. if (res.ok) {
  2095. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2096. loadWireGuard(false);
  2097. fetchData(false);
  2098. }
  2099. } catch (err) {
  2100. showToast('Error', err.message, 'error');
  2101. }
  2102. }
  2103. async function deleteWGInterface(name) {
  2104. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2105. try {
  2106. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2107. if (res.ok) {
  2108. showToast('Deleted', `Interface ${name} removed`, 'success');
  2109. loadWireGuard(false);
  2110. fetchData(false);
  2111. }
  2112. } catch (err) {
  2113. showToast('Error', err.message, 'error');
  2114. }
  2115. }
  2116. function populateWGPeerIfaceSelect(selectedIface = '') {
  2117. const sel = document.getElementById('wg-peer-modal-iface');
  2118. if (!sel) return;
  2119. sel.innerHTML = '';
  2120. (state.wgInterfaces || []).forEach(i => {
  2121. const opt = document.createElement('option');
  2122. opt.value = i.name;
  2123. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2124. if (i.name === selectedIface) opt.selected = true;
  2125. sel.appendChild(opt);
  2126. });
  2127. }
  2128. function openAddWGPeerModal() {
  2129. if ((state.wgInterfaces || []).length === 0) {
  2130. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2131. openAddWGInterfaceModal();
  2132. return;
  2133. }
  2134. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2135. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2136. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2137. populateWGPeerIfaceSelect();
  2138. document.getElementById('wg-peer-modal-name').value = '';
  2139. document.getElementById('wg-peer-modal-pubkey').value = '';
  2140. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2141. document.getElementById('wg-peer-modal-endpoint').value = '';
  2142. document.getElementById('wg-peer-modal-port').value = '';
  2143. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2144. document.getElementById('wg-peer-modal-preshared').value = '';
  2145. document.getElementById('wg-peer-modal-disabled').checked = false;
  2146. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2147. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2148. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2149. }
  2150. function openEditWGPeerModal(ifaceName, pubKey) {
  2151. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2152. if (!peer) {
  2153. showToast('Not Found', 'Peer not found', 'warning');
  2154. return;
  2155. }
  2156. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2157. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2158. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2159. populateWGPeerIfaceSelect(peer.interface);
  2160. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2161. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2162. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2163. let epHost = (peer.endpoint_address || '').trim();
  2164. let epPort = peer.endpoint_port || '';
  2165. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2166. const lastColon = epHost.lastIndexOf(':');
  2167. const maybePort = epHost.substring(lastColon + 1);
  2168. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2169. if (!epPort) epPort = parseInt(maybePort, 10);
  2170. epHost = epHost.substring(0, lastColon);
  2171. } else {
  2172. break;
  2173. }
  2174. }
  2175. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2176. document.getElementById('wg-peer-modal-port').value = epPort;
  2177. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2178. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2179. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2180. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2181. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2182. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2183. }
  2184. function closeAddWGPeerModal() {
  2185. document.getElementById('wg-peer-modal').classList.add('hidden');
  2186. }
  2187. async function generatePeerKeypairHelper() {
  2188. try {
  2189. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2190. const keys = await res.json();
  2191. if (res.ok) {
  2192. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2193. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2194. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2195. checkWGPeerKeyValidity();
  2196. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2197. }
  2198. } catch (err) {
  2199. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2200. }
  2201. }
  2202. function copyGeneratedPeerPrivKey() {
  2203. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2204. if (priv) copyToClipboard(priv, 'Client Private Key');
  2205. }
  2206. async function generatePeerPSK() {
  2207. try {
  2208. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2209. const keys = await res.json();
  2210. if (res.ok && keys.private_key) {
  2211. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2212. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2213. }
  2214. } catch (err) {
  2215. showToast('Error', err.message, 'error');
  2216. }
  2217. }
  2218. function checkWGPeerKeyValidity() {
  2219. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2220. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2221. const warningEl = document.getElementById('wg-peer-key-warning');
  2222. if (!warningEl) return;
  2223. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2224. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2225. warningEl.classList.remove('hidden');
  2226. } else {
  2227. warningEl.classList.add('hidden');
  2228. }
  2229. }
  2230. async function submitSaveWGPeer(e) {
  2231. e.preventDefault();
  2232. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2233. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2234. const iface = document.getElementById('wg-peer-modal-iface').value;
  2235. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2236. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2237. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2238. .split(',')
  2239. .map(s => s.trim())
  2240. .filter(s => s.length > 0);
  2241. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2242. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2243. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2244. const lastColon = epHost.lastIndexOf(':');
  2245. const maybePort = epHost.substring(lastColon + 1);
  2246. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2247. if (!epPort) epPort = parseInt(maybePort, 10);
  2248. epHost = epHost.substring(0, lastColon);
  2249. } else {
  2250. break;
  2251. }
  2252. }
  2253. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2254. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2255. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2256. // Validation
  2257. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2258. if (targetIface && targetIface.public_key === pub) {
  2259. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2260. return;
  2261. }
  2262. try {
  2263. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2264. method: 'POST',
  2265. headers: { 'Content-Type': 'application/json' },
  2266. body: JSON.stringify({
  2267. orig_interface: origIface,
  2268. orig_public_key: origPubKey,
  2269. interface: iface,
  2270. name,
  2271. public_key: pub,
  2272. allowed_ips: allowed,
  2273. endpoint_address: epHost,
  2274. endpoint_port: epPort,
  2275. persistent_keepalive: keepalive,
  2276. preshared_key: psk,
  2277. disabled
  2278. })
  2279. });
  2280. const data = await res.json();
  2281. if (res.ok) {
  2282. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2283. closeAddWGPeerModal();
  2284. loadWireGuard(false);
  2285. } else {
  2286. showToast('Error', data.error || 'Failed to save peer', 'error');
  2287. }
  2288. } catch (err) {
  2289. showToast('Error', err.message, 'error');
  2290. }
  2291. }
  2292. async function toggleWGPeerState(iface, pubkey, enable) {
  2293. try {
  2294. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2295. method: 'POST',
  2296. headers: { 'Content-Type': 'application/json' },
  2297. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2298. });
  2299. const data = await res.json();
  2300. if (res.ok) {
  2301. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2302. loadWireGuard(false);
  2303. } else {
  2304. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2305. }
  2306. } catch (err) {
  2307. showToast('Error', err.message, 'error');
  2308. }
  2309. }
  2310. async function deleteWGPeer(iface, pubkey) {
  2311. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2312. try {
  2313. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2314. method: 'POST',
  2315. headers: { 'Content-Type': 'application/json' },
  2316. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2317. });
  2318. const data = await res.json();
  2319. if (res.ok) {
  2320. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2321. loadWireGuard(false);
  2322. } else {
  2323. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2324. }
  2325. } catch (err) {
  2326. showToast('Error', err.message, 'error');
  2327. }
  2328. }
  2329. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2330. function switchIpsecModalTab(tab) {
  2331. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2332. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2333. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2334. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2335. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2336. if (tab === 'p1') {
  2337. if (p1Tab) {
  2338. 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';
  2339. }
  2340. if (p2Tab) {
  2341. 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';
  2342. }
  2343. if (p1Content) p1Content.classList.remove('hidden');
  2344. if (p2Content) p2Content.classList.add('hidden');
  2345. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2346. } else {
  2347. if (p1Tab) {
  2348. 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';
  2349. }
  2350. if (p2Tab) {
  2351. 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';
  2352. }
  2353. if (p1Content) p1Content.classList.add('hidden');
  2354. if (p2Content) p2Content.classList.remove('hidden');
  2355. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2356. }
  2357. }
  2358. function toggleIpsecPhaseStep() {
  2359. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2360. if (p1Content && !p1Content.classList.contains('hidden')) {
  2361. switchIpsecModalTab('p2');
  2362. } else {
  2363. switchIpsecModalTab('p1');
  2364. }
  2365. }
  2366. function toggleIpsecPskVisibility() {
  2367. const pskInput = document.getElementById('ipsec-modal-psk');
  2368. if (!pskInput) return;
  2369. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2370. }
  2371. function addIpsecLocalSubnet(val = '') {
  2372. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2373. if (!container) return;
  2374. const row = document.createElement('div');
  2375. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2376. row.innerHTML = `
  2377. <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">
  2378. <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>
  2379. `;
  2380. container.appendChild(row);
  2381. }
  2382. function addIpsecRemoteSubnet(val = '') {
  2383. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2384. if (!container) return;
  2385. const row = document.createElement('div');
  2386. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2387. row.innerHTML = `
  2388. <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">
  2389. <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>
  2390. `;
  2391. container.appendChild(row);
  2392. }
  2393. function updateIpsecEspProposalFromPFS(val) {
  2394. const prop = document.getElementById('ipsec-modal-espprop');
  2395. if (!prop) return;
  2396. if (val === 'none') {
  2397. prop.value = 'aes256-sha256,aes128-sha256,default';
  2398. } else {
  2399. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2400. }
  2401. }
  2402. function updateIpsecIkeProposalFromDH(dh) {
  2403. const el = document.getElementById('ipsec-modal-ikeprop');
  2404. if (el) {
  2405. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2406. }
  2407. }
  2408. function safeSetVal(id, val) {
  2409. const el = document.getElementById(id);
  2410. if (el) el.value = val;
  2411. }
  2412. function safeSetChecked(id, val) {
  2413. const el = document.getElementById(id);
  2414. if (el) el.checked = !!val;
  2415. }
  2416. function safeGetVal(id, def = '') {
  2417. const el = document.getElementById(id);
  2418. return el ? el.value : def;
  2419. }
  2420. async function loadIPSec(populateInputs = true) {
  2421. try {
  2422. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2423. const list = await res.json();
  2424. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2425. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2426. const badge = document.getElementById('ipsec-sas-badge');
  2427. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2428. const tbody = document.getElementById('ipsec-table-body');
  2429. const empty = document.getElementById('ipsec-empty');
  2430. if (!tbody) return;
  2431. tbody.innerHTML = '';
  2432. if (state.ipsecTunnels.length === 0) {
  2433. if (empty) empty.classList.remove('hidden');
  2434. } else {
  2435. if (empty) empty.classList.add('hidden');
  2436. state.ipsecTunnels.forEach(c => {
  2437. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2438. const tr = document.createElement('tr');
  2439. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2440. // Local subnets tags
  2441. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2442. 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('');
  2443. // Remote subnets tags
  2444. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2445. 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('');
  2446. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2447. const p2Name = c.phase2_name || `${c.name}_p2`;
  2448. tr.innerHTML = `
  2449. <td class="py-2.5 px-3 text-center">
  2450. ${isEstablished ? `
  2451. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2452. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2453. <span>UP</span>
  2454. </span>
  2455. ` : (c.disabled ? `
  2456. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2457. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2458. <span>DOWN</span>
  2459. </span>
  2460. ` : `
  2461. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2462. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2463. <span>IDLE</span>
  2464. </span>
  2465. `)}
  2466. </td>
  2467. <td class="py-2.5 px-4 font-bold text-white">
  2468. <div class="flex items-center gap-2">
  2469. <span class="text-amber-400">🛡</span>
  2470. <div>
  2471. <div>${escapeHtml(c.name)}</div>
  2472. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2473. </div>
  2474. </div>
  2475. </td>
  2476. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2477. <td class="py-2.5 px-4 font-sans">
  2478. <div class="flex items-center gap-1.5">
  2479. <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>
  2480. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2481. </div>
  2482. </td>
  2483. <td class="py-2.5 px-4">
  2484. <div class="space-y-1">
  2485. <div class="flex items-center flex-wrap gap-1">
  2486. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2487. ${localBadges}
  2488. </div>
  2489. <div class="flex items-center flex-wrap gap-1">
  2490. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2491. ${remoteBadges}
  2492. </div>
  2493. </div>
  2494. </td>
  2495. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2496. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2497. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2498. </div>
  2499. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2500. </td>
  2501. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2502. ${isEstablished ? `
  2503. <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>
  2504. ` : `
  2505. <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>
  2506. `}
  2507. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2508. ${c.disabled ? 'Enable' : 'Disable'}
  2509. </button>
  2510. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2511. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2512. </td>
  2513. `;
  2514. tbody.appendChild(tr);
  2515. });
  2516. }
  2517. } catch (err) {
  2518. console.error('Failed to load IPSec:', err);
  2519. }
  2520. }
  2521. function openAddIPSecModal() {
  2522. const modal = document.getElementById('ipsec-modal');
  2523. if (!modal) return;
  2524. const title = document.getElementById('ipsec-modal-title');
  2525. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2526. // Phase 1 Fields
  2527. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2528. const nameEl = document.getElementById('ipsec-modal-name');
  2529. if (nameEl) nameEl.readOnly = false;
  2530. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2531. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2532. safeSetVal('ipsec-modal-remotegw', '');
  2533. safeSetVal('ipsec-modal-localaddrs', '');
  2534. safeSetVal('ipsec-modal-comments', '');
  2535. safeSetVal('ipsec-modal-psk', '');
  2536. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2537. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2538. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2539. safeSetVal('ipsec-modal-localid', '');
  2540. safeSetVal('ipsec-modal-remoteid', '');
  2541. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2542. // Phase 2 Fields
  2543. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2544. safeSetVal('ipsec-modal-espkeylife', '28800');
  2545. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2546. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2547. safeSetChecked('ipsec-modal-autostart', true);
  2548. safeSetChecked('ipsec-modal-disabled', false);
  2549. // Clear & Populate default dynamic subnets
  2550. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2551. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2552. if (localContainer) {
  2553. localContainer.innerHTML = '';
  2554. addIpsecLocalSubnet('192.168.10.0/24');
  2555. }
  2556. if (remoteContainer) {
  2557. remoteContainer.innerHTML = '';
  2558. addIpsecRemoteSubnet('192.168.20.0/24');
  2559. }
  2560. switchIpsecModalTab('p1');
  2561. modal.classList.remove('hidden');
  2562. }
  2563. function openEditIPSecModal(name) {
  2564. const modal = document.getElementById('ipsec-modal');
  2565. if (!modal) return;
  2566. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2567. if (!conn) return;
  2568. const title = document.getElementById('ipsec-modal-title');
  2569. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2570. // Phase 1 Fields
  2571. safeSetVal('ipsec-modal-name', conn.name);
  2572. const nameEl = document.getElementById('ipsec-modal-name');
  2573. if (nameEl) nameEl.readOnly = true;
  2574. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2575. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2576. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2577. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2578. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2579. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2580. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2581. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2582. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2583. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2584. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2585. // Phase 2 Fields
  2586. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2587. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2588. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2589. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2590. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2591. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2592. // Populate dynamic subnets
  2593. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2594. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2595. if (localContainer) {
  2596. localContainer.innerHTML = '';
  2597. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2598. locals.forEach(s => addIpsecLocalSubnet(s));
  2599. }
  2600. if (remoteContainer) {
  2601. remoteContainer.innerHTML = '';
  2602. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2603. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2604. }
  2605. switchIpsecModalTab('p1');
  2606. modal.classList.remove('hidden');
  2607. }
  2608. function closeAddIPSecModal() {
  2609. const modal = document.getElementById('ipsec-modal');
  2610. if (modal) modal.classList.add('hidden');
  2611. }
  2612. async function submitSaveIPSec(e) {
  2613. if (e) e.preventDefault();
  2614. const name = safeGetVal('ipsec-modal-name').trim();
  2615. if (!name) {
  2616. showToast('Error', 'Tunnel name is required', 'error');
  2617. return;
  2618. }
  2619. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2620. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2621. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2622. const comments = safeGetVal('ipsec-modal-comments').trim();
  2623. const psk = safeGetVal('ipsec-modal-psk');
  2624. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2625. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2626. const localId = safeGetVal('ipsec-modal-localid').trim();
  2627. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2628. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2629. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2630. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2631. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2632. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2633. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2634. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2635. // Scrape dynamic local and remote subnets
  2636. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2637. const localSubnets = [];
  2638. localInputs.forEach(inp => {
  2639. const v = inp.value.trim();
  2640. if (v) localSubnets.push(v);
  2641. });
  2642. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2643. const remoteSubnets = [];
  2644. remoteInputs.forEach(inp => {
  2645. const v = inp.value.trim();
  2646. if (v) remoteSubnets.push(v);
  2647. });
  2648. try {
  2649. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2650. method: 'POST',
  2651. headers: { 'Content-Type': 'application/json' },
  2652. body: JSON.stringify({
  2653. name,
  2654. comment: comments,
  2655. ike_version: ikeVersion,
  2656. local_addrs: localAddrs,
  2657. remote_addrs: remotegw,
  2658. preshared_key: psk,
  2659. ike_proposals: ikeProposals,
  2660. ike_keylife: ikeKeylife,
  2661. local_id: localId,
  2662. remote_id: remoteId,
  2663. dpd: dpd,
  2664. phase2_name: phase2Name,
  2665. esp_proposals: espProposals,
  2666. esp_keylife: espKeylife,
  2667. pfs_group: pfsGroup,
  2668. pfs: pfsGroup !== 'none',
  2669. local_subnets: localSubnets,
  2670. remote_subnets: remoteSubnets,
  2671. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2672. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2673. auto_start: autostart,
  2674. disabled
  2675. })
  2676. });
  2677. if (res.ok) {
  2678. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2679. closeAddIPSecModal();
  2680. loadIPSec(false);
  2681. } else {
  2682. const err = await res.json();
  2683. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2684. }
  2685. } catch (err) {
  2686. showToast('Error', err.message, 'error');
  2687. }
  2688. }
  2689. async function startIPSecTunnel(name) {
  2690. try {
  2691. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2692. if (res.ok) {
  2693. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2694. setTimeout(() => loadIPSec(false), 2000);
  2695. }
  2696. } catch (err) {
  2697. showToast('Error', err.message, 'error');
  2698. }
  2699. }
  2700. async function stopIPSecTunnel(name) {
  2701. try {
  2702. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2703. if (res.ok) {
  2704. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2705. loadIPSec(false);
  2706. }
  2707. } catch (err) {
  2708. showToast('Error', err.message, 'error');
  2709. }
  2710. }
  2711. async function toggleIPSecState(name, enable) {
  2712. try {
  2713. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2714. method: 'POST',
  2715. headers: { 'Content-Type': 'application/json' },
  2716. body: JSON.stringify({ enabled: enable })
  2717. });
  2718. if (res.ok) {
  2719. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2720. loadIPSec(false);
  2721. }
  2722. } catch (err) {
  2723. showToast('Error', err.message, 'error');
  2724. }
  2725. }
  2726. async function deleteIPSecConn(name) {
  2727. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2728. try {
  2729. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2730. if (res.ok) {
  2731. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2732. loadIPSec(false);
  2733. fetchData(false);
  2734. }
  2735. } catch (err) {
  2736. showToast('Error', err.message, 'error');
  2737. }
  2738. }
  2739. // ======================== L2TP Multi-Instance ========================
  2740. async function loadL2TP(populateInputs = true) {
  2741. try {
  2742. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2743. await fetchPPPProfilesList();
  2744. }
  2745. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2746. const list = await res.json();
  2747. state.l2tpList = Array.isArray(list) ? list : [];
  2748. const badge = document.getElementById('l2tp-count-badge');
  2749. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2750. const tbody = document.getElementById('l2tp-table-body');
  2751. const empty = document.getElementById('l2tp-empty');
  2752. if (!tbody) return;
  2753. tbody.innerHTML = '';
  2754. if (state.l2tpList.length === 0) {
  2755. if (empty) empty.classList.remove('hidden');
  2756. } else {
  2757. if (empty) empty.classList.add('hidden');
  2758. state.l2tpList.forEach(inst => {
  2759. const tr = document.createElement('tr');
  2760. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2761. tr.innerHTML = `
  2762. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2763. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2764. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2765. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2766. <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>
  2767. <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>
  2768. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2769. <td class="py-2.5 px-3 text-center">
  2770. <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'}">
  2771. ${inst.default_route ? 'Yes' : 'No'}
  2772. </span>
  2773. </td>
  2774. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2775. ${inst.running ? `
  2776. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2777. ` : `
  2778. <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>
  2779. `}
  2780. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2781. ${inst.disabled ? 'Enable' : 'Disable'}
  2782. </button>
  2783. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2784. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2785. </td>
  2786. `;
  2787. tbody.appendChild(tr);
  2788. });
  2789. }
  2790. } catch (err) {
  2791. console.error('Failed to load L2TP:', err);
  2792. }
  2793. }
  2794. async function openAddL2TPModal() {
  2795. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2796. await fetchPPPProfilesList();
  2797. }
  2798. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2799. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2800. document.getElementById('l2tp-modal-name').readOnly = false;
  2801. document.getElementById('l2tp-modal-server').value = '';
  2802. document.getElementById('l2tp-modal-user').value = '';
  2803. document.getElementById('l2tp-modal-pass').value = '';
  2804. document.getElementById('l2tp-modal-ipsec').value = '';
  2805. document.getElementById('l2tp-modal-defroute').checked = true;
  2806. document.getElementById('l2tp-modal-disabled').checked = false;
  2807. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2808. document.getElementById('l2tp-modal').classList.remove('hidden');
  2809. }
  2810. async function openEditL2TPModal(name) {
  2811. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2812. await fetchPPPProfilesList();
  2813. }
  2814. const inst = (state.l2tpList || []).find(i => i.name === name);
  2815. if (!inst) return;
  2816. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2817. document.getElementById('l2tp-modal-name').value = inst.name;
  2818. document.getElementById('l2tp-modal-name').readOnly = true;
  2819. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2820. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2821. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2822. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2823. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2824. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2825. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2826. document.getElementById('l2tp-modal').classList.remove('hidden');
  2827. }
  2828. function closeL2TPModal() {
  2829. document.getElementById('l2tp-modal').classList.add('hidden');
  2830. }
  2831. async function submitSaveL2TP(e) {
  2832. e.preventDefault();
  2833. const name = document.getElementById('l2tp-modal-name').value.trim();
  2834. const server = document.getElementById('l2tp-modal-server').value.trim();
  2835. const user = document.getElementById('l2tp-modal-user').value.trim();
  2836. const pass = document.getElementById('l2tp-modal-pass').value;
  2837. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2838. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2839. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2840. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2841. try {
  2842. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2843. method: 'POST',
  2844. headers: { 'Content-Type': 'application/json' },
  2845. body: JSON.stringify({
  2846. name,
  2847. connect_to: server,
  2848. username: user,
  2849. password: pass,
  2850. profile: profile,
  2851. ipsec_secret: ipsec,
  2852. default_route: defRoute,
  2853. disabled
  2854. })
  2855. });
  2856. if (res.ok) {
  2857. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2858. closeL2TPModal();
  2859. loadL2TP(false);
  2860. fetchData(false);
  2861. }
  2862. } catch (err) {
  2863. showToast('Error', err.message, 'error');
  2864. }
  2865. }
  2866. async function connectL2TPInstance(name) {
  2867. try {
  2868. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2869. if (res.ok) {
  2870. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2871. setTimeout(() => loadL2TP(false), 2000);
  2872. }
  2873. } catch (err) {
  2874. showToast('Error', err.message, 'error');
  2875. }
  2876. }
  2877. async function disconnectL2TPInstance(name) {
  2878. try {
  2879. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2880. if (res.ok) {
  2881. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2882. loadL2TP(false);
  2883. }
  2884. } catch (err) {
  2885. showToast('Error', err.message, 'error');
  2886. }
  2887. }
  2888. async function toggleL2TPState(name, enable) {
  2889. try {
  2890. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2891. method: 'POST',
  2892. headers: { 'Content-Type': 'application/json' },
  2893. body: JSON.stringify({ enabled: enable })
  2894. });
  2895. if (res.ok) {
  2896. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2897. loadL2TP(false);
  2898. }
  2899. } catch (err) {
  2900. showToast('Error', err.message, 'error');
  2901. }
  2902. }
  2903. async function deleteL2TPInstance(name) {
  2904. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2905. try {
  2906. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2907. if (res.ok) {
  2908. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2909. loadL2TP(false);
  2910. fetchData(false);
  2911. }
  2912. } catch (err) {
  2913. showToast('Error', err.message, 'error');
  2914. }
  2915. }
  2916. // ======================== PPTP Multi-Instance ========================
  2917. async function loadPPTP(populateInputs = true) {
  2918. try {
  2919. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2920. await fetchPPPProfilesList();
  2921. }
  2922. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2923. const list = await res.json();
  2924. state.pptpList = Array.isArray(list) ? list : [];
  2925. const badge = document.getElementById('pptp-count-badge');
  2926. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2927. const tbody = document.getElementById('pptp-table-body');
  2928. const empty = document.getElementById('pptp-empty');
  2929. if (!tbody) return;
  2930. tbody.innerHTML = '';
  2931. if (state.pptpList.length === 0) {
  2932. if (empty) empty.classList.remove('hidden');
  2933. } else {
  2934. if (empty) empty.classList.add('hidden');
  2935. state.pptpList.forEach(inst => {
  2936. const tr = document.createElement('tr');
  2937. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2938. tr.innerHTML = `
  2939. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2940. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2941. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2942. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2943. <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>
  2944. <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>
  2945. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2946. <td class="py-2.5 px-3 text-center">
  2947. <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'}">
  2948. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2949. </span>
  2950. </td>
  2951. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2952. ${inst.running ? `
  2953. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2954. ` : `
  2955. <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>
  2956. `}
  2957. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2958. ${inst.disabled ? 'Enable' : 'Disable'}
  2959. </button>
  2960. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2961. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2962. </td>
  2963. `;
  2964. tbody.appendChild(tr);
  2965. });
  2966. }
  2967. } catch (err) {
  2968. console.error('Failed to load PPTP:', err);
  2969. }
  2970. }
  2971. async function openAddPPTPModal() {
  2972. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2973. await fetchPPPProfilesList();
  2974. }
  2975. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2976. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2977. document.getElementById('pptp-modal-name').readOnly = false;
  2978. document.getElementById('pptp-modal-server').value = '';
  2979. document.getElementById('pptp-modal-user').value = '';
  2980. document.getElementById('pptp-modal-pass').value = '';
  2981. document.getElementById('pptp-modal-mppe').checked = true;
  2982. document.getElementById('pptp-modal-defroute').checked = true;
  2983. document.getElementById('pptp-modal-disabled').checked = false;
  2984. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2985. document.getElementById('pptp-modal').classList.remove('hidden');
  2986. }
  2987. async function openEditPPTPModal(name) {
  2988. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2989. await fetchPPPProfilesList();
  2990. }
  2991. const inst = (state.pptpList || []).find(i => i.name === name);
  2992. if (!inst) return;
  2993. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2994. document.getElementById('pptp-modal-name').value = inst.name;
  2995. document.getElementById('pptp-modal-name').readOnly = true;
  2996. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2997. document.getElementById('pptp-modal-user').value = inst.username || '';
  2998. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2999. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  3000. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  3001. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  3002. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  3003. document.getElementById('pptp-modal').classList.remove('hidden');
  3004. }
  3005. function closePPTPModal() {
  3006. document.getElementById('pptp-modal').classList.add('hidden');
  3007. }
  3008. async function submitSavePPTP(e) {
  3009. e.preventDefault();
  3010. const name = document.getElementById('pptp-modal-name').value.trim();
  3011. const server = document.getElementById('pptp-modal-server').value.trim();
  3012. const user = document.getElementById('pptp-modal-user').value.trim();
  3013. const pass = document.getElementById('pptp-modal-pass').value;
  3014. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  3015. const mppe = document.getElementById('pptp-modal-mppe').checked;
  3016. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  3017. const disabled = document.getElementById('pptp-modal-disabled').checked;
  3018. try {
  3019. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  3020. method: 'POST',
  3021. headers: { 'Content-Type': 'application/json' },
  3022. body: JSON.stringify({
  3023. name,
  3024. connect_to: server,
  3025. username: user,
  3026. password: pass,
  3027. profile: profile,
  3028. require_mppe: mppe,
  3029. default_route: defRoute,
  3030. auto_reconnect: true,
  3031. disabled
  3032. })
  3033. });
  3034. if (res.ok) {
  3035. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  3036. closePPTPModal();
  3037. loadPPTP(false);
  3038. fetchData(false);
  3039. }
  3040. } catch (err) {
  3041. showToast('Error', err.message, 'error');
  3042. }
  3043. }
  3044. async function connectPPTPInstance(name) {
  3045. try {
  3046. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  3047. if (res.ok) {
  3048. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  3049. setTimeout(() => loadPPTP(false), 2000);
  3050. }
  3051. } catch (err) {
  3052. showToast('Error', err.message, 'error');
  3053. }
  3054. }
  3055. async function disconnectPPTPInstance(name) {
  3056. try {
  3057. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3058. if (res.ok) {
  3059. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3060. loadPPTP(false);
  3061. }
  3062. } catch (err) {
  3063. showToast('Error', err.message, 'error');
  3064. }
  3065. }
  3066. async function togglePPTPState(name, enable) {
  3067. try {
  3068. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3069. method: 'POST',
  3070. headers: { 'Content-Type': 'application/json' },
  3071. body: JSON.stringify({ enabled: enable })
  3072. });
  3073. if (res.ok) {
  3074. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3075. loadPPTP(false);
  3076. }
  3077. } catch (err) {
  3078. showToast('Error', err.message, 'error');
  3079. }
  3080. }
  3081. async function deletePPTPInstance(name) {
  3082. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3083. try {
  3084. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3085. if (res.ok) {
  3086. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3087. loadPPTP(false);
  3088. fetchData(false);
  3089. }
  3090. } catch (err) {
  3091. showToast('Error', err.message, 'error');
  3092. }
  3093. }
  3094. // ---------------- Modal & Helper Functions ----------------
  3095. function openVlanModal(defaultParent = '') {
  3096. const select = document.getElementById('vlan-parent');
  3097. select.innerHTML = '';
  3098. const allIfaces = state.interfaces || [];
  3099. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3100. if (eligible.length === 0) {
  3101. const opt = document.createElement('option');
  3102. opt.value = '';
  3103. opt.innerText = 'No VLAN-capable interfaces available';
  3104. select.appendChild(opt);
  3105. } else {
  3106. eligible.forEach(i => {
  3107. const opt = document.createElement('option');
  3108. opt.value = i.name;
  3109. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3110. if (i.name === defaultParent) opt.selected = true;
  3111. select.appendChild(opt);
  3112. });
  3113. }
  3114. document.getElementById('vlan-id').value = '';
  3115. document.getElementById('vlan-name').value = '';
  3116. document.getElementById('vlan-ip').value = '';
  3117. document.getElementById('vlan-desc').value = '';
  3118. populateRoleSelects('LAN');
  3119. autoSuggestVlanName();
  3120. document.getElementById('vlan-modal').classList.remove('hidden');
  3121. }
  3122. function closeVlanModal() {
  3123. document.getElementById('vlan-modal').classList.add('hidden');
  3124. }
  3125. function autoSuggestVlanName() {
  3126. const parent = document.getElementById('vlan-parent').value;
  3127. if (!parent) return;
  3128. const id = document.getElementById('vlan-id').value;
  3129. const nameInput = document.getElementById('vlan-name');
  3130. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3131. }
  3132. function setSubnetPreset(cidr) {
  3133. const ipInput = document.getElementById('vlan-ip');
  3134. const id = document.getElementById('vlan-id').value || '10';
  3135. ipInput.value = `192.168.${id}.1${cidr}`;
  3136. }
  3137. async function submitCreateVlan(e) {
  3138. e.preventDefault();
  3139. const btn = document.getElementById('vlan-submit-btn');
  3140. btn.disabled = true;
  3141. btn.innerText = 'Creating...';
  3142. const parent = document.getElementById('vlan-parent').value;
  3143. if (!parent) {
  3144. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3145. btn.disabled = false;
  3146. btn.innerText = 'Create VLAN';
  3147. return;
  3148. }
  3149. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3150. const name = document.getElementById('vlan-name').value.trim();
  3151. const ip = document.getElementById('vlan-ip').value.trim();
  3152. const role = document.getElementById('vlan-role').value;
  3153. const desc = document.getElementById('vlan-desc').value.trim();
  3154. try {
  3155. const res = await fetch(`${API_BASE}/vlans`, {
  3156. method: 'POST',
  3157. headers: { 'Content-Type': 'application/json' },
  3158. body: JSON.stringify({
  3159. parent_name: parent,
  3160. vlan_id: id,
  3161. name: name,
  3162. ip_address: ip,
  3163. role: role,
  3164. description: desc,
  3165. mtu: 1500,
  3166. auto_up: true
  3167. })
  3168. });
  3169. const data = await res.json();
  3170. if (res.ok) {
  3171. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3172. state.expandedParents.add(parent);
  3173. closeVlanModal();
  3174. await fetchData(true);
  3175. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3176. } else {
  3177. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3178. }
  3179. } catch (err) {
  3180. showToast('Error', err.message, 'error');
  3181. } finally {
  3182. btn.disabled = false;
  3183. btn.innerText = 'Create VLAN';
  3184. }
  3185. }
  3186. async function confirmDeleteVlan(name) {
  3187. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3188. try {
  3189. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3190. if (res.ok) {
  3191. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3192. closeIfaceModal();
  3193. fetchData(true);
  3194. }
  3195. } catch (err) {
  3196. showToast('Error', err.message, 'error');
  3197. }
  3198. }
  3199. function openIfaceModal(name) {
  3200. const iface = (state.interfaces || []).find(i => i.name === name);
  3201. if (!iface) return;
  3202. state.currentModalIface = iface.name;
  3203. document.getElementById('modal-iface-name').innerText = iface.name;
  3204. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3205. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3206. populateRoleSelects(iface.role || 'LAN');
  3207. document.getElementById('modal-iface-desc').value = iface.description || '';
  3208. const nameInput = document.getElementById('modal-iface-new-name');
  3209. const renameBtn = document.getElementById('modal-btn-rename');
  3210. const renameHelp = document.getElementById('modal-iface-rename-help');
  3211. if (nameInput) {
  3212. nameInput.value = iface.name;
  3213. if (iface.name === 'lo' || iface.type === 'loopback') {
  3214. nameInput.disabled = true;
  3215. if (renameBtn) renameBtn.disabled = true;
  3216. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3217. } else {
  3218. nameInput.disabled = false;
  3219. if (renameBtn) renameBtn.disabled = false;
  3220. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3221. }
  3222. }
  3223. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3224. if (iface.is_vlan) {
  3225. delBtn.classList.remove('hidden');
  3226. } else {
  3227. delBtn.classList.add('hidden');
  3228. }
  3229. renderModalIPs(iface);
  3230. document.getElementById('iface-modal').classList.remove('hidden');
  3231. }
  3232. function renderModalIPs(iface) {
  3233. const container = document.getElementById('modal-ip-list');
  3234. container.innerHTML = '';
  3235. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3236. if (addrs.length === 0) {
  3237. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3238. return;
  3239. }
  3240. addrs.forEach(addr => {
  3241. const row = document.createElement('div');
  3242. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3243. row.innerHTML = `
  3244. <span class="text-white">${addr}</span>
  3245. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3246. `;
  3247. container.appendChild(row);
  3248. });
  3249. }
  3250. function closeIfaceModal() {
  3251. document.getElementById('iface-modal').classList.add('hidden');
  3252. state.currentModalIface = null;
  3253. }
  3254. async function setIfaceState(name, newState) {
  3255. const target = name || state.currentModalIface;
  3256. if (!target) return;
  3257. await toggleInterfaceState(target, newState);
  3258. const updated = (state.interfaces || []).find(i => i.name === target);
  3259. if (updated) openIfaceModal(target);
  3260. }
  3261. async function applyMTU() {
  3262. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3263. try {
  3264. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3265. method: 'POST',
  3266. headers: { 'Content-Type': 'application/json' },
  3267. body: JSON.stringify({ mtu })
  3268. });
  3269. if (res.ok) {
  3270. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3271. fetchData(false);
  3272. }
  3273. } catch (err) {
  3274. showToast('Error', err.message, 'error');
  3275. }
  3276. }
  3277. async function addInterfaceIP() {
  3278. const ip = document.getElementById('modal-new-ip').value.trim();
  3279. if (!ip) return;
  3280. try {
  3281. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3282. method: 'POST',
  3283. headers: { 'Content-Type': 'application/json' },
  3284. body: JSON.stringify({ ip })
  3285. });
  3286. if (res.ok) {
  3287. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3288. document.getElementById('modal-new-ip').value = '';
  3289. await fetchData(false);
  3290. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3291. if (iface) renderModalIPs(iface);
  3292. } else {
  3293. const err = await res.json();
  3294. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3295. }
  3296. } catch (err) {
  3297. showToast('Error', err.message, 'error');
  3298. }
  3299. }
  3300. async function removeInterfaceIP(ip) {
  3301. if (!confirm(`Remove IP ${ip}?`)) return;
  3302. try {
  3303. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3304. method: 'DELETE',
  3305. headers: { 'Content-Type': 'application/json' },
  3306. body: JSON.stringify({ ip })
  3307. });
  3308. if (res.ok) {
  3309. showToast('IP Removed', `Removed ${ip}`, 'success');
  3310. await fetchData(false);
  3311. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3312. if (iface) renderModalIPs(iface);
  3313. }
  3314. } catch (err) {
  3315. showToast('Error', err.message, 'error');
  3316. }
  3317. }
  3318. async function renameInterface() {
  3319. const oldName = state.currentModalIface;
  3320. const newNameInput = document.getElementById('modal-iface-new-name');
  3321. const newName = (newNameInput?.value || '').trim();
  3322. if (!oldName) return;
  3323. if (!newName) {
  3324. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3325. return;
  3326. }
  3327. if (newName === oldName) {
  3328. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3329. return;
  3330. }
  3331. if (newName.length > 15) {
  3332. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3333. return;
  3334. }
  3335. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3336. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3337. return;
  3338. }
  3339. const renameBtn = document.getElementById('modal-btn-rename');
  3340. if (renameBtn) {
  3341. renameBtn.disabled = true;
  3342. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3343. }
  3344. try {
  3345. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3346. method: 'POST',
  3347. headers: { 'Content-Type': 'application/json' },
  3348. body: JSON.stringify({ new_name: newName })
  3349. });
  3350. const data = await res.json();
  3351. if (!res.ok) {
  3352. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3353. return;
  3354. }
  3355. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3356. state.currentModalIface = newName;
  3357. document.getElementById('modal-iface-name').innerText = newName;
  3358. // Refresh application state
  3359. await fetchData(false);
  3360. const updated = (state.interfaces || []).find(i => i.name === newName);
  3361. if (updated) {
  3362. openIfaceModal(newName);
  3363. } else {
  3364. closeIfaceModal();
  3365. }
  3366. } catch (err) {
  3367. showToast('Error', err.message, 'error');
  3368. } finally {
  3369. if (renameBtn) {
  3370. renameBtn.disabled = false;
  3371. renameBtn.innerHTML = `
  3372. <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>
  3373. <span>Rename</span>
  3374. `;
  3375. }
  3376. }
  3377. }
  3378. async function saveInterfaceMetadata() {
  3379. const oldName = state.currentModalIface;
  3380. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3381. const role = document.getElementById('modal-iface-role').value;
  3382. const desc = document.getElementById('modal-iface-desc').value.trim();
  3383. let targetName = oldName;
  3384. // If user changed the name before clicking Save Changes, execute rename first
  3385. if (newName && newName !== oldName && oldName !== 'lo') {
  3386. try {
  3387. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3388. method: 'POST',
  3389. headers: { 'Content-Type': 'application/json' },
  3390. body: JSON.stringify({ new_name: newName })
  3391. });
  3392. const data = await renameRes.json();
  3393. if (!renameRes.ok) {
  3394. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3395. return;
  3396. }
  3397. targetName = newName;
  3398. state.currentModalIface = newName;
  3399. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3400. } catch (err) {
  3401. showToast('Error', err.message, 'error');
  3402. return;
  3403. }
  3404. }
  3405. try {
  3406. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3407. method: 'POST',
  3408. headers: { 'Content-Type': 'application/json' },
  3409. body: JSON.stringify({ role, description: desc })
  3410. });
  3411. if (res.ok) {
  3412. showToast('Saved', 'Interface configuration updated', 'success');
  3413. closeIfaceModal();
  3414. fetchData(false);
  3415. } else {
  3416. const err = await res.json();
  3417. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3418. }
  3419. } catch (err) {
  3420. showToast('Error', err.message, 'error');
  3421. }
  3422. }
  3423. // ======================== IPTABLES FIREWALL ========================
  3424. state.fwSubTab = 'filter';
  3425. state.routesSubTab = 'routes';
  3426. function nativeNATChain(chain) {
  3427. const value = (chain || '').toLowerCase();
  3428. if (value === 'dstnat') return 'prerouting';
  3429. if (value === 'srcnat') return 'postrouting';
  3430. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3431. }
  3432. function nativeFirewallTarget(action) {
  3433. const name = (action || '').toLowerCase();
  3434. return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
  3435. }
  3436. function renderRuleFlag(disabled, hasComment) {
  3437. let flags = '';
  3438. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3439. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3440. return flags || '<span class="text-slate-600">-</span>';
  3441. }
  3442. function renderActionBadge(action) {
  3443. const act = (action || '').toLowerCase();
  3444. let color = 'bg-slate-800 text-slate-300';
  3445. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3446. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3447. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3448. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3449. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3450. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3451. }
  3452. function switchFWSubTab(tab) {
  3453. state.fwSubTab = tab;
  3454. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3455. tabs.forEach(t => {
  3456. const panel = document.getElementById(`fw-subtab-${t}`);
  3457. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3458. if (panel) {
  3459. if (t === tab) panel.classList.remove('hidden');
  3460. else panel.classList.add('hidden');
  3461. }
  3462. if (btn) {
  3463. if (t === tab) {
  3464. 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';
  3465. } else {
  3466. 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';
  3467. }
  3468. }
  3469. });
  3470. const addBtn = document.getElementById('fw-primary-add-btn');
  3471. if (addBtn) {
  3472. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3473. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3474. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3475. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3476. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3477. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3478. }
  3479. if (tab === 'filter') renderFilterRules();
  3480. else if (tab === 'nat') renderNATRules();
  3481. else if (tab === 'mangle') renderMangleRules();
  3482. else if (tab === 'addrlist') renderAddressLists();
  3483. else if (tab === 'geo') loadGeoIP();
  3484. else if (tab === 'connections') loadConnections();
  3485. setTimeout(initTableSorting, 50);
  3486. }
  3487. function openCurrentFWModal() {
  3488. if (state.fwSubTab === 'filter') openAddFilterModal();
  3489. else if (state.fwSubTab === 'nat') openAddNATModal();
  3490. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3491. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3492. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3493. else if (state.fwSubTab === 'connections') loadConnections();
  3494. }
  3495. async function loadFirewall(populateDropdowns = true) {
  3496. try {
  3497. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3498. fetch(`${API_BASE}/firewall/summary`),
  3499. fetch(`${API_BASE}/firewall/filter`),
  3500. fetch(`${API_BASE}/firewall/nat`),
  3501. fetch(`${API_BASE}/firewall/mangle`),
  3502. fetch(`${API_BASE}/firewall/address-lists`),
  3503. fetch(`${API_BASE}/firewall/geoip/status`),
  3504. fetch(`${API_BASE}/firewall/geoip/countries`)
  3505. ]);
  3506. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3507. const applyError = document.getElementById('fw-apply-error');
  3508. if (applyError) {
  3509. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3510. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3511. }
  3512. if (filterRes.ok) state.filterRules = await filterRes.json();
  3513. if (natRes.ok) state.natRules = await natRes.json();
  3514. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3515. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3516. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3517. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3518. if (applyError) { const messages=[state.fwSummary?.last_error, state.fwSummary?.connections_error, state.geoStatus?.last_error && 'GeoIP: '+state.geoStatus.last_error].filter(Boolean); applyError.textContent=messages.join(' · '); applyError.classList.toggle('hidden', !messages.length); }
  3519. // Badges
  3520. const bFilter = document.getElementById('fw-badge-filter');
  3521. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3522. const bNat = document.getElementById('fw-badge-nat');
  3523. if (bNat) bNat.innerText = (state.natRules || []).length;
  3524. const bMangle = document.getElementById('fw-badge-mangle');
  3525. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3526. const bAddr = document.getElementById('fw-badge-addrlist');
  3527. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3528. const bGeo = document.getElementById('fw-badge-geo');
  3529. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3530. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3531. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3532. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3533. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3534. const tbodyFilter = document.getElementById('filter-table-body');
  3535. if (tbodyFilter) {
  3536. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3537. tbodyFilter.dataset.sig = sigFilter;
  3538. renderFilterRules();
  3539. } else {
  3540. // In-place live stats update (ZERO flicker)
  3541. (state.filterRules || []).forEach(r => {
  3542. const p = document.getElementById(`filter-pkts-${r.id}`);
  3543. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3544. const b = document.getElementById(`filter-bytes-${r.id}`);
  3545. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3546. });
  3547. }
  3548. }
  3549. const tbodyNat = document.getElementById('nat-table-body');
  3550. if (tbodyNat) {
  3551. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3552. tbodyNat.dataset.sig = sigNat;
  3553. renderNATRules();
  3554. } else {
  3555. (state.natRules || []).forEach(r => {
  3556. const p = document.getElementById(`nat-pkts-${r.id}`);
  3557. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3558. const b = document.getElementById(`nat-bytes-${r.id}`);
  3559. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3560. });
  3561. }
  3562. }
  3563. const tbodyMangle = document.getElementById('mangle-table-body');
  3564. if (tbodyMangle) {
  3565. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3566. tbodyMangle.dataset.sig = sigMangle;
  3567. renderMangleRules();
  3568. } else {
  3569. (state.mangleRules || []).forEach(r => {
  3570. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3571. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3572. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3573. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3574. });
  3575. }
  3576. }
  3577. const tbodyAddr = document.getElementById('addrlist-table-body');
  3578. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3579. tbodyAddr.dataset.sig = sigAddr;
  3580. renderAddressLists();
  3581. }
  3582. renderGeoCountries();
  3583. if (state.fwSubTab === 'connections') {
  3584. loadConnections();
  3585. }
  3586. } catch (err) {
  3587. console.error('Failed to load firewall:', err);
  3588. }
  3589. }
  3590. // ----------------- Filter Rules -----------------
  3591. function renderFilterRules() {
  3592. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3593. const tbody = document.getElementById('filter-table-body');
  3594. const empty = document.getElementById('filter-empty');
  3595. if (!tbody) return;
  3596. tbody.innerHTML = '';
  3597. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3598. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3599. if (rules.length === 0) {
  3600. empty?.classList.remove('hidden');
  3601. return;
  3602. }
  3603. empty?.classList.add('hidden');
  3604. rules.forEach((raw, idx) => {
  3605. const r = safeFirewallRow(raw);
  3606. const tr = document.createElement('tr');
  3607. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3608. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3609. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3610. let actionExtra = '';
  3611. if (r.action === 'reject') {
  3612. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3613. } else if (r.action === 'jump') {
  3614. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3615. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3616. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3617. } else if (r.action === 'log' && r.log_prefix) {
  3618. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3619. }
  3620. tr.innerHTML = `
  3621. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3622. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3623. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3624. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3625. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3626. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  3627. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3628. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3629. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3630. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3631. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3632. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3633. </td>
  3634. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3635. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3636. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3637. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3638. <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>
  3639. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3640. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3641. </td>
  3642. `;
  3643. tbody.appendChild(tr);
  3644. });
  3645. }
  3646. function formatTarget(addr, list, geo) {
  3647. const parts = [];
  3648. if (addr) parts.push(`<span>${addr}</span>`);
  3649. if (list) {
  3650. const inv = list.startsWith('!') ? '!' : '';
  3651. const clean = list.replace(/^!/, '');
  3652. 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>`);
  3653. }
  3654. if (geo) {
  3655. const inv = geo.startsWith('!') ? '!' : '';
  3656. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3657. 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>`);
  3658. }
  3659. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3660. return parts.join(' ');
  3661. }
  3662. function populateInterfaceSelect(selectId, currentVal = '') {
  3663. const sel = document.getElementById(selectId);
  3664. if (!sel) return;
  3665. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3666. const sdwanNames = new Set((state.sdwanGroups || []).map(g => g.name));
  3667. (state.interfaces || []).filter(i => !sdwanNames.has(i.name)).forEach(i => {
  3668. const opt = document.createElement('option');
  3669. opt.value = i.name;
  3670. opt.innerText = `${i.name} (${i.role || i.type})`;
  3671. if (i.name === currentVal) opt.selected = true;
  3672. sel.appendChild(opt);
  3673. });
  3674. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3675. const optgroup = document.createElement('optgroup');
  3676. optgroup.label = 'SD-WAN Groups';
  3677. state.sdwanGroups.forEach(g => {
  3678. const opt = document.createElement('option');
  3679. opt.value = g.name;
  3680. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3681. if (g.name === currentVal) opt.selected = true;
  3682. optgroup.appendChild(opt);
  3683. });
  3684. sel.appendChild(optgroup);
  3685. }
  3686. }
  3687. function populateAddressListSelect(selectId, currentVal = '') {
  3688. const sel = document.getElementById(selectId);
  3689. if (!sel) return;
  3690. sel.innerHTML = '<option value="">(None)</option>';
  3691. const cleanVal = (currentVal || '').replace(/^!/, '');
  3692. const ruleLists = [...(state.filterRules||[]), ...(state.natRules||[]), ...(state.mangleRules||[])].flatMap(r => [r.src_address_list,r.dst_address_list,r.address_list]).filter(Boolean).map(n => n.replace(/^!/, '')).filter(n => !n.startsWith('geo:') && !n.startsWith('geo_'));
  3693. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3694. customNames.forEach(name => {
  3695. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3696. const opt = document.createElement('option');
  3697. opt.value = name;
  3698. opt.innerText = `${name} (${count} entries)`;
  3699. if (name === cleanVal) opt.selected = true;
  3700. sel.appendChild(opt);
  3701. });
  3702. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3703. const opt = document.createElement('option');
  3704. opt.value = cleanVal;
  3705. opt.innerText = cleanVal;
  3706. opt.selected = true;
  3707. sel.appendChild(opt);
  3708. }
  3709. populateCommonAddrListDatalist();
  3710. }
  3711. function populateCommonAddrListDatalist() {
  3712. const dl = document.getElementById('fw-addrlist-datalist');
  3713. if (!dl) return;
  3714. dl.innerHTML = '';
  3715. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3716. names.forEach(name => {
  3717. const opt = document.createElement('option');
  3718. opt.value = name;
  3719. dl.appendChild(opt);
  3720. });
  3721. }
  3722. function populateGeoIPSelect(selectId, currentVal = '') {
  3723. const sel = document.getElementById(selectId);
  3724. if (!sel) return;
  3725. sel.innerHTML = '<option value="">(None)</option>';
  3726. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3727. // Presets optgroup
  3728. const grpPresets = document.createElement('optgroup');
  3729. grpPresets.label = '⚡ Regional Presets';
  3730. const presets = [
  3731. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3732. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3733. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3734. ];
  3735. presets.forEach(p => {
  3736. const opt = document.createElement('option');
  3737. opt.value = p.code;
  3738. opt.innerText = p.label;
  3739. if (p.code === cleanVal) opt.selected = true;
  3740. grpPresets.appendChild(opt);
  3741. });
  3742. sel.appendChild(grpPresets);
  3743. // All Countries optgroup
  3744. const grpCountries = document.createElement('optgroup');
  3745. grpCountries.label = '🌍 All Countries';
  3746. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3747. countries.forEach(c => {
  3748. const opt = document.createElement('option');
  3749. opt.value = c.code;
  3750. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3751. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3752. if (c.code === cleanVal) opt.selected = true;
  3753. grpCountries.appendChild(opt);
  3754. });
  3755. sel.appendChild(grpCountries);
  3756. }
  3757. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3758. function switchFwRuleTab(tab) {
  3759. state.activeFwRuleTab = tab;
  3760. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3761. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3762. btn.classList.add('text-slate-400', 'border-transparent');
  3763. });
  3764. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3765. if (activeBtn) {
  3766. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3767. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3768. }
  3769. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3770. const activePane = document.getElementById(`fw-pane-${tab}`);
  3771. if (activePane) activePane.classList.remove('hidden');
  3772. if (tab === 'statistics') {
  3773. startFwStatPolling();
  3774. } else {
  3775. stopFwStatPolling();
  3776. }
  3777. }
  3778. function toggleFwField(fieldKey, expand) {
  3779. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3780. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3781. if (!plusBtn || !fieldBox) return;
  3782. if (expand) {
  3783. plusBtn.classList.add('hidden');
  3784. fieldBox.classList.remove('hidden');
  3785. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3786. if (valInput) valInput.focus();
  3787. } else {
  3788. fieldBox.classList.add('hidden');
  3789. plusBtn.classList.remove('hidden');
  3790. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3791. if (valInput) {
  3792. if (valInput.tagName === 'SELECT') {
  3793. valInput.selectedIndex = 0;
  3794. } else {
  3795. valInput.value = '';
  3796. }
  3797. }
  3798. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3799. if (invInput) invInput.checked = false;
  3800. if (fieldKey === 'cs') {
  3801. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3802. const el = document.getElementById(id);
  3803. if (el) el.checked = false;
  3804. });
  3805. }
  3806. if (fieldKey === 'natstate') {
  3807. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3808. const el = document.getElementById(id);
  3809. if (el) el.checked = false;
  3810. });
  3811. }
  3812. if (fieldKey === 'days') {
  3813. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3814. const el = document.getElementById(`fw-day-${d}`);
  3815. if (el) el.checked = true;
  3816. });
  3817. }
  3818. }
  3819. }
  3820. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3821. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3822. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3823. toggleFwField(fieldKey, true);
  3824. let strVal = String(value);
  3825. if (hasInvert) {
  3826. const inv = strVal.startsWith('!');
  3827. if (inv) strVal = strVal.slice(1);
  3828. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3829. if (invEl) invEl.checked = inv;
  3830. else if (inv) strVal = '!'+strVal;
  3831. }
  3832. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3833. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  3834. } else {
  3835. toggleFwField(fieldKey, false);
  3836. }
  3837. }
  3838. function getFwFieldVal(fieldKey, hasInvert = false) {
  3839. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3840. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3841. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3842. let v = valEl ? valEl.value.trim() : '';
  3843. if (!v) return '';
  3844. if (hasInvert) {
  3845. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3846. if (invEl && invEl.checked) {
  3847. v = '!' + v.replace(/^!/, '');
  3848. }
  3849. }
  3850. return v;
  3851. }
  3852. function toggleMaximizeFilterModal() {
  3853. const win = document.getElementById('filter-modal-window');
  3854. if (!win) return;
  3855. if (win.classList.contains('max-w-[720px]')) {
  3856. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3857. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3858. } else {
  3859. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3860. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3861. }
  3862. }
  3863. const FW_NATIVE_CHAINS = {
  3864. filter: [
  3865. { id: 'forward', label: 'FORWARD (routed through router)' },
  3866. { id: 'input', label: 'INPUT (destined to this router)' },
  3867. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3868. ],
  3869. nat: [
  3870. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3871. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3872. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3873. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3874. ],
  3875. mangle: [
  3876. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3877. { id: 'input', label: 'INPUT (destined to this machine)' },
  3878. { id: 'forward', label: 'FORWARD (routed through router)' },
  3879. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3880. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3881. ]
  3882. };
  3883. function populateChainDropdown(table, currentChain) {
  3884. const sel = document.getElementById(`${table}-modal-chain-select`);
  3885. if (!sel) return;
  3886. const cur = (currentChain || '').trim();
  3887. const lower = cur.toLowerCase();
  3888. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3889. const rules = state[rulesKey] || [];
  3890. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3891. const customChains = new Set();
  3892. rules.forEach(r => {
  3893. if (r.chain) {
  3894. const c = r.chain.trim();
  3895. const l = c.toLowerCase();
  3896. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3897. customChains.add(c);
  3898. }
  3899. }
  3900. });
  3901. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3902. if (isCurrentCustom) {
  3903. customChains.add(cur);
  3904. }
  3905. let html = '';
  3906. FW_NATIVE_CHAINS[table].forEach(c => {
  3907. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3908. });
  3909. if (customChains.size > 0) {
  3910. html += `<optgroup label="Custom Chains">`;
  3911. customChains.forEach(c => {
  3912. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3913. });
  3914. html += `</optgroup>`;
  3915. }
  3916. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3917. sel.innerHTML = html;
  3918. if (isCurrentCustom) {
  3919. sel.value = cur;
  3920. } else if (nativeIds.includes(lower)) {
  3921. sel.value = lower;
  3922. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3923. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3924. } else {
  3925. sel.value = nativeIds[0];
  3926. }
  3927. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3928. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3929. if (isCurrentCustom || sel.value === '__custom__') {
  3930. if (customWrap) customWrap.classList.remove('hidden');
  3931. if (customInput) customInput.value = cur;
  3932. } else {
  3933. if (customWrap) customWrap.classList.add('hidden');
  3934. if (customInput) customInput.value = '';
  3935. }
  3936. const chainInput = document.getElementById(`${table}-modal-chain`);
  3937. if (chainInput) chainInput.value = cur || sel.value;
  3938. }
  3939. function syncFilterChainFromSelect() {
  3940. const sel = document.getElementById('filter-modal-chain-select');
  3941. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3942. const customInput = document.getElementById('filter-modal-custom-input');
  3943. const chainInput = document.getElementById('filter-modal-chain');
  3944. if (!sel || !chainInput) return;
  3945. if (sel.value === '__custom__') {
  3946. if (customWrap) customWrap.classList.remove('hidden');
  3947. if (customInput) {
  3948. customInput.value = '';
  3949. customInput.focus();
  3950. }
  3951. chainInput.value = '';
  3952. } else {
  3953. if (customWrap) customWrap.classList.add('hidden');
  3954. chainInput.value = sel.value;
  3955. }
  3956. handleFilterChainChange();
  3957. }
  3958. function syncFilterCustomChainInput() {
  3959. const customInput = document.getElementById('filter-modal-custom-input');
  3960. const chainInput = document.getElementById('filter-modal-chain');
  3961. if (customInput && chainInput) {
  3962. chainInput.value = customInput.value.trim();
  3963. }
  3964. handleFilterChainChange();
  3965. }
  3966. function handleFilterChainChange() {
  3967. const chainInput = document.getElementById('filter-modal-chain');
  3968. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  3969. const sel = document.getElementById('filter-modal-chain-select');
  3970. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  3971. if (['forward', 'input', 'output'].includes(chain)) {
  3972. sel.value = chain;
  3973. }
  3974. }
  3975. const hintEl = document.getElementById('filter-chain-hint');
  3976. if (hintEl) {
  3977. if (chain === 'forward') {
  3978. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  3979. } else if (chain === 'input') {
  3980. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  3981. } else if (chain === 'output') {
  3982. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  3983. } else {
  3984. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  3985. }
  3986. }
  3987. const rowIn = document.getElementById('fw-row-iniface');
  3988. const rowInList = document.getElementById('fw-row-inifacelist');
  3989. const rowOut = document.getElementById('fw-row-outiface');
  3990. const rowOutList = document.getElementById('fw-row-outifacelist');
  3991. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  3992. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  3993. const rowSrcMac = document.getElementById('fw-row-srcmac');
  3994. if (chain === 'input') {
  3995. if (rowIn) rowIn.classList.remove('hidden');
  3996. if (rowInList) rowInList.classList.remove('hidden');
  3997. if (rowOut) rowOut.classList.add('hidden');
  3998. if (rowOutList) rowOutList.classList.add('hidden');
  3999. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4000. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4001. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4002. } else if (chain === 'output') {
  4003. if (rowIn) rowIn.classList.add('hidden');
  4004. if (rowInList) rowInList.classList.add('hidden');
  4005. if (rowOut) rowOut.classList.remove('hidden');
  4006. if (rowOutList) rowOutList.classList.remove('hidden');
  4007. if (rowInBridge) rowInBridge.classList.add('hidden');
  4008. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4009. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4010. } else {
  4011. if (rowIn) rowIn.classList.remove('hidden');
  4012. if (rowInList) rowInList.classList.remove('hidden');
  4013. if (rowOut) rowOut.classList.remove('hidden');
  4014. if (rowOutList) rowOutList.classList.remove('hidden');
  4015. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4016. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4017. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4018. }
  4019. checkFilterActionChainCompatibility();
  4020. }
  4021. function checkFilterActionChainCompatibility() {
  4022. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  4023. const warnBox = document.getElementById('filter-action-incompatible-warn');
  4024. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  4025. if (!warnBox || !warnMsg) return;
  4026. if (chain === 'prerouting' || chain === 'postrouting') {
  4027. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  4028. warnBox.classList.remove('hidden');
  4029. } else {
  4030. warnBox.classList.add('hidden');
  4031. }
  4032. }
  4033. function openAddFilterModal() {
  4034. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  4035. switchFwRuleTab('general');
  4036. setFirewallDays('fw', '');
  4037. const badge = document.getElementById('fw-modal-badge');
  4038. if (badge) badge.innerText = 'New...';
  4039. document.getElementById('filter-modal-id').value = '';
  4040. document.getElementById('filter-modal-family').value = '4';
  4041. document.getElementById('filter-modal-enabled').checked = true;
  4042. document.getElementById('filter-modal-comment').value = '';
  4043. document.getElementById('filter-modal-chain').value = 'forward';
  4044. populateChainDropdown('filter', 'forward');
  4045. handleFilterChainChange();
  4046. document.getElementById('filter-modal-action').value = 'accept';
  4047. document.getElementById('filter-modal-log').checked = false;
  4048. populateInterfaceSelect('fw-val-iniface');
  4049. populateInterfaceSelect('fw-val-outiface');
  4050. populateAddressListSelect('fw-val-srclist');
  4051. populateAddressListSelect('fw-val-dstlist');
  4052. populateGeoIPSelect('fw-val-srcgeo');
  4053. populateGeoIPSelect('fw-val-dstgeo');
  4054. const allFieldKeys = [
  4055. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4056. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4057. 'routingmark', 'conntype', 'cs', 'natstate',
  4058. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4059. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4060. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4061. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4062. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4063. ];
  4064. allFieldKeys.forEach(k => toggleFwField(k, false));
  4065. resetRuleCounterDisplay();
  4066. toggleFilterActionFields();
  4067. refreshFirewallRejectTypes();
  4068. document.getElementById('filter-modal').classList.remove('hidden');
  4069. }
  4070. function openEditFilterModal(id) {
  4071. id = decodeURIComponent(id);
  4072. const r = (state.filterRules || []).find(rule => rule.id === id);
  4073. if (!r) return;
  4074. switchFwRuleTab('general');
  4075. const badge = document.getElementById('fw-modal-badge');
  4076. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4077. document.getElementById('filter-modal-id').value = r.id;
  4078. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4079. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4080. document.getElementById('filter-modal-comment').value = r.comment || '';
  4081. const filterChain = r.chain || 'forward';
  4082. document.getElementById('filter-modal-chain').value = filterChain;
  4083. populateChainDropdown('filter', filterChain);
  4084. handleFilterChainChange();
  4085. setFirewallActionSelection('filter', r.action || 'accept');
  4086. document.getElementById('filter-modal-log').checked = !!r.log;
  4087. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4088. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4089. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4090. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4091. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4092. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4093. setFwFieldVal('src', r.src_address, true);
  4094. setFwFieldVal('dst', r.dst_address, true);
  4095. setFwFieldVal('srclist', r.src_address_list, true);
  4096. setFwFieldVal('dstlist', r.dst_address_list, true);
  4097. setFwFieldVal('srcgeo', r.src_geoip, true);
  4098. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4099. if (r.protocol && r.protocol !== 'all') {
  4100. setFwFieldVal('proto', r.protocol, true);
  4101. } else {
  4102. toggleFwField('proto', false);
  4103. }
  4104. setFwFieldVal('sport', r.src_port, true);
  4105. setFwFieldVal('dport', r.dst_port, true);
  4106. setFwFieldVal('anyport', r.any_port, true);
  4107. setFwFieldVal('iniface', r.in_interface, true);
  4108. setFwFieldVal('outiface', r.out_interface, true);
  4109. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4110. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4111. setFwFieldVal('pktmark', r.packet_mark, true);
  4112. setFwFieldVal('connmark', r.connection_mark, true);
  4113. setFwFieldVal('routingmark', r.routing_mark, true);
  4114. setFwFieldVal('conntype', r.connection_type, false);
  4115. const states = r.connection_state || [];
  4116. if (states.length > 0) {
  4117. toggleFwField('cs', true);
  4118. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4119. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4120. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4121. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4122. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4123. } else {
  4124. toggleFwField('cs', false);
  4125. }
  4126. const natStates = r.connection_nat_state || [];
  4127. if (natStates.length > 0) {
  4128. toggleFwField('natstate', true);
  4129. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4130. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4131. } else {
  4132. toggleFwField('natstate', false);
  4133. }
  4134. // Advanced tab fields
  4135. setFwFieldVal('layer7', r.layer7_protocol, false);
  4136. setFwFieldVal('content', r.content, false);
  4137. setFwFieldVal('connbytes', r.connection_bytes, false);
  4138. setFwFieldVal('connrate', r.connection_rate, false);
  4139. setFwFieldVal('pcc', r.pcc, false);
  4140. setFwFieldVal('srcmac', r.src_mac_address, true);
  4141. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4142. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4143. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4144. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4145. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4146. setFwFieldVal('tlshost', r.tls_host, false);
  4147. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4148. setFwFieldVal('priority', r.priority, false);
  4149. setFwFieldVal('dscp', r.dscp, false);
  4150. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4151. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4152. setFwFieldVal('pktsize', r.packet_size, false);
  4153. setFwFieldVal('random', r.random, false);
  4154. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4155. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4156. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4157. setFwFieldVal('ttl', r.ttl, false);
  4158. // Extra tab fields
  4159. setFwFieldVal('time', r.time, false);
  4160. if (r.days) {
  4161. toggleFwField('days', true);
  4162. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4163. const chk = document.getElementById(`fw-day-${d}`);
  4164. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4165. });
  4166. } else {
  4167. toggleFwField('days', false);
  4168. }
  4169. setFwFieldVal('limit', r.limit, false);
  4170. setFwFieldVal('dstlimit', r.dst_limit, false);
  4171. setFwFieldVal('psd', r.psd, false);
  4172. // Action fields
  4173. if (r.reject_with) {
  4174. const rwEl = document.getElementById('filter-modal-rejectwith');
  4175. if (rwEl) rwEl.value = r.reject_with;
  4176. }
  4177. if (r.jump_target) {
  4178. const jtEl = document.getElementById('filter-modal-jumptarget');
  4179. if (jtEl) jtEl.value = r.jump_target;
  4180. }
  4181. if (r.address_list) {
  4182. const alEl = document.getElementById('filter-modal-action-addrlist');
  4183. if (alEl) alEl.value = r.address_list;
  4184. }
  4185. if (r.address_list_timeout) {
  4186. const toEl = document.getElementById('filter-modal-action-timeout');
  4187. if (toEl) toEl.value = r.address_list_timeout;
  4188. }
  4189. setFwFieldVal('logprefix', r.log_prefix, false);
  4190. // Statistics
  4191. const bEl = document.getElementById('fw-stat-bytes');
  4192. const pEl = document.getElementById('fw-stat-packets');
  4193. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4194. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4195. state.fwLastBytes = r.bytes || 0;
  4196. state.fwLastPackets = r.packets || 0;
  4197. state.fwLastTimestamp = Date.now();
  4198. state.fwStatRateHistory = new Array(30).fill(0);
  4199. state.fwStatPktHistory = new Array(30).fill(0);
  4200. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4201. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4202. toggleFilterActionFields();
  4203. refreshFirewallRejectTypes();
  4204. document.getElementById('filter-modal').classList.remove('hidden');
  4205. }
  4206. function closeFilterModal() {
  4207. stopFwStatPolling();
  4208. document.getElementById('filter-modal').classList.add('hidden');
  4209. }
  4210. function toggleFilterActionFields() {
  4211. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4212. const rejectBox = document.getElementById('filter-action-reject-box');
  4213. const jumpBox = document.getElementById('filter-action-jump-box');
  4214. const addrBox = document.getElementById('filter-action-addrlist-box');
  4215. if (rejectBox) {
  4216. if (act === 'reject') rejectBox.classList.remove('hidden');
  4217. else rejectBox.classList.add('hidden');
  4218. }
  4219. if (jumpBox) {
  4220. if (act === 'jump') jumpBox.classList.remove('hidden');
  4221. else jumpBox.classList.add('hidden');
  4222. }
  4223. if (addrBox) {
  4224. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4225. addrBox.classList.remove('hidden');
  4226. } else {
  4227. addrBox.classList.add('hidden');
  4228. }
  4229. }
  4230. if (act === 'log') {
  4231. const logEl = document.getElementById('filter-modal-log');
  4232. if (logEl) logEl.checked = true;
  4233. toggleFwField('logprefix', true);
  4234. }
  4235. }
  4236. function toggleFwLogPrefix() {
  4237. const isLog = document.getElementById('filter-modal-log')?.checked;
  4238. toggleFwField('logprefix', !!isLog);
  4239. }
  4240. function copyFilterRule() {
  4241. document.getElementById('filter-modal-id').value = '';
  4242. const badge = document.getElementById('fw-modal-badge');
  4243. if (badge) badge.innerText = 'New...';
  4244. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4245. }
  4246. function resetRuleCounterDisplay() {
  4247. state.fwStatRateHistory = new Array(30).fill(0);
  4248. state.fwStatPktHistory = new Array(30).fill(0);
  4249. state.fwLastBytes = 0;
  4250. state.fwLastPackets = 0;
  4251. state.fwLastTimestamp = Date.now();
  4252. const bEl = document.getElementById('fw-stat-bytes');
  4253. const pEl = document.getElementById('fw-stat-packets');
  4254. const rEl = document.getElementById('fw-stat-rate');
  4255. const prEl = document.getElementById('fw-stat-pktrate');
  4256. if (bEl) bEl.value = '0 B';
  4257. if (pEl) pEl.value = '0';
  4258. if (rEl) rEl.value = '0 bps';
  4259. if (prEl) prEl.value = '0 p/s';
  4260. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4261. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4262. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4263. }
  4264. async function resetAllFwCounters() {
  4265. try {
  4266. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4267. if (res.ok) {
  4268. resetRuleCounterDisplay();
  4269. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4270. loadFirewall(false);
  4271. }
  4272. } catch (err) {
  4273. showToast('Error', err.message, 'error');
  4274. }
  4275. }
  4276. async function applyFilterRule(closeAfter = false) {
  4277. const id = document.getElementById('filter-modal-id').value;
  4278. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4279. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4280. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4281. const chainLower = chain.toLowerCase();
  4282. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4283. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4284. switchFwRuleTab('general');
  4285. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4286. return;
  4287. }
  4288. const action = document.getElementById('filter-modal-action').value;
  4289. const comment = document.getElementById('filter-modal-comment').value.trim();
  4290. const enabled = document.getElementById('filter-modal-enabled').checked;
  4291. const src = getFwFieldVal('src', true);
  4292. const dst = getFwFieldVal('dst', true);
  4293. const srclist = getFwFieldVal('srclist', true);
  4294. const dstlist = getFwFieldVal('dstlist', true);
  4295. const srcgeo = getFwFieldVal('srcgeo', true);
  4296. const dstgeo = getFwFieldVal('dstgeo', true);
  4297. const proto = getFwFieldVal('proto', true);
  4298. const sport = getFwFieldVal('sport', true);
  4299. const dport = getFwFieldVal('dport', true);
  4300. const anyport = getFwFieldVal('anyport', true);
  4301. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4302. switchFwRuleTab('general'); toggleFwField('proto', true);
  4303. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4304. }
  4305. let iniface = getFwFieldVal('iniface', true);
  4306. let outiface = getFwFieldVal('outiface', true);
  4307. let inifacelist = getFwFieldVal('inifacelist', true);
  4308. let outifacelist = getFwFieldVal('outifacelist', true);
  4309. if (chainLower === 'input') {
  4310. outiface = '';
  4311. outifacelist = '';
  4312. } else if (chainLower === 'output') {
  4313. iniface = '';
  4314. inifacelist = '';
  4315. }
  4316. const pktmark = getFwFieldVal('pktmark', true);
  4317. const connmark = getFwFieldVal('connmark', true);
  4318. const routingmark = getFwFieldVal('routingmark', true);
  4319. const conntype = getFwFieldVal('conntype', false);
  4320. const states = [];
  4321. const csBox = document.getElementById('fw-field-cs');
  4322. if (csBox && !csBox.classList.contains('hidden')) {
  4323. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4324. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4325. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4326. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4327. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4328. }
  4329. const natStates = [];
  4330. const natBox = document.getElementById('fw-field-natstate');
  4331. if (natBox && !natBox.classList.contains('hidden')) {
  4332. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4333. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4334. }
  4335. const payload = {
  4336. ip_version: Number(document.getElementById('filter-modal-family').value),
  4337. id,
  4338. chain,
  4339. action,
  4340. protocol: proto || 'all',
  4341. src_address: src,
  4342. dst_address: dst,
  4343. src_port: sport,
  4344. dst_port: dport,
  4345. any_port: anyport,
  4346. in_interface: iniface,
  4347. out_interface: outiface,
  4348. in_interface_list: inifacelist,
  4349. out_interface_list: outifacelist,
  4350. packet_mark: pktmark,
  4351. connection_mark: connmark,
  4352. routing_mark: routingmark,
  4353. connection_type: conntype,
  4354. connection_state: states,
  4355. connection_nat_state: natStates,
  4356. src_address_list: srclist,
  4357. dst_address_list: dstlist,
  4358. src_geoip: srcgeo,
  4359. dst_geoip: dstgeo,
  4360. comment,
  4361. disabled: !enabled,
  4362. // Advanced tab
  4363. content: getFwFieldVal('content', false),
  4364. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4365. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4366. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4367. ipsec_policy: getFwFieldVal('ipsec', false),
  4368. dscp: getFwFieldVal('dscp', false),
  4369. tcp_mss: getFwFieldVal('tcpmss', false),
  4370. tos: document.getElementById('fw-val-tos')?.value || '',
  4371. packet_size: getFwFieldVal('pktsize', false),
  4372. random: getFwFieldVal('random', false),
  4373. tcp_flags: getFwFieldVal('tcpflags', false),
  4374. icmp_options: getFwFieldVal('icmpoptions', false),
  4375. ttl: getFwFieldVal('ttl', false),
  4376. days: selectedDays,
  4377. // Extra tab
  4378. time: getFwFieldVal('time', false),
  4379. limit: getFwFieldVal('limit', false),
  4380. // Action tab
  4381. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4382. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4383. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4384. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4385. log: document.getElementById('filter-modal-log')?.checked || false,
  4386. log_prefix: getFwFieldVal('logprefix', false)
  4387. };
  4388. try {
  4389. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4390. method: 'POST',
  4391. headers: { 'Content-Type': 'application/json' },
  4392. body: JSON.stringify(payload)
  4393. });
  4394. if (res.ok) {
  4395. const data = await res.json();
  4396. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4397. loadFirewall(false);
  4398. if (closeAfter) {
  4399. closeFilterModal();
  4400. } else {
  4401. if (data.id) {
  4402. document.getElementById('filter-modal-id').value = data.id;
  4403. const badge = document.getElementById('fw-modal-badge');
  4404. if (badge) badge.innerText = `#${data.id}`;
  4405. }
  4406. }
  4407. } else {
  4408. const err = await res.json();
  4409. showToast('Error', err.message || 'Failed to save rule', 'error');
  4410. }
  4411. } catch (err) {
  4412. showToast('Error', err.message, 'error');
  4413. }
  4414. }
  4415. function submitSaveFilterRule(e) {
  4416. if (e && e.preventDefault) e.preventDefault();
  4417. return applyFilterRule(true);
  4418. }
  4419. function startFwStatPolling() {
  4420. stopFwStatPolling();
  4421. pollRuleStats();
  4422. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4423. }
  4424. function stopFwStatPolling() {
  4425. if (state.fwStatInterval) {
  4426. clearInterval(state.fwStatInterval);
  4427. state.fwStatInterval = null;
  4428. }
  4429. }
  4430. async function pollRuleStats() {
  4431. const id = document.getElementById('filter-modal-id')?.value;
  4432. if (!id) {
  4433. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4434. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4435. return;
  4436. }
  4437. try {
  4438. const res = await fetch(`${API_BASE}/firewall/filter`);
  4439. if (!res.ok) return;
  4440. const rules = await res.json();
  4441. const r = rules.find(x => x.id === id);
  4442. if (!r) return;
  4443. const now = Date.now();
  4444. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4445. state.fwLastTimestamp = now;
  4446. const curBytes = r.bytes || 0;
  4447. const curPackets = r.packets || 0;
  4448. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4449. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4450. state.fwLastBytes = curBytes;
  4451. state.fwLastPackets = curPackets;
  4452. const rateBps = Math.round((deltaBytes * 8) / dt);
  4453. const ratePkt = Math.round(deltaPkts / dt);
  4454. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4455. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4456. state.fwStatRateHistory.push(rateBps);
  4457. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4458. state.fwStatPktHistory.push(ratePkt);
  4459. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4460. const bEl = document.getElementById('fw-stat-bytes');
  4461. const pEl = document.getElementById('fw-stat-packets');
  4462. const rEl = document.getElementById('fw-stat-rate');
  4463. const prEl = document.getElementById('fw-stat-pktrate');
  4464. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4465. if (pEl) pEl.value = curPackets.toLocaleString();
  4466. if (rEl) rEl.value = formatBps(rateBps);
  4467. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4468. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4469. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4470. } catch (e) {
  4471. console.error('Error polling rule stats', e);
  4472. }
  4473. }
  4474. function formatBps(bps) {
  4475. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4476. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4477. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4478. return bps + ' bps';
  4479. }
  4480. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4481. const svg = document.getElementById(svgId);
  4482. if (!svg) return;
  4483. const w = 500;
  4484. const h = 100;
  4485. const paddingRight = 45;
  4486. const graphWidth = w - paddingRight;
  4487. const maxVal = Math.max(5, ...dataArray);
  4488. const currentVal = dataArray[dataArray.length - 1] || 0;
  4489. const leg = document.getElementById(legendId);
  4490. if (leg) {
  4491. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4492. }
  4493. let gridLines = '';
  4494. for (let i = 0; i <= 5; i++) {
  4495. const y = 8 + (i * (h - 18) / 5);
  4496. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4497. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4498. gridLines += `
  4499. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4500. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4501. `;
  4502. }
  4503. const step = graphWidth / (dataArray.length - 1);
  4504. const points = dataArray.map((val, idx) => {
  4505. const x = idx * step;
  4506. const y = (h - 10) - (val / maxVal) * (h - 20);
  4507. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4508. });
  4509. const polylineStr = points.join(' ');
  4510. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4511. svg.innerHTML = `
  4512. ${gridLines}
  4513. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4514. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4515. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4516. `;
  4517. }
  4518. async function moveFilterRule(id, dir) {
  4519. id = decodeURIComponent(id);
  4520. try {
  4521. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4522. method: 'POST',
  4523. headers: { 'Content-Type': 'application/json' },
  4524. body: JSON.stringify({ direction: dir })
  4525. });
  4526. if (!res.ok) throw new Error(await responseError(res));
  4527. await loadFirewall(false);
  4528. } catch (err) {
  4529. showToast('Error', err.message, 'error');
  4530. }
  4531. }
  4532. async function toggleFilterRuleState(id, disabled) {
  4533. id = decodeURIComponent(id);
  4534. try {
  4535. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4536. method: 'POST',
  4537. headers: { 'Content-Type': 'application/json' },
  4538. body: JSON.stringify({ disabled })
  4539. });
  4540. if (!res.ok) throw new Error(await responseError(res));
  4541. await loadFirewall(false);
  4542. } catch (err) {
  4543. showToast('Error', err.message, 'error');
  4544. }
  4545. }
  4546. async function deleteFilterRule(id) {
  4547. id = decodeURIComponent(id);
  4548. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4549. try {
  4550. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4551. if (!res.ok) throw new Error(await responseError(res));
  4552. {
  4553. showToast('Deleted', 'Filter rule removed', 'success');
  4554. loadFirewall(false);
  4555. }
  4556. } catch (err) {
  4557. showToast('Error', err.message, 'error');
  4558. }
  4559. }
  4560. // ----------------- NAT Rules -----------------
  4561. function renderNATRules() {
  4562. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4563. const tbody = document.getElementById('nat-table-body');
  4564. const empty = document.getElementById('nat-empty');
  4565. if (!tbody) return;
  4566. tbody.innerHTML = '';
  4567. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4568. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4569. if (rules.length === 0) {
  4570. empty?.classList.remove('hidden');
  4571. return;
  4572. }
  4573. empty?.classList.add('hidden');
  4574. rules.forEach((raw, idx) => {
  4575. const r = safeFirewallRow(raw);
  4576. const tr = document.createElement('tr');
  4577. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4578. let toTarget = '-';
  4579. if (r.action === 'jump') {
  4580. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4581. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4582. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4583. } else if (r.action === 'redirect') {
  4584. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4585. } else if (r.action === 'masquerade') {
  4586. 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>`;
  4587. } else if (r.action === 'log') {
  4588. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4589. } else {
  4590. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4591. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4592. }
  4593. const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
  4594. tr.innerHTML = `
  4595. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4596. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4597. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4598. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4599. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4600. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  4601. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4602. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4603. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4604. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4605. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4606. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4607. </td>
  4608. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4609. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4610. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4611. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4612. <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>
  4613. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4614. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4615. </td>
  4616. `;
  4617. tbody.appendChild(tr);
  4618. });
  4619. }
  4620. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4621. function switchNATRuleTab(tab) {
  4622. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4623. state.activeNATRuleTab = tab;
  4624. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4625. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4626. btn.classList.add('text-slate-400', 'border-transparent');
  4627. });
  4628. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4629. if (activeBtn) {
  4630. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4631. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4632. }
  4633. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4634. const activePane = document.getElementById(`nat-pane-${tab}`);
  4635. if (activePane) activePane.classList.remove('hidden');
  4636. if (tab === 'statistics') {
  4637. startNATStatPolling();
  4638. } else {
  4639. stopNATStatPolling();
  4640. }
  4641. }
  4642. function toggleNATField(fieldKey, expand) {
  4643. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4644. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4645. if (!plusBtn || !fieldBox) return;
  4646. if (expand) {
  4647. plusBtn.classList.add('hidden');
  4648. fieldBox.classList.remove('hidden');
  4649. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4650. if (valInput) valInput.focus();
  4651. } else {
  4652. fieldBox.classList.add('hidden');
  4653. plusBtn.classList.remove('hidden');
  4654. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4655. if (valInput) {
  4656. if (valInput.tagName === 'SELECT') {
  4657. valInput.selectedIndex = 0;
  4658. } else {
  4659. valInput.value = '';
  4660. }
  4661. }
  4662. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4663. if (invInput) invInput.checked = false;
  4664. if (fieldKey === 'days') {
  4665. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4666. const el = document.getElementById(`nat-day-${d}`);
  4667. if (el) el.checked = true;
  4668. });
  4669. }
  4670. }
  4671. }
  4672. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4673. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4674. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4675. toggleNATField(fieldKey, true);
  4676. let strVal = String(value);
  4677. if (hasInvert) {
  4678. const inv = strVal.startsWith('!');
  4679. if (inv) strVal = strVal.slice(1);
  4680. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4681. if (invEl) invEl.checked = inv;
  4682. else if (inv) strVal = '!'+strVal;
  4683. }
  4684. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4685. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  4686. } else {
  4687. toggleNATField(fieldKey, false);
  4688. }
  4689. }
  4690. function getNATFieldVal(fieldKey, hasInvert = false) {
  4691. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4692. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4693. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4694. let v = valEl ? valEl.value.trim() : '';
  4695. if (!v) return '';
  4696. if (hasInvert) {
  4697. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4698. if (invEl && invEl.checked) {
  4699. v = '!' + v.replace(/^!/, '');
  4700. }
  4701. }
  4702. return v;
  4703. }
  4704. function toggleMaximizeNATModal() {
  4705. const win = document.getElementById('nat-modal-window');
  4706. if (!win) return;
  4707. if (win.classList.contains('max-w-[720px]')) {
  4708. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4709. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4710. } else {
  4711. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4712. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4713. }
  4714. }
  4715. function syncNATChainFromSelect() {
  4716. const sel = document.getElementById('nat-modal-chain-select');
  4717. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4718. const customInput = document.getElementById('nat-modal-custom-input');
  4719. const chainInput = document.getElementById('nat-modal-chain');
  4720. if (!sel || !chainInput) return;
  4721. if (sel.value === '__custom__') {
  4722. if (customWrap) customWrap.classList.remove('hidden');
  4723. if (customInput) {
  4724. customInput.value = '';
  4725. customInput.focus();
  4726. }
  4727. chainInput.value = '';
  4728. } else {
  4729. if (customWrap) customWrap.classList.add('hidden');
  4730. chainInput.value = sel.value;
  4731. const actEl = document.getElementById('nat-modal-action');
  4732. if (actEl) {
  4733. const curAct = actEl.value;
  4734. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4735. actEl.value = 'dst-nat';
  4736. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4737. actEl.value = 'masquerade';
  4738. }
  4739. }
  4740. }
  4741. handleNATChainChange();
  4742. }
  4743. function syncNATCustomChainInput() {
  4744. const customInput = document.getElementById('nat-modal-custom-input');
  4745. const chainInput = document.getElementById('nat-modal-chain');
  4746. if (customInput && chainInput) {
  4747. chainInput.value = customInput.value.trim();
  4748. }
  4749. handleNATChainChange();
  4750. }
  4751. function handleNATChainChange() {
  4752. const chainInput = document.getElementById('nat-modal-chain');
  4753. const rawChain = (chainInput?.value || 'postrouting').trim();
  4754. const chain = nativeNATChain(rawChain).toLowerCase();
  4755. const sel = document.getElementById('nat-modal-chain-select');
  4756. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4757. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4758. sel.value = chain;
  4759. }
  4760. }
  4761. const hintEl = document.getElementById('nat-chain-hint');
  4762. if (hintEl) {
  4763. if (chain === 'prerouting') {
  4764. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4765. } else if (chain === 'postrouting') {
  4766. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4767. } else if (chain === 'output') {
  4768. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4769. } else if (chain === 'input') {
  4770. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4771. } else {
  4772. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4773. }
  4774. }
  4775. const rowIn = document.getElementById('nat-row-iniface');
  4776. const rowInList = document.getElementById('nat-row-inifacelist');
  4777. const rowOut = document.getElementById('nat-row-outiface');
  4778. const rowOutList = document.getElementById('nat-row-outifacelist');
  4779. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4780. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4781. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4782. if (chain === 'prerouting' || chain === 'input') {
  4783. if (rowIn) rowIn.classList.remove('hidden');
  4784. if (rowInList) rowInList.classList.remove('hidden');
  4785. if (rowOut) rowOut.classList.add('hidden');
  4786. if (rowOutList) rowOutList.classList.add('hidden');
  4787. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4788. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4789. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4790. } else if (chain === 'postrouting' || chain === 'output') {
  4791. if (rowIn) rowIn.classList.add('hidden');
  4792. if (rowInList) rowInList.classList.add('hidden');
  4793. if (rowOut) rowOut.classList.remove('hidden');
  4794. if (rowOutList) rowOutList.classList.remove('hidden');
  4795. if (rowInBridge) rowInBridge.classList.add('hidden');
  4796. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4797. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4798. } else {
  4799. if (rowIn) rowIn.classList.remove('hidden');
  4800. if (rowInList) rowInList.classList.remove('hidden');
  4801. if (rowOut) rowOut.classList.remove('hidden');
  4802. if (rowOutList) rowOutList.classList.remove('hidden');
  4803. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4804. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4805. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4806. }
  4807. checkNATActionChainCompatibility();
  4808. toggleNATActionFields();
  4809. }
  4810. function checkNATActionChainCompatibility() {
  4811. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4812. const chain = nativeNATChain(rawChain).toLowerCase();
  4813. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4814. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4815. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4816. if (!warnBox || !warnMsg) return;
  4817. let msg = '';
  4818. if (['dst-nat', 'redirect'].includes(action)) {
  4819. if (chain !== 'prerouting' && chain !== 'output') {
  4820. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4821. }
  4822. } else if (action === 'masquerade') {
  4823. if (chain !== 'postrouting') {
  4824. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4825. }
  4826. } else if (action === 'src-nat') {
  4827. if (chain !== 'postrouting' && chain !== 'input') {
  4828. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4829. }
  4830. }
  4831. if (msg) {
  4832. warnMsg.textContent = msg;
  4833. warnBox.classList.remove('hidden');
  4834. } else {
  4835. warnBox.classList.add('hidden');
  4836. }
  4837. }
  4838. function toggleNATActionFields() {
  4839. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4840. const rowAddr = document.getElementById('nat-row-toaddr');
  4841. const rowPort = document.getElementById('nat-row-toport');
  4842. const jumpBox = document.getElementById('nat-action-jump-box');
  4843. const addrBox = document.getElementById('nat-action-addrlist-box');
  4844. // Hide all dynamic rows first
  4845. if (rowAddr) rowAddr.classList.add('hidden');
  4846. if (rowPort) rowPort.classList.add('hidden');
  4847. if (jumpBox) jumpBox.classList.add('hidden');
  4848. if (addrBox) addrBox.classList.add('hidden');
  4849. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4850. if (rowAddr) rowAddr.classList.remove('hidden');
  4851. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4852. } else if (act === 'redirect' || act === 'masquerade') {
  4853. if (rowPort) rowPort.classList.remove('hidden');
  4854. } else if (act === 'jump') {
  4855. if (jumpBox) jumpBox.classList.remove('hidden');
  4856. } else if (act.includes('address-list') || act.includes('address list')) {
  4857. if (addrBox) addrBox.classList.remove('hidden');
  4858. }
  4859. if (act === 'log') {
  4860. const logEl = document.getElementById('nat-modal-log');
  4861. if (logEl) logEl.checked = true;
  4862. toggleNATField('logprefix', true);
  4863. }
  4864. }
  4865. function handleNATActionChange() {
  4866. toggleNATActionFields();
  4867. checkNATActionChainCompatibility();
  4868. }
  4869. function toggleNATLogPrefix() {
  4870. const isLog = document.getElementById('nat-modal-log')?.checked;
  4871. toggleNATField('logprefix', !!isLog);
  4872. }
  4873. function openAddNATModal() {
  4874. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4875. switchNATRuleTab('general');
  4876. setFirewallDays('nat', '');
  4877. const badge = document.getElementById('nat-modal-badge');
  4878. if (badge) badge.innerText = 'New...';
  4879. document.getElementById('nat-modal-id').value = '';
  4880. document.getElementById('nat-modal-family').value = '4';
  4881. document.getElementById('nat-modal-enabled').checked = true;
  4882. document.getElementById('nat-modal-comment').value = '';
  4883. document.getElementById('nat-modal-chain').value = 'postrouting';
  4884. populateChainDropdown('nat', 'postrouting');
  4885. handleNATChainChange();
  4886. document.getElementById('nat-modal-action').value = 'masquerade';
  4887. document.getElementById('nat-modal-toaddr').value = '';
  4888. document.getElementById('nat-modal-toport').value = '';
  4889. document.getElementById('nat-modal-log').checked = false;
  4890. populateInterfaceSelect('nat-val-iniface');
  4891. populateInterfaceSelect('nat-val-outiface');
  4892. populateAddressListSelect('nat-val-srclist');
  4893. populateAddressListSelect('nat-val-dstlist');
  4894. populateGeoIPSelect('nat-val-srcgeo');
  4895. populateGeoIPSelect('nat-val-dstgeo');
  4896. const allFieldKeys = [
  4897. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4898. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4899. 'routingmark', 'conntype',
  4900. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4901. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4902. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4903. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4904. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4905. ];
  4906. allFieldKeys.forEach(k => toggleNATField(k, false));
  4907. resetNATCounterDisplay();
  4908. toggleNATActionFields();
  4909. document.getElementById('nat-modal').classList.remove('hidden');
  4910. }
  4911. function openEditNATModal(id) {
  4912. id = decodeURIComponent(id);
  4913. const r = (state.natRules || []).find(rule => rule.id === id);
  4914. if (!r) return;
  4915. setFirewallDays('nat', r.days || '');
  4916. switchNATRuleTab('general');
  4917. const badge = document.getElementById('nat-modal-badge');
  4918. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4919. document.getElementById('nat-modal-id').value = r.id;
  4920. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4921. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4922. document.getElementById('nat-modal-comment').value = r.comment || '';
  4923. const natChain = nativeNATChain(r.chain || 'postrouting');
  4924. document.getElementById('nat-modal-chain').value = natChain;
  4925. populateChainDropdown('nat', natChain);
  4926. handleNATChainChange();
  4927. setFirewallActionSelection('nat', r.action || 'accept');
  4928. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4929. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4930. document.getElementById('nat-modal-log').checked = !!r.log;
  4931. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4932. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4933. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4934. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4935. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4936. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4937. setNATFieldVal('src', r.src_address, true);
  4938. setNATFieldVal('dst', r.dst_address, true);
  4939. setNATFieldVal('srclist', r.src_address_list, true);
  4940. setNATFieldVal('dstlist', r.dst_address_list, true);
  4941. setNATFieldVal('srcgeo', r.src_geoip, true);
  4942. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4943. if (r.protocol && r.protocol !== 'all') {
  4944. setNATFieldVal('proto', r.protocol, true);
  4945. } else {
  4946. toggleNATField('proto', false);
  4947. }
  4948. setNATFieldVal('sport', r.src_port, true);
  4949. setNATFieldVal('dport', r.dst_port, true);
  4950. setNATFieldVal('anyport', r.any_port, true);
  4951. setNATFieldVal('iniface', r.in_interface, true);
  4952. setNATFieldVal('outiface', r.out_interface, true);
  4953. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4954. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4955. setNATFieldVal('pktmark', r.packet_mark, true);
  4956. setNATFieldVal('connmark', r.connection_mark, true);
  4957. setNATFieldVal('routingmark', r.routing_mark, true);
  4958. setNATFieldVal('conntype', r.connection_type, false);
  4959. // Advanced tab fields
  4960. setNATFieldVal('layer7', r.layer7_protocol, false);
  4961. setNATFieldVal('content', r.content, false);
  4962. setNATFieldVal('connbytes', r.connection_bytes, false);
  4963. setNATFieldVal('connrate', r.connection_rate, false);
  4964. setNATFieldVal('pcc', r.pcc, false);
  4965. setNATFieldVal('srcmac', r.src_mac_address, true);
  4966. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4967. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4968. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4969. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4970. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4971. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4972. setNATFieldVal('priority', r.priority, false);
  4973. setNATFieldVal('dscp', r.dscp, false);
  4974. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4975. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4976. setNATFieldVal('pktsize', r.packet_size, false);
  4977. setNATFieldVal('random', r.random, false);
  4978. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4979. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4980. setNATFieldVal('ttl', r.ttl, false);
  4981. // Extra tab fields
  4982. setNATFieldVal('time', r.time, false);
  4983. if (r.days) {
  4984. toggleNATField('days', true);
  4985. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4986. const chk = document.getElementById(`nat-day-${d}`);
  4987. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4988. });
  4989. } else {
  4990. toggleNATField('days', false);
  4991. }
  4992. setNATFieldVal('limit', r.limit, false);
  4993. setNATFieldVal('dstlimit', r.dst_limit, false);
  4994. setNATFieldVal('psd', r.psd, false);
  4995. // Action fields
  4996. if (r.jump_target) {
  4997. const jtEl = document.getElementById('nat-modal-jumptarget');
  4998. if (jtEl) jtEl.value = r.jump_target;
  4999. }
  5000. if (r.address_list) {
  5001. const alEl = document.getElementById('nat-modal-action-addrlist');
  5002. if (alEl) alEl.value = r.address_list;
  5003. }
  5004. if (r.address_list_timeout) {
  5005. const toEl = document.getElementById('nat-modal-action-timeout');
  5006. if (toEl) toEl.value = r.address_list_timeout;
  5007. }
  5008. setNATFieldVal('logprefix', r.log_prefix, false);
  5009. // Statistics
  5010. const bEl = document.getElementById('nat-stat-bytes');
  5011. const pEl = document.getElementById('nat-stat-packets');
  5012. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5013. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5014. state.natLastBytes = r.bytes || 0;
  5015. state.natLastPackets = r.packets || 0;
  5016. state.natLastTimestamp = Date.now();
  5017. state.natStatRateHistory = new Array(30).fill(0);
  5018. state.natStatPktHistory = new Array(30).fill(0);
  5019. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5020. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5021. toggleNATActionFields();
  5022. document.getElementById('nat-modal').classList.remove('hidden');
  5023. }
  5024. function closeNATModal() {
  5025. stopNATStatPolling();
  5026. document.getElementById('nat-modal').classList.add('hidden');
  5027. }
  5028. function copyNATRule() {
  5029. document.getElementById('nat-modal-id').value = '';
  5030. const badge = document.getElementById('nat-modal-badge');
  5031. if (badge) badge.innerText = 'New...';
  5032. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  5033. }
  5034. function resetNATCounterDisplay() {
  5035. state.natStatRateHistory = new Array(30).fill(0);
  5036. state.natStatPktHistory = new Array(30).fill(0);
  5037. state.natLastBytes = 0;
  5038. state.natLastPackets = 0;
  5039. state.natLastTimestamp = Date.now();
  5040. const bEl = document.getElementById('nat-stat-bytes');
  5041. const pEl = document.getElementById('nat-stat-packets');
  5042. const rEl = document.getElementById('nat-stat-rate');
  5043. const prEl = document.getElementById('nat-stat-pktrate');
  5044. if (bEl) bEl.value = '0 B';
  5045. if (pEl) pEl.value = '0';
  5046. if (rEl) rEl.value = '0 bps';
  5047. if (prEl) prEl.value = '0 p/s';
  5048. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5049. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5050. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5051. }
  5052. async function applyNATRule(closeAfter = false) {
  5053. const id = document.getElementById('nat-modal-id').value;
  5054. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5055. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5056. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5057. const chainLower = nativeNATChain(chain).toLowerCase();
  5058. const action = document.getElementById('nat-modal-action').value;
  5059. const comment = document.getElementById('nat-modal-comment').value.trim();
  5060. const enabled = document.getElementById('nat-modal-enabled').checked;
  5061. const src = getNATFieldVal('src', true);
  5062. const dst = getNATFieldVal('dst', true);
  5063. const srclist = getNATFieldVal('srclist', true);
  5064. const dstlist = getNATFieldVal('dstlist', true);
  5065. const srcgeo = getNATFieldVal('srcgeo', true);
  5066. const dstgeo = getNATFieldVal('dstgeo', true);
  5067. const proto = getNATFieldVal('proto', true);
  5068. const sport = getNATFieldVal('sport', true);
  5069. const dport = getNATFieldVal('dport', true);
  5070. const anyport = getNATFieldVal('anyport', true);
  5071. let iniface = getNATFieldVal('iniface', true);
  5072. let outiface = getNATFieldVal('outiface', true);
  5073. let inifacelist = getNATFieldVal('inifacelist', true);
  5074. let outifacelist = getNATFieldVal('outifacelist', true);
  5075. if (chainLower === 'prerouting' || chainLower === 'input') {
  5076. outiface = '';
  5077. outifacelist = '';
  5078. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5079. iniface = '';
  5080. inifacelist = '';
  5081. }
  5082. const pktmark = getNATFieldVal('pktmark', true);
  5083. const connmark = getNATFieldVal('connmark', true);
  5084. const routingmark = getNATFieldVal('routingmark', true);
  5085. const conntype = getNATFieldVal('conntype', false);
  5086. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5087. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5088. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5089. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5090. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5091. switchNATRuleTab('general');
  5092. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5093. return;
  5094. }
  5095. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5096. switchNATRuleTab('general');
  5097. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5098. return;
  5099. }
  5100. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5101. switchNATRuleTab('general');
  5102. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5103. return;
  5104. }
  5105. if (usesAddr && !document.getElementById('nat-modal-toaddr').value.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter the destination IP / address for this action.', 'error'); document.getElementById('nat-modal-toaddr').focus(); return; }
  5106. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5107. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5108. showToast('Select protocol', 'Port rules require TCP or UDP. For DNS, create one UDP and one TCP rule.', 'error'); document.getElementById('nat-val-proto').focus(); return;
  5109. }
  5110. const payload = {
  5111. ip_version: Number(document.getElementById('nat-modal-family').value),
  5112. id,
  5113. chain,
  5114. action,
  5115. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5116. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5117. protocol: proto || 'all',
  5118. src_address: src,
  5119. dst_address: dst,
  5120. src_port: sport,
  5121. dst_port: dport,
  5122. any_port: anyport,
  5123. in_interface: iniface,
  5124. out_interface: outiface,
  5125. in_interface_list: inifacelist,
  5126. out_interface_list: outifacelist,
  5127. packet_mark: pktmark,
  5128. connection_mark: connmark,
  5129. routing_mark: routingmark,
  5130. connection_type: conntype,
  5131. src_address_list: srclist,
  5132. dst_address_list: dstlist,
  5133. src_geoip: srcgeo,
  5134. dst_geoip: dstgeo,
  5135. comment,
  5136. disabled: !enabled,
  5137. // Advanced tab
  5138. content: getNATFieldVal('content', false),
  5139. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5140. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5141. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5142. ipsec_policy: getNATFieldVal('ipsec', false),
  5143. dscp: getNATFieldVal('dscp', false),
  5144. tcp_mss: getNATFieldVal('tcpmss', false),
  5145. tos: document.getElementById('nat-val-tos')?.value || '',
  5146. packet_size: getNATFieldVal('pktsize', false),
  5147. random: getNATFieldVal('random', false),
  5148. icmp_options: getNATFieldVal('icmpoptions', false),
  5149. ttl: getNATFieldVal('ttl', false),
  5150. days: selectedDays,
  5151. // Extra tab
  5152. time: getNATFieldVal('time', false),
  5153. limit: getNATFieldVal('limit', false),
  5154. // Action tab
  5155. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5156. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5157. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5158. log: document.getElementById('nat-modal-log')?.checked || false,
  5159. log_prefix: getNATFieldVal('logprefix', false)
  5160. };
  5161. try {
  5162. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5163. method: 'POST',
  5164. headers: { 'Content-Type': 'application/json' },
  5165. body: JSON.stringify(payload)
  5166. });
  5167. if (res.ok) {
  5168. const data = await res.json();
  5169. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5170. loadFirewall(false);
  5171. if (closeAfter) {
  5172. closeNATModal();
  5173. } else {
  5174. if (data.id) {
  5175. document.getElementById('nat-modal-id').value = data.id;
  5176. const badge = document.getElementById('nat-modal-badge');
  5177. if (badge) badge.innerText = `#${data.id}`;
  5178. }
  5179. }
  5180. } else {
  5181. const err = await res.json();
  5182. showToast('Error', err.message || 'Failed to save rule', 'error');
  5183. }
  5184. } catch (err) {
  5185. showToast('Error', err.message, 'error');
  5186. }
  5187. }
  5188. function submitSaveNATRule(e) {
  5189. if (e && e.preventDefault) e.preventDefault();
  5190. return applyNATRule(true);
  5191. }
  5192. function startNATStatPolling() {
  5193. stopNATStatPolling();
  5194. pollNATRuleStats();
  5195. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5196. }
  5197. function stopNATStatPolling() {
  5198. if (state.natStatInterval) {
  5199. clearInterval(state.natStatInterval);
  5200. state.natStatInterval = null;
  5201. }
  5202. }
  5203. async function pollNATRuleStats() {
  5204. const id = document.getElementById('nat-modal-id')?.value;
  5205. if (!id) {
  5206. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5207. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5208. return;
  5209. }
  5210. try {
  5211. const res = await fetch(`${API_BASE}/firewall/nat`);
  5212. if (!res.ok) return;
  5213. const rules = await res.json();
  5214. const r = rules.find(x => x.id === id);
  5215. if (!r) return;
  5216. const now = Date.now();
  5217. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5218. state.natLastTimestamp = now;
  5219. const curBytes = r.bytes || 0;
  5220. const curPackets = r.packets || 0;
  5221. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5222. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5223. state.natLastBytes = curBytes;
  5224. state.natLastPackets = curPackets;
  5225. const rateBps = Math.round((deltaBytes * 8) / dt);
  5226. const ratePkt = Math.round(deltaPkts / dt);
  5227. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5228. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5229. state.natStatRateHistory.push(rateBps);
  5230. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5231. state.natStatPktHistory.push(ratePkt);
  5232. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5233. const bEl = document.getElementById('nat-stat-bytes');
  5234. const pEl = document.getElementById('nat-stat-packets');
  5235. const rEl = document.getElementById('nat-stat-rate');
  5236. const prEl = document.getElementById('nat-stat-pktrate');
  5237. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5238. if (pEl) pEl.value = curPackets.toLocaleString();
  5239. if (rEl) rEl.value = formatBps(rateBps);
  5240. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5241. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5242. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5243. } catch (e) {
  5244. console.error('Error polling NAT rule stats', e);
  5245. }
  5246. }
  5247. async function moveNATRule(id, dir) {
  5248. id = decodeURIComponent(id);
  5249. try {
  5250. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5251. method: 'POST',
  5252. headers: { 'Content-Type': 'application/json' },
  5253. body: JSON.stringify({ direction: dir })
  5254. });
  5255. if (!res.ok) throw new Error(await responseError(res));
  5256. await loadFirewall(false);
  5257. } catch (err) {
  5258. showToast('Error', err.message, 'error');
  5259. }
  5260. }
  5261. async function toggleNATRuleState(id, disabled) {
  5262. id = decodeURIComponent(id);
  5263. try {
  5264. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5265. method: 'POST',
  5266. headers: { 'Content-Type': 'application/json' },
  5267. body: JSON.stringify({ disabled })
  5268. });
  5269. if (!res.ok) throw new Error(await responseError(res));
  5270. await loadFirewall(false);
  5271. } catch (err) {
  5272. showToast('Error', err.message, 'error');
  5273. }
  5274. }
  5275. async function deleteNATRule(id) {
  5276. id = decodeURIComponent(id);
  5277. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5278. try {
  5279. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5280. if (!res.ok) throw new Error(await responseError(res));
  5281. {
  5282. showToast('Deleted', 'NAT rule removed', 'success');
  5283. loadFirewall(false);
  5284. }
  5285. } catch (err) {
  5286. showToast('Error', err.message, 'error');
  5287. }
  5288. }
  5289. // ----------------- Mangle Rules -----------------
  5290. function renderMangleRules() {
  5291. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5292. const tbody = document.getElementById('mangle-table-body');
  5293. const empty = document.getElementById('mangle-empty');
  5294. if (!tbody) return;
  5295. tbody.innerHTML = '';
  5296. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5297. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5298. if (rules.length === 0) {
  5299. empty?.classList.remove('hidden');
  5300. return;
  5301. }
  5302. empty?.classList.add('hidden');
  5303. rules.forEach((raw, idx) => {
  5304. const r = safeFirewallRow(raw);
  5305. const tr = document.createElement('tr');
  5306. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5307. let markVal = '<span class="text-slate-500">-</span>';
  5308. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5309. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5310. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5311. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5312. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5313. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5314. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5315. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5316. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5317. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5318. 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>`;
  5319. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5320. tr.innerHTML = `
  5321. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5322. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5323. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5324. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5325. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5326. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5327. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5328. <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>
  5329. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5330. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5331. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5332. </td>
  5333. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5334. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5335. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5336. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5337. <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>
  5338. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5339. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5340. </td>
  5341. `;
  5342. tbody.appendChild(tr);
  5343. });
  5344. }
  5345. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5346. function switchMangleRuleTab(tab) {
  5347. state.activeMangleRuleTab = tab;
  5348. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5349. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5350. btn.classList.add('text-slate-400', 'border-transparent');
  5351. });
  5352. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5353. if (activeBtn) {
  5354. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5355. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5356. }
  5357. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5358. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5359. if (activePane) activePane.classList.remove('hidden');
  5360. if (tab === 'statistics') {
  5361. startMangleStatPolling();
  5362. } else {
  5363. stopMangleStatPolling();
  5364. }
  5365. }
  5366. function toggleMangleField(fieldKey, expand) {
  5367. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5368. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5369. if (!plusBtn || !fieldBox) return;
  5370. if (expand) {
  5371. plusBtn.classList.add('hidden');
  5372. fieldBox.classList.remove('hidden');
  5373. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5374. if (valInput) valInput.focus();
  5375. } else {
  5376. fieldBox.classList.add('hidden');
  5377. plusBtn.classList.remove('hidden');
  5378. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5379. if (valInput) {
  5380. if (valInput.tagName === 'SELECT') {
  5381. valInput.selectedIndex = 0;
  5382. } else {
  5383. valInput.value = '';
  5384. }
  5385. }
  5386. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5387. if (invInput) invInput.checked = false;
  5388. if (fieldKey === 'cs') {
  5389. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5390. const el = document.getElementById(id);
  5391. if (el) el.checked = false;
  5392. });
  5393. }
  5394. if (fieldKey === 'natstate') {
  5395. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5396. const el = document.getElementById(id);
  5397. if (el) el.checked = false;
  5398. });
  5399. }
  5400. }
  5401. }
  5402. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5403. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5404. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5405. toggleMangleField(fieldKey, true);
  5406. let strVal = String(value);
  5407. if (hasInvert) {
  5408. const inv = strVal.startsWith('!');
  5409. if (inv) strVal = strVal.slice(1);
  5410. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5411. if (invEl) invEl.checked = inv;
  5412. else if (inv) strVal = '!'+strVal;
  5413. }
  5414. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5415. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  5416. } else {
  5417. toggleMangleField(fieldKey, false);
  5418. }
  5419. }
  5420. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5421. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5422. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5423. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5424. let v = valEl ? valEl.value.trim() : '';
  5425. if (!v) return '';
  5426. if (hasInvert) {
  5427. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5428. if (invEl && invEl.checked) {
  5429. v = '!' + v.replace(/^!/, '');
  5430. }
  5431. }
  5432. return v;
  5433. }
  5434. function toggleMaximizeMangleModal() {
  5435. const win = document.getElementById('mangle-modal-window');
  5436. if (!win) return;
  5437. if (win.classList.contains('max-w-[720px]')) {
  5438. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5439. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5440. } else {
  5441. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5442. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5443. }
  5444. }
  5445. function syncMangleChainFromSelect() {
  5446. const sel = document.getElementById('mangle-modal-chain-select');
  5447. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5448. const customInput = document.getElementById('mangle-modal-custom-input');
  5449. const chainInput = document.getElementById('mangle-modal-chain');
  5450. if (!sel || !chainInput) return;
  5451. if (sel.value === '__custom__') {
  5452. if (customWrap) customWrap.classList.remove('hidden');
  5453. if (customInput) {
  5454. customInput.value = '';
  5455. customInput.focus();
  5456. }
  5457. chainInput.value = '';
  5458. } else {
  5459. if (customWrap) customWrap.classList.add('hidden');
  5460. chainInput.value = sel.value;
  5461. }
  5462. handleMangleChainChange();
  5463. }
  5464. function syncMangleCustomChainInput() {
  5465. const customInput = document.getElementById('mangle-modal-custom-input');
  5466. const chainInput = document.getElementById('mangle-modal-chain');
  5467. if (customInput && chainInput) {
  5468. chainInput.value = customInput.value.trim();
  5469. }
  5470. handleMangleChainChange();
  5471. }
  5472. function handleMangleChainChange() {
  5473. const chainInput = document.getElementById('mangle-modal-chain');
  5474. const rawChain = (chainInput?.value || 'prerouting').trim();
  5475. const chain = rawChain.toLowerCase();
  5476. const sel = document.getElementById('mangle-modal-chain-select');
  5477. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5478. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5479. sel.value = chain;
  5480. }
  5481. }
  5482. const hintEl = document.getElementById('mangle-chain-hint');
  5483. if (hintEl) {
  5484. if (chain === 'prerouting') {
  5485. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5486. } else if (chain === 'input') {
  5487. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5488. } else if (chain === 'forward') {
  5489. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5490. } else if (chain === 'output') {
  5491. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5492. } else if (chain === 'postrouting') {
  5493. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5494. } else {
  5495. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5496. }
  5497. }
  5498. const rowIn = document.getElementById('mangle-row-iniface');
  5499. const rowInList = document.getElementById('mangle-row-inifacelist');
  5500. const rowOut = document.getElementById('mangle-row-outiface');
  5501. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5502. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5503. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5504. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5505. if (chain === 'prerouting' || chain === 'input') {
  5506. if (rowIn) rowIn.classList.remove('hidden');
  5507. if (rowInList) rowInList.classList.remove('hidden');
  5508. if (rowOut) rowOut.classList.add('hidden');
  5509. if (rowOutList) rowOutList.classList.add('hidden');
  5510. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5511. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5512. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5513. } else if (chain === 'output' || chain === 'postrouting') {
  5514. if (rowIn) rowIn.classList.add('hidden');
  5515. if (rowInList) rowInList.classList.add('hidden');
  5516. if (rowOut) rowOut.classList.remove('hidden');
  5517. if (rowOutList) rowOutList.classList.remove('hidden');
  5518. if (rowInBridge) rowInBridge.classList.add('hidden');
  5519. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5520. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5521. } else {
  5522. if (rowIn) rowIn.classList.remove('hidden');
  5523. if (rowInList) rowInList.classList.remove('hidden');
  5524. if (rowOut) rowOut.classList.remove('hidden');
  5525. if (rowOutList) rowOutList.classList.remove('hidden');
  5526. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5527. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5528. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5529. }
  5530. checkMangleActionChainCompatibility();
  5531. toggleMangleActionFields();
  5532. }
  5533. function checkMangleActionChainCompatibility() {
  5534. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5535. const chain = rawChain.toLowerCase();
  5536. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5537. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5538. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5539. if (!warnBox || !warnMsg) return;
  5540. let msg = '';
  5541. if (action === 'set-priority' && chain !== 'postrouting') {
  5542. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5543. }
  5544. if (msg) {
  5545. warnMsg.textContent = msg;
  5546. warnBox.classList.remove('hidden');
  5547. } else {
  5548. warnBox.classList.add('hidden');
  5549. }
  5550. }
  5551. function toggleMangleActionFields() {
  5552. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5553. // Hide all dynamic rows first
  5554. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5555. const el = document.getElementById(`mangle-row-${id}`);
  5556. if (el) el.classList.add('hidden');
  5557. });
  5558. const jumpBox = document.getElementById('mangle-action-jump-box');
  5559. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5560. if (jumpBox) jumpBox.classList.add('hidden');
  5561. if (addrBox) addrBox.classList.add('hidden');
  5562. // Activate matching rows
  5563. if (act === 'mark-connection') {
  5564. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5565. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5566. } else if (act === 'mark-routing') {
  5567. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5568. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5569. } else if (act === 'mark-packet') {
  5570. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5571. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5572. } else if (act === 'change-mss') {
  5573. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5574. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5575. } else if (act === 'change-dscp') {
  5576. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5577. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5578. } else if (act === 'change-ttl') {
  5579. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5580. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5581. } else if (act === 'set-priority') {
  5582. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5583. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5584. } else if (act === 'route') {
  5585. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5586. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5587. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5588. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5589. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5590. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5591. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5592. } else if (act === 'jump') {
  5593. if (jumpBox) jumpBox.classList.remove('hidden');
  5594. } else if (act.includes('address-list') || act.includes('address list')) {
  5595. if (addrBox) addrBox.classList.remove('hidden');
  5596. }
  5597. if (act === 'log') {
  5598. const logEl = document.getElementById('mangle-modal-log');
  5599. if (logEl) logEl.checked = true;
  5600. toggleMangleField('logprefix', true);
  5601. }
  5602. checkMangleActionChainCompatibility();
  5603. }
  5604. function toggleMangleLogPrefix() {
  5605. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5606. toggleMangleField('logprefix', !!isLog);
  5607. }
  5608. const allMangleFieldKeys = [
  5609. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5610. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5611. 'routingmark', 'conntype', 'cs', 'natstate',
  5612. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5613. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5614. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5615. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5616. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5617. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5618. ];
  5619. function openAddMangleModal() {
  5620. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5621. switchMangleRuleTab('general');
  5622. const badge = document.getElementById('mangle-modal-badge');
  5623. if (badge) badge.innerText = 'New...';
  5624. document.getElementById('mangle-modal-id').value = '';
  5625. document.getElementById('mangle-modal-family').value = '4';
  5626. document.getElementById('mangle-modal-enabled').checked = true;
  5627. document.getElementById('mangle-modal-comment').value = '';
  5628. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5629. populateChainDropdown('mangle', 'prerouting');
  5630. handleMangleChainChange();
  5631. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5632. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5633. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5634. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5635. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5636. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5637. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5638. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5639. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5640. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5641. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5642. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5643. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5644. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5645. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5646. populateInterfaceSelect('mangle-val-iniface');
  5647. populateInterfaceSelect('mangle-val-outiface');
  5648. populateAddressListSelect('mangle-val-srclist');
  5649. populateAddressListSelect('mangle-val-dstlist');
  5650. populateGeoIPSelect('mangle-val-srcgeo');
  5651. populateGeoIPSelect('mangle-val-dstgeo');
  5652. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5653. resetMangleCounterDisplay();
  5654. toggleMangleActionFields();
  5655. document.getElementById('mangle-modal').classList.remove('hidden');
  5656. }
  5657. function openEditMangleModal(id) {
  5658. id = decodeURIComponent(id);
  5659. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5660. if (!r) return;
  5661. switchMangleRuleTab('general');
  5662. const badge = document.getElementById('mangle-modal-badge');
  5663. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5664. document.getElementById('mangle-modal-id').value = r.id;
  5665. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5666. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5667. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5668. const mangleChain = r.chain || 'prerouting';
  5669. document.getElementById('mangle-modal-chain').value = mangleChain;
  5670. populateChainDropdown('mangle', mangleChain);
  5671. handleMangleChainChange();
  5672. setFirewallActionSelection('mangle', r.action || 'accept');
  5673. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5674. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5675. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5676. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5677. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5678. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5679. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5680. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5681. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5682. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5683. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5684. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5685. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5686. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5687. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5688. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5689. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5690. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5691. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5692. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5693. setMangleFieldVal('src', r.src_address, true);
  5694. setMangleFieldVal('dst', r.dst_address, true);
  5695. setMangleFieldVal('srclist', r.src_address_list, true);
  5696. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5697. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5698. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5699. if (r.protocol && r.protocol !== 'all') {
  5700. setMangleFieldVal('proto', r.protocol, true);
  5701. } else {
  5702. toggleMangleField('proto', false);
  5703. }
  5704. setMangleFieldVal('sport', r.src_port, true);
  5705. setMangleFieldVal('dport', r.dst_port, true);
  5706. setMangleFieldVal('anyport', r.any_port, true);
  5707. setMangleFieldVal('iniface', r.in_interface, true);
  5708. setMangleFieldVal('outiface', r.out_interface, true);
  5709. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5710. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5711. setMangleFieldVal('pktmark', r.packet_mark, true);
  5712. setMangleFieldVal('connmark', r.connection_mark, true);
  5713. setMangleFieldVal('routingmark', r.routing_mark, true);
  5714. setMangleFieldVal('conntype', r.connection_type, false);
  5715. // Connection State
  5716. const states = r.connection_state || [];
  5717. if (states.length > 0) {
  5718. toggleMangleField('cs', true);
  5719. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5720. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5721. if (el) el.checked = states.includes(s);
  5722. });
  5723. } else {
  5724. toggleMangleField('cs', false);
  5725. }
  5726. // Connection NAT State
  5727. const natStates = r.connection_nat_state || [];
  5728. if (natStates.length > 0) {
  5729. toggleMangleField('natstate', true);
  5730. ['srcnat', 'dstnat'].forEach(s => {
  5731. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5732. if (el) el.checked = natStates.includes(s);
  5733. });
  5734. } else {
  5735. toggleMangleField('natstate', false);
  5736. }
  5737. // Advanced tab fields
  5738. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5739. setMangleFieldVal('content', r.content, false);
  5740. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5741. setMangleFieldVal('connrate', r.connection_rate, false);
  5742. setMangleFieldVal('pcc', r.pcc, false);
  5743. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5744. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5745. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5746. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5747. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5748. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5749. setMangleFieldVal('tlshost', r.tls_host, false);
  5750. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5751. setMangleFieldVal('priority', r.priority, false);
  5752. setMangleFieldVal('dscp', r.dscp, false);
  5753. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5754. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5755. setMangleFieldVal('pktsize', r.packet_size, false);
  5756. setMangleFieldVal('random', r.random, false);
  5757. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5758. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5759. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5760. setMangleFieldVal('ttl', r.ttl, false);
  5761. // Extra tab fields
  5762. setMangleFieldVal('nth', r.nth, false);
  5763. setMangleFieldVal('connlimit', r.connection_limit, false);
  5764. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5765. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5766. setMangleFieldVal('hotspot', r.hotspot, false);
  5767. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5768. setMangleFieldVal('limit', r.limit, false);
  5769. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5770. setMangleFieldVal('time', r.time, false);
  5771. setMangleFieldVal('psd', r.psd, false);
  5772. // Action fields
  5773. if (r.jump_target) {
  5774. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5775. if (jtEl) jtEl.value = r.jump_target;
  5776. }
  5777. if (r.address_list) {
  5778. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5779. if (alEl) alEl.value = r.address_list;
  5780. }
  5781. if (r.address_list_timeout) {
  5782. const toEl = document.getElementById('mangle-modal-action-timeout');
  5783. if (toEl) toEl.value = r.address_list_timeout;
  5784. }
  5785. setMangleFieldVal('logprefix', r.log_prefix, false);
  5786. // Statistics
  5787. const bEl = document.getElementById('mangle-stat-bytes');
  5788. const pEl = document.getElementById('mangle-stat-packets');
  5789. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5790. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5791. state.mangleLastBytes = r.bytes || 0;
  5792. state.mangleLastPackets = r.packets || 0;
  5793. state.mangleLastTimestamp = Date.now();
  5794. state.mangleStatRateHistory = new Array(30).fill(0);
  5795. state.mangleStatPktHistory = new Array(30).fill(0);
  5796. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5797. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5798. toggleMangleActionFields();
  5799. document.getElementById('mangle-modal').classList.remove('hidden');
  5800. }
  5801. function closeMangleModal() {
  5802. stopMangleStatPolling();
  5803. document.getElementById('mangle-modal').classList.add('hidden');
  5804. }
  5805. function copyMangleRule() {
  5806. document.getElementById('mangle-modal-id').value = '';
  5807. const badge = document.getElementById('mangle-modal-badge');
  5808. if (badge) badge.innerText = 'New...';
  5809. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5810. }
  5811. function resetMangleCounterDisplay() {
  5812. state.mangleStatRateHistory = new Array(30).fill(0);
  5813. state.mangleStatPktHistory = new Array(30).fill(0);
  5814. state.mangleLastBytes = 0;
  5815. state.mangleLastPackets = 0;
  5816. state.mangleLastTimestamp = Date.now();
  5817. const bEl = document.getElementById('mangle-stat-bytes');
  5818. const pEl = document.getElementById('mangle-stat-packets');
  5819. const rEl = document.getElementById('mangle-stat-rate');
  5820. const prEl = document.getElementById('mangle-stat-pktrate');
  5821. if (bEl) bEl.value = '0 B';
  5822. if (pEl) pEl.value = '0';
  5823. if (rEl) rEl.value = '0 bps';
  5824. if (prEl) prEl.value = '0 p/s';
  5825. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5826. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5827. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5828. }
  5829. async function applyMangleRule(closeAfter = false) {
  5830. const id = document.getElementById('mangle-modal-id').value;
  5831. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5832. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5833. const chainLower = chain.toLowerCase();
  5834. const action = document.getElementById('mangle-modal-action').value;
  5835. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5836. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5837. const src = getMangleFieldVal('src', true);
  5838. const dst = getMangleFieldVal('dst', true);
  5839. const srclist = getMangleFieldVal('srclist', true);
  5840. const dstlist = getMangleFieldVal('dstlist', true);
  5841. const srcgeo = getMangleFieldVal('srcgeo', true);
  5842. const dstgeo = getMangleFieldVal('dstgeo', true);
  5843. const proto = getMangleFieldVal('proto', true);
  5844. const sport = getMangleFieldVal('sport', true);
  5845. const dport = getMangleFieldVal('dport', true);
  5846. const anyport = getMangleFieldVal('anyport', true);
  5847. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5848. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5849. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5850. }
  5851. let iniface = getMangleFieldVal('iniface', true);
  5852. let outiface = getMangleFieldVal('outiface', true);
  5853. let inifacelist = getMangleFieldVal('inifacelist', true);
  5854. let outifacelist = getMangleFieldVal('outifacelist', true);
  5855. if (chainLower === 'prerouting' || chainLower === 'input') {
  5856. outiface = '';
  5857. outifacelist = '';
  5858. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5859. iniface = '';
  5860. inifacelist = '';
  5861. }
  5862. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5863. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5864. switchMangleRuleTab('general');
  5865. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5866. return;
  5867. }
  5868. const pktmark = getMangleFieldVal('pktmark', true);
  5869. const connmark = getMangleFieldVal('connmark', true);
  5870. const routingmark = getMangleFieldVal('routingmark', true);
  5871. const conntype = getMangleFieldVal('conntype', false);
  5872. const states = [];
  5873. const csBox = document.getElementById('mangle-field-cs');
  5874. if (csBox && !csBox.classList.contains('hidden')) {
  5875. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5876. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5877. });
  5878. }
  5879. const natStates = [];
  5880. const natBox = document.getElementById('mangle-field-natstate');
  5881. if (natBox && !natBox.classList.contains('hidden')) {
  5882. ['srcnat', 'dstnat'].forEach(s => {
  5883. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5884. });
  5885. }
  5886. const payload = {
  5887. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5888. id,
  5889. chain,
  5890. action,
  5891. protocol: proto || 'all',
  5892. src_address: src,
  5893. dst_address: dst,
  5894. src_port: sport,
  5895. dst_port: dport,
  5896. any_port: anyport,
  5897. in_interface: iniface,
  5898. out_interface: outiface,
  5899. in_interface_list: inifacelist,
  5900. out_interface_list: outifacelist,
  5901. packet_mark: pktmark,
  5902. connection_mark: connmark,
  5903. routing_mark: routingmark,
  5904. connection_type: conntype,
  5905. connection_state: states,
  5906. connection_nat_state: natStates,
  5907. src_address_list: srclist,
  5908. dst_address_list: dstlist,
  5909. src_geoip: srcgeo,
  5910. dst_geoip: dstgeo,
  5911. comment,
  5912. disabled: !enabled,
  5913. // Advanced tab
  5914. content: getMangleFieldVal('content', false),
  5915. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5916. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5917. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5918. ipsec_policy: getMangleFieldVal('ipsec', false),
  5919. dscp: getMangleFieldVal('dscp', false),
  5920. tcp_mss: getMangleFieldVal('tcpmss', false),
  5921. tos: document.getElementById('mangle-val-tos')?.value || '',
  5922. packet_size: getMangleFieldVal('pktsize', false),
  5923. random: getMangleFieldVal('random', false),
  5924. tcp_flags: getMangleFieldVal('tcpflags', false),
  5925. icmp_options: getMangleFieldVal('icmpoptions', false),
  5926. ttl: getMangleFieldVal('ttl', false),
  5927. // Extra tab
  5928. nth: getMangleFieldVal('nth', false),
  5929. connection_limit: getMangleFieldVal('connlimit', false),
  5930. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5931. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5932. ip_fragment: getMangleFieldVal('ipfragment', false),
  5933. limit: getMangleFieldVal('limit', false),
  5934. time: getMangleFieldVal('time', false),
  5935. // Action tab
  5936. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5937. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5938. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5939. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5940. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5941. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5942. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5943. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5944. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5945. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5946. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5947. log: document.getElementById('mangle-modal-log')?.checked || false,
  5948. log_prefix: getMangleFieldVal('logprefix', false)
  5949. };
  5950. try {
  5951. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5952. method: 'POST',
  5953. headers: { 'Content-Type': 'application/json' },
  5954. body: JSON.stringify(payload)
  5955. });
  5956. if (res.ok) {
  5957. const data = await res.json();
  5958. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5959. loadFirewall(false);
  5960. if (closeAfter) {
  5961. closeMangleModal();
  5962. } else {
  5963. if (data.id) {
  5964. document.getElementById('mangle-modal-id').value = data.id;
  5965. const badge = document.getElementById('mangle-modal-badge');
  5966. if (badge) badge.innerText = `#${data.id}`;
  5967. }
  5968. }
  5969. } else {
  5970. const err = await res.json();
  5971. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5972. }
  5973. } catch (err) {
  5974. showToast('Error', err.message, 'error');
  5975. }
  5976. }
  5977. function submitSaveMangleRule(e) {
  5978. if (e && e.preventDefault) e.preventDefault();
  5979. return applyMangleRule(true);
  5980. }
  5981. function startMangleStatPolling() {
  5982. stopMangleStatPolling();
  5983. pollMangleRuleStats();
  5984. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5985. }
  5986. function stopMangleStatPolling() {
  5987. if (state.mangleStatInterval) {
  5988. clearInterval(state.mangleStatInterval);
  5989. state.mangleStatInterval = null;
  5990. }
  5991. }
  5992. async function pollMangleRuleStats() {
  5993. const id = document.getElementById('mangle-modal-id')?.value;
  5994. if (!id) {
  5995. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5996. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5997. return;
  5998. }
  5999. try {
  6000. const res = await fetch(`${API_BASE}/firewall/mangle`);
  6001. if (!res.ok) return;
  6002. const rules = await res.json();
  6003. const r = rules.find(x => x.id === id);
  6004. if (!r) return;
  6005. const now = Date.now();
  6006. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  6007. state.mangleLastTimestamp = now;
  6008. const curBytes = r.bytes || 0;
  6009. const curPackets = r.packets || 0;
  6010. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  6011. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  6012. state.mangleLastBytes = curBytes;
  6013. state.mangleLastPackets = curPackets;
  6014. const rateBps = Math.round((deltaBytes * 8) / dt);
  6015. const ratePkt = Math.round(deltaPkts / dt);
  6016. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  6017. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  6018. state.mangleStatRateHistory.push(rateBps);
  6019. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  6020. state.mangleStatPktHistory.push(ratePkt);
  6021. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  6022. const bEl = document.getElementById('mangle-stat-bytes');
  6023. const pEl = document.getElementById('mangle-stat-packets');
  6024. const rEl = document.getElementById('mangle-stat-rate');
  6025. const prEl = document.getElementById('mangle-stat-pktrate');
  6026. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  6027. if (pEl) pEl.value = curPackets.toLocaleString();
  6028. if (rEl) rEl.value = formatBps(rateBps);
  6029. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  6030. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  6031. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  6032. } catch (e) {
  6033. console.error('Error polling Mangle rule stats', e);
  6034. }
  6035. }
  6036. async function moveMangleRule(id, dir) {
  6037. id = decodeURIComponent(id);
  6038. try {
  6039. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  6040. method: 'POST',
  6041. headers: { 'Content-Type': 'application/json' },
  6042. body: JSON.stringify({ direction: dir })
  6043. });
  6044. if (!res.ok) throw new Error(await responseError(res));
  6045. await loadFirewall(false);
  6046. } catch (err) {
  6047. showToast('Error', err.message, 'error');
  6048. }
  6049. }
  6050. async function toggleMangleRuleState(id, disabled) {
  6051. id = decodeURIComponent(id);
  6052. try {
  6053. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6054. method: 'POST',
  6055. headers: { 'Content-Type': 'application/json' },
  6056. body: JSON.stringify({ disabled })
  6057. });
  6058. if (!res.ok) throw new Error(await responseError(res));
  6059. await loadFirewall(false);
  6060. } catch (err) {
  6061. showToast('Error', err.message, 'error');
  6062. }
  6063. }
  6064. async function deleteMangleRule(id) {
  6065. id = decodeURIComponent(id);
  6066. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6067. try {
  6068. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6069. if (!res.ok) throw new Error(await responseError(res));
  6070. {
  6071. showToast('Deleted', 'Mangle rule removed', 'success');
  6072. loadFirewall(false);
  6073. }
  6074. } catch (err) {
  6075. showToast('Error', err.message, 'error');
  6076. }
  6077. }
  6078. // ----------------- Address Lists -----------------
  6079. function renderAddressLists() {
  6080. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6081. const tbody = document.getElementById('addrlist-table-body');
  6082. const empty = document.getElementById('addrlist-empty');
  6083. if (!tbody) return;
  6084. tbody.innerHTML = '';
  6085. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6086. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6087. // Update filter select
  6088. const sel = document.getElementById('addrlist-filter-name');
  6089. if (sel) {
  6090. const cur = sel.value;
  6091. sel.innerHTML = '<option value="">All Lists</option>';
  6092. const set = new Set((state.addressLists || []).map(a => a.name));
  6093. set.forEach(n => {
  6094. const opt = document.createElement('option');
  6095. opt.value = n;
  6096. opt.innerText = n;
  6097. if (n === cur) opt.selected = true;
  6098. sel.appendChild(opt);
  6099. });
  6100. }
  6101. if (entries.length === 0) {
  6102. empty?.classList.remove('hidden');
  6103. return;
  6104. }
  6105. empty?.classList.add('hidden');
  6106. entries.forEach((raw, idx) => {
  6107. const e = safeFirewallRow(raw);
  6108. const tr = document.createElement('tr');
  6109. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6110. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6111. tr.innerHTML = `
  6112. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6113. <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>
  6114. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6115. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6116. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.dynamic ? 'Dynamic · '+(e.timeout ? e.timeout+'s remaining' : 'no expiry') : e.comment || '-'}</td>
  6117. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6118. ${e.dynamic ? '' : ` <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>
  6119. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6120. `}
  6121. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6122. </td>
  6123. `;
  6124. tbody.appendChild(tr);
  6125. });
  6126. populateCommonAddrListDatalist();
  6127. }
  6128. function openAddAddrListModal() {
  6129. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6130. document.getElementById('addrlist-modal-id').value = '';
  6131. document.getElementById('addrlist-modal-name').value = '';
  6132. document.getElementById('addrlist-modal-addr').value = '';
  6133. document.getElementById('addrlist-modal-comment').value = '';
  6134. document.getElementById('addrlist-modal-disabled').checked = false;
  6135. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6136. if (submitBtn) submitBtn.innerText = 'Add to List';
  6137. document.getElementById('addrlist-modal').classList.remove('hidden');
  6138. }
  6139. function openEditAddrListModal(id) {
  6140. id = decodeURIComponent(id);
  6141. const e = (state.addressLists || []).find(item => item.id === id);
  6142. if (!e) return;
  6143. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6144. document.getElementById('addrlist-modal-id').value = e.id;
  6145. document.getElementById('addrlist-modal-name').value = e.name;
  6146. document.getElementById('addrlist-modal-addr').value = e.address;
  6147. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6148. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6149. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6150. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6151. document.getElementById('addrlist-modal').classList.remove('hidden');
  6152. }
  6153. function closeAddrListModal() {
  6154. document.getElementById('addrlist-modal').classList.add('hidden');
  6155. }
  6156. async function submitSaveAddrList(e) {
  6157. e.preventDefault();
  6158. const id = document.getElementById('addrlist-modal-id').value;
  6159. const name = document.getElementById('addrlist-modal-name').value.trim();
  6160. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6161. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6162. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6163. try {
  6164. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6165. method: 'POST',
  6166. headers: { 'Content-Type': 'application/json' },
  6167. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6168. });
  6169. if (res.ok) {
  6170. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6171. closeAddrListModal();
  6172. loadFirewall(false);
  6173. } else {
  6174. const err = await res.json();
  6175. showToast('Error', err.message || 'Failed to save address list', 'error');
  6176. }
  6177. } catch (err) {
  6178. showToast('Error', err.message, 'error');
  6179. }
  6180. }
  6181. async function toggleAddrListState(id, disabled) {
  6182. id = decodeURIComponent(id);
  6183. try {
  6184. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6185. method: 'POST',
  6186. headers: { 'Content-Type': 'application/json' },
  6187. body: JSON.stringify({ disabled })
  6188. });
  6189. if (res.ok) {
  6190. loadFirewall(false);
  6191. }
  6192. } catch (err) {
  6193. showToast('Error', err.message, 'error');
  6194. }
  6195. }
  6196. async function deleteAddrList(id) {
  6197. id = decodeURIComponent(id);
  6198. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6199. try {
  6200. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6201. if (res.ok) {
  6202. showToast('Deleted', 'Address list item removed', 'info');
  6203. loadFirewall(false);
  6204. }
  6205. } catch (err) {
  6206. showToast('Error', err.message, 'error');
  6207. }
  6208. }
  6209. // ----------------- Geo-Location IP Management -----------------
  6210. async function loadGeoIP() {
  6211. try {
  6212. const [statusRes, countriesRes] = await Promise.all([
  6213. fetch(`${API_BASE}/firewall/geoip/status`),
  6214. fetch(`${API_BASE}/firewall/geoip/countries`)
  6215. ]);
  6216. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6217. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6218. updateGeoHeader();
  6219. renderGeoCountries();
  6220. } catch (err) {
  6221. console.error('Failed to load GeoIP:', err);
  6222. }
  6223. }
  6224. function getGeoUsageMap() {
  6225. const usage = {};
  6226. const checkRule = (r, type) => {
  6227. ['src_geoip', 'dst_geoip'].forEach(field => {
  6228. let val = (r && r[field]) || '';
  6229. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6230. if (code) {
  6231. if (!usage[code]) usage[code] = [];
  6232. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6233. if (!usage[code].includes(label)) usage[code].push(label);
  6234. }
  6235. });
  6236. };
  6237. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6238. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6239. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6240. return usage;
  6241. }
  6242. function updateGeoHeader() {
  6243. const s = state.geoStatus || {};
  6244. const statusBadge = document.getElementById('geo-status-badge');
  6245. if (statusBadge) {
  6246. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6247. statusBadge.className = s.auto_update
  6248. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6249. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6250. }
  6251. const intervalLabel = document.getElementById('geo-interval-label');
  6252. if (intervalLabel) {
  6253. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6254. }
  6255. const usageMap = getGeoUsageMap();
  6256. const inUseCount = Object.keys(usageMap).length;
  6257. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6258. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6259. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6260. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6261. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6262. if (lastSyncEl) {
  6263. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6264. const d = new Date(s.last_updated);
  6265. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6266. } else {
  6267. lastSyncEl.innerText = 'Never (Sync Pending)';
  6268. }
  6269. }
  6270. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6271. if (nextSyncEl) {
  6272. if (s.next_update && !s.next_update.startsWith('0001')) {
  6273. const d = new Date(s.next_update);
  6274. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6275. } else {
  6276. nextSyncEl.innerText = '-';
  6277. }
  6278. }
  6279. const badge = document.getElementById('fw-badge-geo');
  6280. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6281. }
  6282. function renderGeoCountries() {
  6283. const tbody = document.getElementById('geo-table-body');
  6284. const empty = document.getElementById('geo-empty');
  6285. if (!tbody) return;
  6286. tbody.innerHTML = '';
  6287. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6288. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6289. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6290. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6291. const usageMap = getGeoUsageMap();
  6292. const countries = (state.geoCountries || []).filter(c => {
  6293. const isUsed = !!usageMap[c.code];
  6294. if (inUseOnly && !isUsed) return false;
  6295. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6296. if (continent && c.continent !== continent) return false;
  6297. if (q) {
  6298. const matchCode = c.code.toLowerCase().includes(q);
  6299. const matchName = c.name.toLowerCase().includes(q);
  6300. if (!matchCode && !matchName) return false;
  6301. }
  6302. return true;
  6303. });
  6304. if (countries.length === 0) {
  6305. empty?.classList.remove('hidden');
  6306. return;
  6307. }
  6308. empty?.classList.add('hidden');
  6309. countries.forEach(c => {
  6310. const tr = document.createElement('tr');
  6311. const isUsed = !!usageMap[c.code];
  6312. const rulesUsing = usageMap[c.code] || [];
  6313. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6314. let statusHtml = '';
  6315. if (isUsed) {
  6316. 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>`;
  6317. } else if (c.subnet_count > 0) {
  6318. 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>';
  6319. } else {
  6320. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6321. }
  6322. tr.innerHTML = `
  6323. <td class="py-2.5 px-3 text-center">
  6324. <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'}">
  6325. ${c.code}
  6326. </span>
  6327. </td>
  6328. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6329. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6330. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6331. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6332. </td>
  6333. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6334. <td class="py-2.5 px-3">
  6335. ${statusHtml}
  6336. </td>
  6337. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6338. <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>
  6339. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6340. </td>
  6341. `;
  6342. tbody.appendChild(tr);
  6343. });
  6344. }
  6345. function quickFilterGeo(preset) {
  6346. const searchInput = document.getElementById('geo-search-input');
  6347. const continentSel = document.getElementById('geo-continent-filter');
  6348. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6349. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6350. if (searchInput) searchInput.value = '';
  6351. if (continentSel) continentSel.value = '';
  6352. if (inUseCheck) inUseCheck.checked = false;
  6353. if (cachedCheck) cachedCheck.checked = false;
  6354. if (preset === 'GR') {
  6355. if (searchInput) searchInput.value = 'Greece';
  6356. } else if (preset === 'Europe') {
  6357. if (continentSel) continentSel.value = 'Europe';
  6358. } else if (preset === 'HIGHRISK') {
  6359. if (searchInput) searchInput.value = 'China';
  6360. }
  6361. renderGeoCountries();
  6362. }
  6363. async function toggleGeoCountry(code, enabled) {
  6364. try {
  6365. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6366. method: 'POST',
  6367. headers: { 'Content-Type': 'application/json' },
  6368. body: JSON.stringify({ enabled })
  6369. });
  6370. if (res.ok) {
  6371. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6372. loadGeoIP();
  6373. } else {
  6374. const err = await res.json();
  6375. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6376. }
  6377. } catch (err) {
  6378. showToast('Error', err.message, 'error');
  6379. }
  6380. }
  6381. async function updateGeoCountry(code) {
  6382. try {
  6383. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6384. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6385. if (res.ok) {
  6386. const data = await res.json();
  6387. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6388. loadGeoIP();
  6389. } else {
  6390. const err = await res.json();
  6391. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6392. }
  6393. } catch (err) {
  6394. showToast('Error', err.message, 'error');
  6395. }
  6396. }
  6397. async function triggerGeoUpdateNow() {
  6398. const spinner = document.getElementById('geo-update-spinner');
  6399. if (spinner) spinner.classList.remove('hidden');
  6400. try {
  6401. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6402. if (res.ok) {
  6403. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6404. setTimeout(() => {
  6405. loadGeoIP();
  6406. if (spinner) spinner.classList.add('hidden');
  6407. }, 2500);
  6408. } else {
  6409. const err = await res.json();
  6410. showToast('Notice', err.message || 'Update in progress', 'info');
  6411. if (spinner) spinner.classList.add('hidden');
  6412. }
  6413. } catch (err) {
  6414. showToast('Error', err.message, 'error');
  6415. if (spinner) spinner.classList.add('hidden');
  6416. }
  6417. }
  6418. async function applyGeoPreset(preset) {
  6419. try {
  6420. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6421. method: 'POST',
  6422. headers: { 'Content-Type': 'application/json' },
  6423. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6424. });
  6425. if (res.ok) {
  6426. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6427. loadGeoIP();
  6428. }
  6429. } catch (err) {
  6430. showToast('Error', err.message, 'error');
  6431. }
  6432. }
  6433. function openGeoIntervalModal() {
  6434. const s = state.geoStatus || {};
  6435. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6436. const sel = document.getElementById('geo-cfg-interval');
  6437. const customBox = document.getElementById('geo-cfg-custom-box');
  6438. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6439. const curHours = s.interval_hours || 24;
  6440. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6441. if (matchOption) {
  6442. sel.value = String(curHours);
  6443. customBox.classList.add('hidden');
  6444. } else {
  6445. sel.value = 'custom';
  6446. customHoursInput.value = curHours;
  6447. customBox.classList.remove('hidden');
  6448. }
  6449. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6450. }
  6451. function closeGeoIntervalModal() {
  6452. document.getElementById('geo-interval-modal').classList.add('hidden');
  6453. }
  6454. function toggleCustomGeoInterval() {
  6455. const val = document.getElementById('geo-cfg-interval').value;
  6456. const customBox = document.getElementById('geo-cfg-custom-box');
  6457. if (val === 'custom') {
  6458. customBox.classList.remove('hidden');
  6459. } else {
  6460. customBox.classList.add('hidden');
  6461. }
  6462. }
  6463. async function submitGeoIntervalSettings(e) {
  6464. e.preventDefault();
  6465. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6466. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6467. let hours = 24;
  6468. if (intervalVal === 'custom') {
  6469. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6470. } else {
  6471. hours = parseInt(intervalVal, 10) || 24;
  6472. }
  6473. try {
  6474. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6475. method: 'POST',
  6476. headers: { 'Content-Type': 'application/json' },
  6477. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6478. });
  6479. if (res.ok) {
  6480. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6481. closeGeoIntervalModal();
  6482. loadGeoIP();
  6483. } else {
  6484. const err = await res.json();
  6485. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6486. }
  6487. } catch (err) {
  6488. showToast('Error', err.message, 'error');
  6489. }
  6490. }
  6491. async function viewGeoSubnets(code, name) {
  6492. if (!name) {
  6493. const found = (state.geoCountries || []).find(x => x.code === code);
  6494. name = found ? found.name : code;
  6495. }
  6496. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6497. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6498. const listEl = document.getElementById('geo-subnets-list');
  6499. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6500. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6501. try {
  6502. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6503. if (res.ok) {
  6504. const data = await res.json();
  6505. const subnets = data.subnets || [];
  6506. if (subnets.length === 0) {
  6507. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6508. } else {
  6509. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6510. }
  6511. } else {
  6512. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6513. }
  6514. } catch (err) {
  6515. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6516. }
  6517. }
  6518. function closeGeoSubnetsModal() {
  6519. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6520. }
  6521. // ----------------- Active Connections Tracking -----------------
  6522. async function loadConnections() {
  6523. try {
  6524. const res = await fetch(`${API_BASE}/firewall/connections`);
  6525. const data = await res.json();
  6526. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6527. state.connections = Array.isArray(data) ? data : [];
  6528. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6529. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6530. renderConnections();
  6531. } catch (err) {
  6532. console.error('Failed to load connections:', err);
  6533. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6534. }
  6535. }
  6536. function renderConnections() {
  6537. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6538. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6539. const tbody = document.getElementById('conns-table-body');
  6540. const empty = document.getElementById('conns-empty');
  6541. if (!tbody) return;
  6542. tbody.innerHTML = '';
  6543. const conns = (state.connections || []).filter(c => {
  6544. if (protoFilter && c.protocol !== protoFilter) return false;
  6545. if (search) {
  6546. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6547. if (!line.includes(search)) return false;
  6548. }
  6549. return true;
  6550. });
  6551. if (conns.length === 0) {
  6552. empty?.classList.remove('hidden');
  6553. return;
  6554. }
  6555. empty?.classList.add('hidden');
  6556. conns.slice(0, 150).forEach(c => {
  6557. const tr = document.createElement('tr');
  6558. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6559. let stateColor = 'text-slate-400';
  6560. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6561. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6562. tr.innerHTML = `
  6563. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6564. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6565. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6566. <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>
  6567. <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>
  6568. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6569. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6570. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6571. <td class="py-2.5 px-3 text-right font-sans">
  6572. ${['TCP','UDP','SCTP','DCCP','ICMP','ICMPV6'].includes(c.protocol) ? ` <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port}, ${c.ip_version || 4}, ${c.zone || 0}, ${c.icmp_id ?? 'null'}, ${c.icmp_type ?? 'null'}, ${c.icmp_code ?? 'null'})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>` : ''}
  6573. </td>
  6574. `;
  6575. tbody.appendChild(tr);
  6576. });
  6577. }
  6578. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6579. try {
  6580. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6581. method: 'POST',
  6582. headers: { 'Content-Type': 'application/json' },
  6583. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6584. });
  6585. if (res.ok) {
  6586. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6587. loadConnections();
  6588. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6589. } catch (err) {
  6590. showToast('Error', err.message, 'error');
  6591. }
  6592. }
  6593. async function resetFirewallCounters() {
  6594. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6595. try {
  6596. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6597. if (res.ok) {
  6598. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6599. loadFirewall(false);
  6600. }
  6601. } catch (err) {
  6602. showToast('Error', err.message, 'error');
  6603. }
  6604. }
  6605. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6606. function switchRoutesSubTab(tab) {
  6607. state.routesSubTab = tab;
  6608. const tabs = ['routes', 'rules', 'tables'];
  6609. tabs.forEach(t => {
  6610. const panel = document.getElementById(`routes-subtab-${t}`);
  6611. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6612. if (panel) {
  6613. if (t === tab) panel.classList.remove('hidden');
  6614. else panel.classList.add('hidden');
  6615. }
  6616. if (btn) {
  6617. if (t === tab) {
  6618. 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';
  6619. } else {
  6620. 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';
  6621. }
  6622. }
  6623. });
  6624. setTimeout(initTableSorting, 50);
  6625. }
  6626. async function loadRoutes() {
  6627. try {
  6628. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6629. fetch(`${API_BASE}/routes`),
  6630. fetch(`${API_BASE}/routing/rules`),
  6631. fetch(`${API_BASE}/routing/tables`)
  6632. ]);
  6633. if (routesRes.ok) state.routes = await routesRes.json();
  6634. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6635. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6636. const bRoutes = document.getElementById('routes-badge-routes');
  6637. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6638. const showSystem = document.getElementById('prule-show-system')?.checked;
  6639. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6640. const bRules = document.getElementById('routes-badge-rules');
  6641. if (bRules) bRules.innerText = userRules.length;
  6642. const bTables = document.getElementById('routes-badge-tables');
  6643. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6644. const bRoutesCount = document.getElementById('badge-routes-count');
  6645. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6646. renderRoutesList();
  6647. renderPolicyRules();
  6648. renderRoutingTables();
  6649. } catch (err) {
  6650. console.error('Failed to load routing:', err);
  6651. }
  6652. }
  6653. function getRouteProtocolBadge(proto) {
  6654. const p = (proto || 'static').toLowerCase();
  6655. switch (p) {
  6656. case 'bgp':
  6657. 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>`;
  6658. case 'ibgp':
  6659. 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>`;
  6660. case 'ospf':
  6661. 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>`;
  6662. case 'rip':
  6663. 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>`;
  6664. case 'babel':
  6665. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-teal-500/20 text-teal-300 border border-teal-500/30">babel</span>`;
  6666. case 'eigrp':
  6667. 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">eigrp</span>`;
  6668. case 'static':
  6669. 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>`;
  6670. case 'connected':
  6671. 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>`;
  6672. case 'dhcp':
  6673. 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>`;
  6674. case 'multicast':
  6675. 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>`;
  6676. default:
  6677. 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>`;
  6678. }
  6679. }
  6680. function renderRoutesList() {
  6681. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6682. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6683. const tbody = document.getElementById('routes-table-body');
  6684. const empty = document.getElementById('routes-empty');
  6685. if (!tbody) return;
  6686. // Update table filter select
  6687. const sel = document.getElementById('routes-filter-table');
  6688. if (sel) {
  6689. const cur = sel.value;
  6690. sel.innerHTML = '<option value="">All Tables</option>';
  6691. (state.routingTables || []).forEach(t => {
  6692. const opt = document.createElement('option');
  6693. opt.value = t.name;
  6694. opt.innerText = t.name;
  6695. if (t.name === cur) opt.selected = true;
  6696. sel.appendChild(opt);
  6697. });
  6698. }
  6699. const routes = (state.routes || []).filter(r => {
  6700. if (tableFilter && r.routing_table !== tableFilter) return false;
  6701. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6702. if (typeFilter === 'multicast' && !r.multicast) return false;
  6703. if (typeFilter === 'static' && !r.static) return false;
  6704. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6705. if (typeFilter === 'connected' && !r.connect) return false;
  6706. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6707. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6708. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6709. return true;
  6710. });
  6711. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6712. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6713. let summaryText = `${routes.length} Routes`;
  6714. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6715. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6716. const badgeEl = document.getElementById('routes-count-badge');
  6717. if (badgeEl) badgeEl.innerText = summaryText;
  6718. if (routes.length === 0) {
  6719. empty?.classList.remove('hidden');
  6720. tbody.innerHTML = '';
  6721. return;
  6722. }
  6723. empty?.classList.add('hidden');
  6724. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r =>
  6725. `${r.id}:${r.dst_address}:${r.gateway}:${r.interface}:${r.distance}:${r.routing_table}:${r.active}:${r.disabled}:${r.protocol}:${r.comment}:${r.check_gateway}:${r.check_target}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`
  6726. ).join(';');
  6727. if (tbody.dataset.sig === sig) {
  6728. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6729. }
  6730. tbody.dataset.sig = sig;
  6731. tbody.innerHTML = '';
  6732. routes.forEach(r => {
  6733. const tr = document.createElement('tr');
  6734. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6735. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6736. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6737. let flags = '';
  6738. if (r.dynamic) flags += 'D';
  6739. if (r.active) flags += 'A';
  6740. if (r.connect) flags += 'C';
  6741. if (r.static) flags += 'S';
  6742. if (r.ecmp) flags += 'E';
  6743. if (r.multicast) flags += 'M';
  6744. if (r.disabled) flags += 'X';
  6745. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6746. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6747. if (r.check_gateway === 'internet') {
  6748. if (r.health_status === 'online') {
  6749. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6750. healthCell = `
  6751. <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)">
  6752. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6753. <span>Internet OK (${ms}ms)</span>
  6754. </span>
  6755. `;
  6756. } else if (r.health_status === 'offline') {
  6757. healthCell = `
  6758. <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.">
  6759. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6760. <span>Internet Down</span>
  6761. </span>
  6762. `;
  6763. } else {
  6764. healthCell = `
  6765. <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">
  6766. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6767. <span>Checking...</span>
  6768. </span>
  6769. `;
  6770. }
  6771. } else if (r.check_gateway === 'ping') {
  6772. if (r.health_status === 'online') {
  6773. healthCell = `
  6774. <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">
  6775. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6776. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6777. </span>
  6778. `;
  6779. } else if (r.health_status === 'offline') {
  6780. healthCell = `
  6781. <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">
  6782. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6783. <span>Gateway Dead</span>
  6784. </span>
  6785. `;
  6786. }
  6787. }
  6788. const flagDescriptions = [];
  6789. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6790. if (r.active) flagDescriptions.push('Active (A)');
  6791. if (r.connect) flagDescriptions.push('Connected (C)');
  6792. if (r.static) flagDescriptions.push('Static (S)');
  6793. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6794. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6795. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6796. tr.innerHTML = `
  6797. <td class="py-2.5 px-3 text-center">
  6798. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6799. 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')
  6800. }" title="Flags: ${flagDescriptions.join(', ')}">
  6801. ${flags || '-'}
  6802. </span>
  6803. </td>
  6804. <td class="py-2.5 px-3">
  6805. <div class="flex items-center gap-1.5 flex-wrap">
  6806. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6807. ${r.ecmp ? `
  6808. <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)">
  6809. <span>⚡ ECMP</span>
  6810. </span>
  6811. ` : ''}
  6812. ${r.multicast ? `
  6813. <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">
  6814. <span>IGMP</span>
  6815. </span>
  6816. ` : ''}
  6817. </div>
  6818. </td>
  6819. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6820. <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>
  6821. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6822. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6823. <td class="py-2.5 px-3 text-emerald-400 font-mono">${
  6824. (state.sdwanGroups || []).some(g => g.name === r.interface)
  6825. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/70 text-cyan-300 border border-cyan-700/50 font-bold inline-flex items-center gap-1"><span>⚡</span><span>${escapeHtml(r.interface)}</span></span>`
  6826. : (r.interface || '-')
  6827. }</td>
  6828. <td class="py-2.5 px-3">${healthCell}</td>
  6829. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6830. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6831. ${r.static ? `
  6832. <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>
  6833. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6834. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6835. ` : `
  6836. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6837. `}
  6838. </td>
  6839. `;
  6840. tbody.appendChild(tr);
  6841. });
  6842. }
  6843. function openAddRouteModal() {
  6844. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6845. document.getElementById('route-modal-id').value = '';
  6846. document.getElementById('route-modal-old-dst').value = '';
  6847. document.getElementById('route-modal-old-gw').value = '';
  6848. document.getElementById('route-modal-old-distance').value = '';
  6849. document.getElementById('route-modal-old-table').value = '';
  6850. document.getElementById('route-modal-old-iface').value = '';
  6851. const dstInput = document.getElementById('route-modal-dst');
  6852. const gwInput = document.getElementById('route-modal-gw');
  6853. const distInput = document.getElementById('route-modal-distance');
  6854. const ifaceSelect = document.getElementById('route-modal-iface');
  6855. const tableSelect = document.getElementById('route-modal-table');
  6856. const commentInput = document.getElementById('route-modal-comment');
  6857. const disCheck = document.getElementById('route-modal-disabled');
  6858. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6859. dstInput.disabled = false;
  6860. dstInput.value = '0.0.0.0/0';
  6861. gwInput.disabled = false;
  6862. gwInput.value = '';
  6863. distInput.disabled = false;
  6864. distInput.value = '1';
  6865. ifaceSelect.disabled = false;
  6866. tableSelect.disabled = false;
  6867. commentInput.disabled = false;
  6868. commentInput.value = '';
  6869. disCheck.disabled = false;
  6870. disCheck.checked = false;
  6871. if (saveBtn) saveBtn.classList.remove('hidden');
  6872. const checkGw = document.getElementById('route-modal-check-gw');
  6873. if (checkGw) checkGw.value = 'internet';
  6874. const checkTarget = document.getElementById('route-modal-check-target');
  6875. if (checkTarget) checkTarget.value = '1.1.1.1';
  6876. const checkInterval = document.getElementById('route-modal-check-interval');
  6877. if (checkInterval) checkInterval.value = '5';
  6878. const checkThresh = document.getElementById('route-modal-check-threshold');
  6879. if (checkThresh) checkThresh.value = '3';
  6880. toggleRouteCheckModeUI();
  6881. populateInterfaceSelect('route-modal-iface');
  6882. // Populate tables
  6883. tableSelect.innerHTML = '';
  6884. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6885. const opt = document.createElement('option');
  6886. opt.value = t.name;
  6887. opt.innerText = t.name;
  6888. if (t.name === 'main') opt.selected = true;
  6889. tableSelect.appendChild(opt);
  6890. });
  6891. document.getElementById('route-modal').classList.remove('hidden');
  6892. }
  6893. function openEditRouteModal(id) {
  6894. const r = (state.routes || []).find(route => route.id === id);
  6895. if (!r) return;
  6896. const isStatic = !!r.static;
  6897. document.getElementById('route-modal-title').innerText = isStatic
  6898. ? `Edit Route: ${r.dst_address}`
  6899. : `Route Properties (Read Only): ${r.dst_address}`;
  6900. document.getElementById('route-modal-id').value = r.id;
  6901. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6902. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6903. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6904. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6905. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6906. const dstInput = document.getElementById('route-modal-dst');
  6907. const gwInput = document.getElementById('route-modal-gw');
  6908. const distInput = document.getElementById('route-modal-distance');
  6909. const ifaceSelect = document.getElementById('route-modal-iface');
  6910. const tableSelect = document.getElementById('route-modal-table');
  6911. const commentInput = document.getElementById('route-modal-comment');
  6912. const disCheck = document.getElementById('route-modal-disabled');
  6913. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6914. dstInput.value = r.dst_address;
  6915. gwInput.value = r.gateway || '';
  6916. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6917. commentInput.value = r.comment || '';
  6918. disCheck.checked = !!r.disabled;
  6919. const checkGw = document.getElementById('route-modal-check-gw');
  6920. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6921. const checkTarget = document.getElementById('route-modal-check-target');
  6922. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6923. const checkInterval = document.getElementById('route-modal-check-interval');
  6924. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6925. const checkThresh = document.getElementById('route-modal-check-threshold');
  6926. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6927. toggleRouteCheckModeUI();
  6928. dstInput.disabled = !isStatic;
  6929. gwInput.disabled = !isStatic;
  6930. distInput.disabled = !isStatic;
  6931. ifaceSelect.disabled = !isStatic;
  6932. tableSelect.disabled = !isStatic;
  6933. commentInput.disabled = !isStatic;
  6934. disCheck.disabled = !isStatic;
  6935. if (checkGw) checkGw.disabled = !isStatic;
  6936. if (checkTarget) checkTarget.disabled = !isStatic;
  6937. if (checkInterval) checkInterval.disabled = !isStatic;
  6938. if (checkThresh) checkThresh.disabled = !isStatic;
  6939. if (saveBtn) {
  6940. if (isStatic) {
  6941. saveBtn.classList.remove('hidden');
  6942. } else {
  6943. saveBtn.classList.add('hidden');
  6944. }
  6945. }
  6946. populateInterfaceSelect('route-modal-iface', r.interface);
  6947. tableSelect.innerHTML = '';
  6948. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6949. const opt = document.createElement('option');
  6950. opt.value = t.name;
  6951. opt.innerText = t.name;
  6952. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6953. tableSelect.appendChild(opt);
  6954. });
  6955. document.getElementById('route-modal').classList.remove('hidden');
  6956. }
  6957. function closeRouteModal() {
  6958. document.getElementById('route-modal').classList.add('hidden');
  6959. }
  6960. function setRouteCheckTarget(ip) {
  6961. const inp = document.getElementById('route-modal-check-target');
  6962. if (inp) inp.value = ip;
  6963. }
  6964. function toggleRouteCheckModeUI() {
  6965. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6966. const targetRow = document.getElementById('route-row-check-target');
  6967. const paramsRow = document.getElementById('route-row-check-params');
  6968. if (mode === 'none') {
  6969. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6970. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6971. } else if (mode === 'ping') {
  6972. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6973. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6974. } else { // internet
  6975. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6976. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6977. }
  6978. }
  6979. async function submitSaveRoute(e) {
  6980. e.preventDefault();
  6981. const id = document.getElementById('route-modal-id').value;
  6982. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6983. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6984. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6985. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6986. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6987. const dst = document.getElementById('route-modal-dst').value.trim();
  6988. const gw = document.getElementById('route-modal-gw').value.trim();
  6989. const table = document.getElementById('route-modal-table').value;
  6990. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6991. const iface = document.getElementById('route-modal-iface').value;
  6992. const comment = document.getElementById('route-modal-comment').value.trim();
  6993. const disabled = document.getElementById('route-modal-disabled').checked;
  6994. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6995. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6996. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6997. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6998. if (!dst) {
  6999. showToast('Error', 'Destination address is required', 'error');
  7000. return;
  7001. }
  7002. if (!gw && !iface) {
  7003. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  7004. return;
  7005. }
  7006. const payload = {
  7007. id,
  7008. old_dst_address: oldDst,
  7009. old_gateway: oldGw,
  7010. old_routing_table: oldTable,
  7011. old_interface: oldIface,
  7012. dst_address: dst,
  7013. gateway: gw || iface,
  7014. routing_table: table,
  7015. distance,
  7016. interface: iface,
  7017. comment,
  7018. disabled,
  7019. check_gateway,
  7020. check_target,
  7021. check_interval,
  7022. check_threshold
  7023. };
  7024. if (oldDistStr !== undefined && oldDistStr !== '') {
  7025. payload.old_distance = parseInt(oldDistStr, 10);
  7026. }
  7027. try {
  7028. const res = await fetch(`${API_BASE}/routes`, {
  7029. method: 'POST',
  7030. headers: { 'Content-Type': 'application/json' },
  7031. body: JSON.stringify(payload)
  7032. });
  7033. if (res.ok) {
  7034. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7035. closeRouteModal();
  7036. const tbody = document.getElementById('routes-table-body');
  7037. if (tbody) tbody.dataset.sig = '';
  7038. loadRoutes();
  7039. } else {
  7040. const err = await res.json().catch(() => ({}));
  7041. showToast('Error', err.message || err.error || 'Failed to save route', 'error');
  7042. }
  7043. } catch (err) {
  7044. showToast('Error', err.message, 'error');
  7045. }
  7046. }
  7047. async function toggleRouteState(id, disabled) {
  7048. try {
  7049. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7050. method: 'POST',
  7051. headers: { 'Content-Type': 'application/json' },
  7052. body: JSON.stringify({ disabled })
  7053. });
  7054. if (res.ok) {
  7055. const tbody = document.getElementById('routes-table-body');
  7056. if (tbody) tbody.dataset.sig = '';
  7057. loadRoutes();
  7058. } else {
  7059. const err = await res.json().catch(() => ({}));
  7060. showToast('Error', err.message || err.error || 'Failed to update route state', 'error');
  7061. }
  7062. } catch (err) {
  7063. showToast('Error', err.message, 'error');
  7064. }
  7065. }
  7066. async function deleteRoute(id) {
  7067. if (!confirm('Are you sure you want to delete this route?')) return;
  7068. try {
  7069. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7070. if (res.ok) {
  7071. showToast('Deleted', 'Route removed', 'success');
  7072. const tbody = document.getElementById('routes-table-body');
  7073. if (tbody) tbody.dataset.sig = '';
  7074. loadRoutes();
  7075. } else {
  7076. const err = await res.json().catch(() => ({}));
  7077. showToast('Error', err.message || err.error || 'Failed to delete route', 'error');
  7078. }
  7079. } catch (err) {
  7080. showToast('Error', err.message, 'error');
  7081. }
  7082. }
  7083. // ----------------- Policy Rules (/ip route rule) -----------------
  7084. function renderPolicyRules() {
  7085. const tbody = document.getElementById('rules-table-body');
  7086. const empty = document.getElementById('rules-empty');
  7087. if (!tbody) return;
  7088. const showSystem = document.getElementById('prule-show-system')?.checked;
  7089. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7090. const countBadge = document.getElementById('rules-count-badge');
  7091. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7092. const bRules = document.getElementById('routes-badge-rules');
  7093. if (bRules) bRules.innerText = filtered.length;
  7094. if (filtered.length === 0) {
  7095. empty?.classList.remove('hidden');
  7096. tbody.innerHTML = '';
  7097. return;
  7098. }
  7099. empty?.classList.add('hidden');
  7100. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7101. if (tbody.dataset.sig === sig) return;
  7102. tbody.dataset.sig = sig;
  7103. tbody.innerHTML = '';
  7104. filtered.forEach(pr => {
  7105. const isSys = pr.is_default || pr.is_system;
  7106. const tr = document.createElement('tr');
  7107. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7108. tr.innerHTML = `
  7109. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7110. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7111. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7112. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7113. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7114. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7115. <td class="py-2.5 px-3 text-right font-sans">
  7116. ${!pr.is_default ? `
  7117. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7118. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7119. </td>
  7120. `;
  7121. tbody.appendChild(tr);
  7122. });
  7123. }
  7124. function openAddPolicyRuleModal() {
  7125. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7126. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7127. document.getElementById('prule-modal-mark').value = '';
  7128. document.getElementById('prule-modal-src').value = '';
  7129. document.getElementById('prule-modal-dst').value = '';
  7130. const sel = document.getElementById('prule-modal-table');
  7131. sel.innerHTML = '';
  7132. (state.routingTables || []).forEach(t => {
  7133. const opt = document.createElement('option');
  7134. opt.value = t.name;
  7135. opt.innerText = t.name;
  7136. sel.appendChild(opt);
  7137. });
  7138. document.getElementById('prule-modal').classList.remove('hidden');
  7139. }
  7140. function closePolicyRuleModal() {
  7141. document.getElementById('prule-modal').classList.add('hidden');
  7142. }
  7143. async function submitSavePolicyRule(e) {
  7144. e.preventDefault();
  7145. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7146. const mark = document.getElementById('prule-modal-mark').value.trim();
  7147. const src = document.getElementById('prule-modal-src').value.trim();
  7148. const dst = document.getElementById('prule-modal-dst').value.trim();
  7149. const table = document.getElementById('prule-modal-table').value;
  7150. const action = document.getElementById('prule-modal-action').value;
  7151. try {
  7152. const res = await fetch(`${API_BASE}/routing/rules`, {
  7153. method: 'POST',
  7154. headers: { 'Content-Type': 'application/json' },
  7155. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7156. });
  7157. if (res.ok) {
  7158. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7159. closePolicyRuleModal();
  7160. loadRoutes();
  7161. } else {
  7162. const err = await res.json();
  7163. showToast('Error', err.message, 'error');
  7164. }
  7165. } catch (err) {
  7166. showToast('Error', err.message, 'error');
  7167. }
  7168. }
  7169. async function deletePolicyRule(id) {
  7170. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7171. try {
  7172. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7173. if (res.ok) {
  7174. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7175. loadRoutes();
  7176. }
  7177. } catch (err) {
  7178. showToast('Error', err.message, 'error');
  7179. }
  7180. }
  7181. // ----------------- Routing Tables -----------------
  7182. function renderRoutingTables() {
  7183. const tbody = document.getElementById('tables-table-body');
  7184. if (!tbody) return;
  7185. const tables = state.routingTables || [];
  7186. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7187. if (tbody.dataset.sig === sig) return;
  7188. tbody.dataset.sig = sig;
  7189. tbody.innerHTML = '';
  7190. (state.routingTables || []).forEach(t => {
  7191. const tr = document.createElement('tr');
  7192. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7193. tr.innerHTML = `
  7194. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7195. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7196. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7197. `;
  7198. tbody.appendChild(tr);
  7199. });
  7200. }
  7201. function openAddTableModal() {
  7202. document.getElementById('table-modal-name').value = '';
  7203. document.getElementById('table-modal-id').value = '';
  7204. document.getElementById('table-modal-comment').value = '';
  7205. document.getElementById('table-modal').classList.remove('hidden');
  7206. }
  7207. function closeTableModal() {
  7208. document.getElementById('table-modal').classList.add('hidden');
  7209. }
  7210. async function submitSaveTable(e) {
  7211. e.preventDefault();
  7212. const name = document.getElementById('table-modal-name').value.trim();
  7213. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7214. const comment = document.getElementById('table-modal-comment').value.trim();
  7215. try {
  7216. const res = await fetch(`${API_BASE}/routing/tables`, {
  7217. method: 'POST',
  7218. headers: { 'Content-Type': 'application/json' },
  7219. body: JSON.stringify({ name, table_id: id, comment })
  7220. });
  7221. if (res.ok) {
  7222. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7223. closeTableModal();
  7224. loadRoutes();
  7225. } else {
  7226. const err = await res.json();
  7227. showToast('Error', err.message, 'error');
  7228. }
  7229. } catch (err) {
  7230. showToast('Error', err.message, 'error');
  7231. }
  7232. }
  7233. async function loadDebianConfig() {
  7234. const view = document.getElementById('debian-config-view');
  7235. view.innerText = 'Generating live configuration...';
  7236. try {
  7237. const res = await fetch(`${API_BASE}/debian/config`);
  7238. const data = await res.json();
  7239. view.innerText = data.content || '# Empty config';
  7240. } catch (err) {
  7241. view.innerText = 'Failed to generate Debian network config.';
  7242. }
  7243. }
  7244. async function saveDebianConfig() {
  7245. try {
  7246. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7247. const data = await res.json();
  7248. if (res.ok) {
  7249. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7250. loadDebianConfig();
  7251. }
  7252. } catch (err) {
  7253. showToast('Error', err.message, 'error');
  7254. }
  7255. }
  7256. function showToast(title, message, type = 'info') {
  7257. const container = document.getElementById('toast-container');
  7258. const toast = document.createElement('div');
  7259. const borderColors = {
  7260. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7261. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7262. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7263. };
  7264. 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}`;
  7265. toast.innerHTML = `
  7266. <div class="flex-1">
  7267. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7268. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7269. </div>
  7270. `;
  7271. container.appendChild(toast);
  7272. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7273. setTimeout(() => {
  7274. toast.classList.add('opacity-0', 'translate-y-2');
  7275. setTimeout(() => toast.remove(), 300);
  7276. }, 4000);
  7277. }
  7278. function formatTraffic(bytesPerSec) {
  7279. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7280. const kb = bytesPerSec / 1024;
  7281. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7282. const mb = kb / 1024;
  7283. return `${mb.toFixed(2)} MB/s`;
  7284. }
  7285. function toggleSidebar() {
  7286. const sb = document.getElementById('sidebar');
  7287. sb.classList.toggle('-translate-x-full');
  7288. }
  7289. // ======================== EoIP (Ethernet over IP) ========================
  7290. async function loadEoIP(populate = true) {
  7291. try {
  7292. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7293. const data = await res.json();
  7294. state.eoipTunnels = Array.isArray(data) ? data : [];
  7295. const badge = document.getElementById('eoip-count-badge');
  7296. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7297. const sideBadge = document.getElementById('badge-eoip-count');
  7298. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7299. renderEoIPTunnels();
  7300. } catch (err) {
  7301. console.error('Failed to load EoIP:', err);
  7302. }
  7303. }
  7304. function renderEoIPTunnels() {
  7305. const tbody = document.getElementById('eoip-table-body');
  7306. const empty = document.getElementById('eoip-empty');
  7307. if (!tbody) return;
  7308. tbody.innerHTML = '';
  7309. const tunnels = state.eoipTunnels || [];
  7310. if (tunnels.length === 0) {
  7311. empty?.classList.remove('hidden');
  7312. return;
  7313. }
  7314. empty?.classList.add('hidden');
  7315. tunnels.forEach(t => {
  7316. const tr = document.createElement('tr');
  7317. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7318. tr.innerHTML = `
  7319. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7320. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7321. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7322. <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>
  7323. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7324. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7325. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7326. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7327. <td class="py-2.5 px-3 font-mono text-[11px]">
  7328. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7329. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7330. </td>
  7331. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7332. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7333. <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>
  7334. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7335. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7336. </td>
  7337. `;
  7338. tbody.appendChild(tr);
  7339. });
  7340. }
  7341. function openAddEoIPModal() {
  7342. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7343. document.getElementById('eoip-modal-id').value = '';
  7344. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7345. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7346. document.getElementById('eoip-modal-remote').value = '';
  7347. document.getElementById('eoip-modal-ip').value = '';
  7348. document.getElementById('eoip-modal-local').value = '';
  7349. document.getElementById('eoip-modal-mac').value = '';
  7350. document.getElementById('eoip-modal-mtu').value = '1500';
  7351. document.getElementById('eoip-modal-comment').value = '';
  7352. document.getElementById('eoip-modal-clampmss').checked = true;
  7353. document.getElementById('eoip-modal-disabled').checked = false;
  7354. document.getElementById('eoip-modal').classList.remove('hidden');
  7355. }
  7356. function openEditEoIPModal(id) {
  7357. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7358. if (!t) return;
  7359. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7360. document.getElementById('eoip-modal-id').value = t.id;
  7361. document.getElementById('eoip-modal-name').value = t.name;
  7362. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7363. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7364. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7365. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7366. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7367. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7368. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7369. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7370. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7371. document.getElementById('eoip-modal').classList.remove('hidden');
  7372. }
  7373. function closeEoIPModal() {
  7374. document.getElementById('eoip-modal').classList.add('hidden');
  7375. }
  7376. async function submitSaveEoIP(e) {
  7377. e.preventDefault();
  7378. const id = document.getElementById('eoip-modal-id').value;
  7379. const name = document.getElementById('eoip-modal-name').value.trim();
  7380. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7381. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7382. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7383. const local = document.getElementById('eoip-modal-local').value.trim();
  7384. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7385. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7386. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7387. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7388. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7389. try {
  7390. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7391. method: 'POST',
  7392. headers: { 'Content-Type': 'application/json' },
  7393. body: JSON.stringify({
  7394. id,
  7395. name,
  7396. tunnel_id: tunnelId,
  7397. remote_address: remote,
  7398. ip_address: ipAddress,
  7399. local_address: local,
  7400. mac_address: mac,
  7401. mtu,
  7402. clamp_mss: clampMss,
  7403. comment,
  7404. disabled
  7405. })
  7406. });
  7407. if (res.ok) {
  7408. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7409. closeEoIPModal();
  7410. loadEoIP(false);
  7411. fetchData(false);
  7412. } else {
  7413. const err = await res.json();
  7414. showToast('Error', err.message, 'error');
  7415. }
  7416. } catch (err) {
  7417. showToast('Error', err.message, 'error');
  7418. }
  7419. }
  7420. async function toggleEoIPState(id, disabled) {
  7421. try {
  7422. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7423. method: 'POST',
  7424. headers: { 'Content-Type': 'application/json' },
  7425. body: JSON.stringify({ disabled })
  7426. });
  7427. if (res.ok) {
  7428. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7429. loadEoIP(false);
  7430. fetchData(false);
  7431. }
  7432. } catch (err) {
  7433. showToast('Error', err.message, 'error');
  7434. }
  7435. }
  7436. async function deleteEoIP(id) {
  7437. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7438. try {
  7439. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7440. if (res.ok) {
  7441. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7442. loadEoIP(false);
  7443. fetchData(false);
  7444. }
  7445. } catch (err) {
  7446. showToast('Error', err.message, 'error');
  7447. }
  7448. }
  7449. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7450. async function loadVXLAN(populate = true) {
  7451. try {
  7452. const [tunnelsRes, vtepsRes] = await Promise.all([
  7453. fetch(`${API_BASE}/vpn/vxlan`),
  7454. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7455. ]);
  7456. if (tunnelsRes.ok) {
  7457. state.vxlanTunnels = await tunnelsRes.json() || [];
  7458. }
  7459. if (vtepsRes.ok) {
  7460. state.vxlanVteps = await vtepsRes.json() || [];
  7461. }
  7462. renderVXLANTable();
  7463. renderVXLANVtepsTable();
  7464. const countBadge = document.getElementById('vxlan-count-badge');
  7465. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7466. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7467. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7468. const navBadge = document.getElementById('badge-vxlan-count');
  7469. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7470. } catch (err) {
  7471. console.error('Error loading VXLAN:', err);
  7472. }
  7473. }
  7474. function renderVXLANTable() {
  7475. const tbody = document.getElementById('vxlan-table-body');
  7476. const empty = document.getElementById('vxlan-empty');
  7477. if (!tbody || !empty) return;
  7478. tbody.innerHTML = '';
  7479. const tunnels = state.vxlanTunnels || [];
  7480. if (tunnels.length === 0) {
  7481. empty.classList.remove('hidden');
  7482. return;
  7483. }
  7484. empty.classList.add('hidden');
  7485. tunnels.forEach(t => {
  7486. const tr = document.createElement('tr');
  7487. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7488. let flag = '';
  7489. if (t.disabled) {
  7490. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 font-bold border border-slate-700" title="Disabled">X</span>';
  7491. } else if (t.running) {
  7492. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 font-bold border border-amber-800/50" title="Running">R</span>';
  7493. } else {
  7494. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-rose-950 text-rose-300 font-bold border border-rose-800/50" title="Down">!</span>';
  7495. }
  7496. const vtepCount = (t.vteps || []).length;
  7497. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7498. tr.innerHTML = `
  7499. <td class="py-2.5 px-3 text-center">${flag}</td>
  7500. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7501. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7502. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7503. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.ip_address || '') || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  7504. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7505. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7506. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7507. <td class="py-2.5 px-3 font-mono">
  7508. <span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-amber-300 border border-slate-700 cursor-pointer" onclick="openAddVXLANVtepModal('${escapeHtml(t.name)}')" title="Click to add VTEP peer">${vtepCount} VTEP${vtepCount === 1 ? '' : 's'}</span>
  7509. </td>
  7510. <td class="py-2.5 px-3 font-mono text-[11px]">
  7511. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7512. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7513. </td>
  7514. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7515. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7516. <button onclick="toggleVXLANState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-amber-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  7517. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7518. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7519. </td>
  7520. `;
  7521. tbody.appendChild(tr);
  7522. });
  7523. }
  7524. function renderVXLANVtepsTable() {
  7525. const tbody = document.getElementById('vxlan-vteps-table-body');
  7526. const empty = document.getElementById('vxlan-vteps-empty');
  7527. if (!tbody || !empty) return;
  7528. tbody.innerHTML = '';
  7529. const vteps = state.vxlanVteps || [];
  7530. if (vteps.length === 0) {
  7531. empty.classList.remove('hidden');
  7532. return;
  7533. }
  7534. empty.classList.add('hidden');
  7535. vteps.forEach(v => {
  7536. const tr = document.createElement('tr');
  7537. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7538. tr.innerHTML = `
  7539. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7540. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7541. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7542. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7543. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7544. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7545. </td>
  7546. `;
  7547. tbody.appendChild(tr);
  7548. });
  7549. }
  7550. function openAddVXLANModal() {
  7551. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7552. document.getElementById('vxlan-modal-id').value = '';
  7553. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7554. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7555. document.getElementById('vxlan-modal-port').value = '4789';
  7556. document.getElementById('vxlan-modal-ip').value = '';
  7557. document.getElementById('vxlan-modal-parent').value = '';
  7558. document.getElementById('vxlan-modal-local').value = '';
  7559. document.getElementById('vxlan-modal-remote').value = '';
  7560. document.getElementById('vxlan-modal-group').value = '';
  7561. document.getElementById('vxlan-modal-mac').value = '';
  7562. document.getElementById('vxlan-modal-mtu').value = '1500';
  7563. document.getElementById('vxlan-modal-comment').value = '';
  7564. document.getElementById('vxlan-modal-learning').checked = true;
  7565. document.getElementById('vxlan-modal-disabled').checked = false;
  7566. document.getElementById('vxlan-modal').classList.remove('hidden');
  7567. }
  7568. function openEditVXLANModal(id) {
  7569. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7570. if (!t) return;
  7571. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7572. document.getElementById('vxlan-modal-id').value = t.id;
  7573. document.getElementById('vxlan-modal-name').value = t.name;
  7574. document.getElementById('vxlan-modal-vni').value = t.vni;
  7575. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7576. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7577. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7578. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7579. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7580. document.getElementById('vxlan-modal-group').value = t.group || '';
  7581. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7582. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7583. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7584. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7585. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7586. document.getElementById('vxlan-modal').classList.remove('hidden');
  7587. }
  7588. function closeVXLANModal() {
  7589. document.getElementById('vxlan-modal').classList.add('hidden');
  7590. }
  7591. async function submitSaveVXLAN(e) {
  7592. e.preventDefault();
  7593. const id = document.getElementById('vxlan-modal-id').value;
  7594. const name = document.getElementById('vxlan-modal-name').value.trim();
  7595. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7596. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7597. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7598. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7599. const local = document.getElementById('vxlan-modal-local').value.trim();
  7600. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7601. const group = document.getElementById('vxlan-modal-group').value.trim();
  7602. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7603. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7604. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7605. const learning = document.getElementById('vxlan-modal-learning').checked;
  7606. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7607. try {
  7608. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7609. method: 'POST',
  7610. headers: { 'Content-Type': 'application/json' },
  7611. body: JSON.stringify({
  7612. id,
  7613. name,
  7614. vni,
  7615. port,
  7616. ip_address: ipAddress,
  7617. parent_interface: parentInterface,
  7618. local_address: local,
  7619. remote_address: remote,
  7620. group,
  7621. mac_address: mac,
  7622. mtu,
  7623. learning,
  7624. comment,
  7625. disabled
  7626. })
  7627. });
  7628. if (res.ok) {
  7629. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7630. closeVXLANModal();
  7631. loadVXLAN(false);
  7632. fetchData(false);
  7633. } else {
  7634. const err = await res.json();
  7635. showToast('Error', err.message, 'error');
  7636. }
  7637. } catch (err) {
  7638. showToast('Error', err.message, 'error');
  7639. }
  7640. }
  7641. async function toggleVXLANState(id, disabled) {
  7642. try {
  7643. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7644. method: 'POST',
  7645. headers: { 'Content-Type': 'application/json' },
  7646. body: JSON.stringify({ disabled })
  7647. });
  7648. if (res.ok) {
  7649. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7650. loadVXLAN(false);
  7651. fetchData(false);
  7652. }
  7653. } catch (err) {
  7654. showToast('Error', err.message, 'error');
  7655. }
  7656. }
  7657. async function deleteVXLAN(id) {
  7658. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7659. try {
  7660. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7661. if (res.ok) {
  7662. showToast('Deleted', 'VXLAN interface removed', 'success');
  7663. loadVXLAN(false);
  7664. fetchData(false);
  7665. }
  7666. } catch (err) {
  7667. showToast('Error', err.message, 'error');
  7668. }
  7669. }
  7670. function openAddVXLANVtepModal(defaultIface = '') {
  7671. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7672. if (sel) {
  7673. sel.innerHTML = '';
  7674. const tunnels = state.vxlanTunnels || [];
  7675. tunnels.forEach(t => {
  7676. const opt = document.createElement('option');
  7677. opt.value = t.name;
  7678. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7679. if (defaultIface && t.name === defaultIface) {
  7680. opt.selected = true;
  7681. }
  7682. sel.appendChild(opt);
  7683. });
  7684. }
  7685. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7686. document.getElementById('vxlan-vtep-modal-port').value = '';
  7687. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7688. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7689. }
  7690. function closeVXLANVtepModal() {
  7691. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7692. }
  7693. async function submitSaveVXLANVtep(e) {
  7694. e.preventDefault();
  7695. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7696. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7697. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7698. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7699. try {
  7700. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7701. method: 'POST',
  7702. headers: { 'Content-Type': 'application/json' },
  7703. body: JSON.stringify({
  7704. interface: iface,
  7705. remote_ip: remote,
  7706. port,
  7707. comment
  7708. })
  7709. });
  7710. if (res.ok) {
  7711. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7712. closeVXLANVtepModal();
  7713. loadVXLAN(false);
  7714. fetchData(false);
  7715. } else {
  7716. const err = await res.json();
  7717. showToast('Error', err.message, 'error');
  7718. }
  7719. } catch (err) {
  7720. showToast('Error', err.message, 'error');
  7721. }
  7722. }
  7723. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7724. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7725. try {
  7726. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7727. method: 'DELETE'
  7728. });
  7729. if (res.ok) {
  7730. showToast('Deleted', 'Remote VTEP removed', 'success');
  7731. loadVXLAN(false);
  7732. fetchData(false);
  7733. }
  7734. } catch (err) {
  7735. showToast('Error', err.message, 'error');
  7736. }
  7737. }
  7738. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7739. const aeroRateSamples = new Map();
  7740. const aeroLiveRates = new Map();
  7741. async function loadAeroTUN(populate = true) {
  7742. try {
  7743. const [tunnelsRes, statsRes] = await Promise.all([
  7744. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7745. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7746. ]);
  7747. if (tunnelsRes.ok) {
  7748. const data = await tunnelsRes.json();
  7749. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7750. const now = Date.now();
  7751. for (const t of state.aerotunTunnels) {
  7752. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7753. if (seconds >= 0.5 && seconds <= 60 && t.rx_bytes >= old.rx && t.tx_bytes >= old.tx && t.packets_rx >= old.prx && t.packets_tx >= old.ptx) {
  7754. aeroLiveRates.set(t.id,{rx:(t.rx_bytes-old.rx)*8/seconds/1e6,tx:(t.tx_bytes-old.tx)*8/seconds/1e6,prx:(t.packets_rx-old.prx)/seconds,ptx:(t.packets_tx-old.ptx)/seconds});
  7755. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7756. if (!old || seconds >= 0.5) aeroRateSamples.set(t.id,{time:now,rx:t.rx_bytes||0,tx:t.tx_bytes||0,prx:t.packets_rx||0,ptx:t.packets_tx||0});
  7757. }
  7758. }
  7759. if (statsRes.ok) {
  7760. state.aerotunStats = await statsRes.json();
  7761. }
  7762. const countBadge = document.getElementById('aerotun-count-badge');
  7763. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7764. const sideBadge = document.getElementById('badge-aerotun-count');
  7765. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7766. renderAeroTUN();
  7767. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7768. } catch (err) {
  7769. console.error('Failed to load AeroTUN:', err);
  7770. }
  7771. }
  7772. function renderAeroTUN() {
  7773. const tbody = document.getElementById('aerotun-table-body');
  7774. const empty = document.getElementById('aerotun-empty');
  7775. // Update summary cards
  7776. const stats = state.aerotunStats || {};
  7777. const tunnels = state.aerotunTunnels || [];
  7778. const statActive = document.getElementById('aerotun-stat-active');
  7779. if (statActive) {
  7780. const activeCount = tunnels.filter(t => t.connected).length;
  7781. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7782. }
  7783. const statSaved = document.getElementById('aerotun-stat-saved');
  7784. if (statSaved) {
  7785. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7786. }
  7787. const statRatio = document.getElementById('aerotun-stat-ratio');
  7788. if (statRatio) {
  7789. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7790. }
  7791. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7792. if (statTraffic) {
  7793. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7794. }
  7795. if (!tbody) return;
  7796. tbody.innerHTML = '';
  7797. if (tunnels.length === 0) {
  7798. empty?.classList.remove('hidden');
  7799. return;
  7800. }
  7801. empty?.classList.add('hidden');
  7802. tunnels.forEach(t => {
  7803. const tr = document.createElement('tr');
  7804. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7805. const modeBadge = t.mode === 'server'
  7806. ? `<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>`
  7807. : `<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>`;
  7808. const endpointInfo = t.mode === 'server'
  7809. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7810. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7811. const compBadge = t.compression
  7812. ? `<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>`
  7813. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7814. const activePeer = t.connected && t.active_peer_endpoint
  7815. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last authenticated packet: ${escapeHtml(t.last_handshake || 'just now')}; dropped: ${t.dropped_packets || 0}; auth failures: ${t.auth_failures || 0}; replay drops: ${t.replay_drops || 0}${t.last_error ? '; last error: ' + escapeHtml(t.last_error) : ''}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  7816. : `<span class="text-slate-500 text-[11px]">${t.last_error ? 'Failed: ' + escapeHtml(t.last_error) : (!t.running ? (t.disabled ? 'Saved / disabled' : 'Stopped') : (t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'))}</span>`;
  7817. const rawRx = formatBytes(t.rx_bytes || 0);
  7818. const rawTx = formatBytes(t.tx_bytes || 0);
  7819. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7820. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7821. const rate = aeroLiveRates.get(t.id);
  7822. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7823. tr.innerHTML = `
  7824. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7825. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7826. <span>${escapeHtml(t.name)}</span>
  7827. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7828. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7829. </td>
  7830. <td class="py-2.5 px-3">${modeBadge}</td>
  7831. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7832. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7833. <td class="py-2.5 px-3">${compBadge}</td>
  7834. <td class="py-2.5 px-3">${activePeer}</td>
  7835. <td class="py-2.5 px-3 font-mono text-[11px]">
  7836. <span class="text-emerald-400">↓ ${rawRx}</span>
  7837. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7838. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7839. </td>
  7840. <td class="py-2.5 px-3 font-mono text-[11px]">
  7841. <span class="text-slate-400">↓ ${wireRx}</span>
  7842. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7843. </td>
  7844. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7845. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7846. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7847. ${t.running
  7848. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7849. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7850. }
  7851. <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>
  7852. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7853. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7854. </td>
  7855. `;
  7856. tbody.appendChild(tr);
  7857. });
  7858. }
  7859. async function openAeroTUNHealth(encodedID) {
  7860. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7861. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7862. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7863. document.getElementById('aerotun-compare-host').value=underlay;
  7864. document.getElementById('aerotun-compare-result').textContent='';
  7865. document.getElementById('aerotun-health-result').textContent = '';
  7866. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7867. await refreshAeroTUNHealth();
  7868. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7869. }
  7870. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7871. async function refreshAeroTUNHealth() {
  7872. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7873. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7874. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7875. try {
  7876. const response=await fetch(`${API_BASE}/vpn/aerotun/health`);if(!response.ok)throw new Error(await responseError(response));const data=await response.json();if(state.aeroHealthSelected!==id)return;
  7877. const current=(data.states||[]).find(x=>x.tunnel_id===id);const status=current?.status||'unknown';const since=current?.since&&!current.since.startsWith('0001')?new Date(current.since).toLocaleString():'—';const rate=aeroLiveRates.get(id);
  7878. const d=t.drop_breakdown;
  7879. document.getElementById('aerotun-health-status').textContent=`Status: ${status} since ${since} · Backend: ${t.backend||'—'} · MTU: ${t.mtu||'—'} / configured ${t.configured_mtu||(!t.running?t.mtu:'—')||'—'} · Last authenticated packet: ${t.last_handshake||'never'} · Drops: ${t.dropped_packets||0}${d?` (outgoing invalid ${d.invalid_outgoing}, session ${d.missing_session}, send ${d.send_failure}, incoming invalid ${d.invalid_incoming}, source policy ${d.source_policy}, interface ${d.interface_write})`:''} · Authentication failures: ${t.auth_failures||0} · Replay drops: ${t.replay_drops||0}${Number.isFinite(data.service_cpu_percent)?` · Service CPU (all features): ${data.service_cpu_percent.toFixed(1)}% of one core`:''}${rate?` · RX/TX: ${rate.rx.toFixed(2)} / ${rate.tx.toFixed(2)} Mbit/s, ${rate.prx.toFixed(0)} / ${rate.ptx.toFixed(0)} packets/s`:''}${t.last_error?` · Last error: ${t.last_error}`:''}`;
  7880. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7881. if(!events.length){node.textContent='No events recorded yet.';return}
  7882. for(const e of events){const line=document.createElement('div');line.textContent=`${new Date(e.time).toLocaleString()} · ${e.type==='check'?'Check':(e.previous?`${e.previous} → ${e.status}${e.previous_duration_seconds?` (after ${Math.round(e.previous_duration_seconds)} s)`:''}`:e.status)}${e.detail?` · ${e.detail}`:''}`;node.appendChild(line)}
  7883. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7884. }
  7885. async function runAeroTUNHealthCheck() {
  7886. const id=state.aeroHealthSelected;if(!id)return;const button=document.getElementById('aerotun-health-check-btn'),output=document.getElementById('aerotun-health-result');button.disabled=true;output.textContent='Checking…';
  7887. try {const response=await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/health-check`,{method:'POST'});if(!response.ok)throw new Error(await responseError(response));const r=await response.json();if(state.aeroHealthSelected!==id)return;output.textContent=`Peer echo: ${r.reachability}${r.rtt_ms!=null?` · RTT ${r.rtt_upper_bound?'<':''}${r.rtt_ms} ms`:''} · ${r.mtu}-byte overlay probe: ${r.mtu_probe}. ${r.explanation}`;await refreshAeroTUNHealth()}
  7888. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7889. finally {button.disabled=false}
  7890. }
  7891. let aeroCompareRunning=false, aeroCompareCancel=false;
  7892. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7893. async function runAeroTUNComparison() {
  7894. if(aeroCompareRunning)return;
  7895. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id),direct=document.getElementById('aerotun-compare-host').value.trim(),port=Number(document.getElementById('aerotun-compare-port').value),peer=(t?.peer_address||'').split('/')[0].trim();
  7896. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7897. if(!t?.connected||!peer||!direct||!Number.isInteger(port)||port<1||port>65535||peer===direct){output.textContent='A connected tunnel, peer IP, different direct server address and valid port are required.';return}
  7898. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7899. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7900. const get=async(path,body)=>{const r=await fetch(`${API_BASE}${path}`,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{});if(!r.ok)throw new Error(await responseError(r));return r.json()};
  7901. const results=[];
  7902. try {
  7903. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7904. if(aeroCompareCancel)break;
  7905. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7906. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7907. const started=await get('/tools/bwtest/start',{target,port,protocol:'tcp',direction,bandwidth_limit:0,packet_size:1200,streams:2,duration:8}),session=started.session_id;let status,complete=false;
  7908. for(let i=0;i<30;i++){await new Promise(resolve=>setTimeout(resolve,1000));status=await get('/tools/bwtest/status');if(status.session_id!==session)throw new Error('Bandwidth test session changed; comparison stopped.');if(!status.running){complete=true;break}}
  7909. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7910. const value=status.summary?.[direction==='tx'?'avg_tx_mbps':'avg_rx_mbps'];if(!Number.isFinite(value)||value<=0)throw new Error(`${path} ${direction.toUpperCase()}: no delivered data.`);
  7911. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7912. }
  7913. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7914. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7915. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7916. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7917. }
  7918. let aeroModalGeneration = 0;
  7919. let aeroIdentityDraft = '';
  7920. let aeroSaving = false;
  7921. let aeroPSKRequest = 0;
  7922. function discardAeroIdentityDraft(id) {
  7923. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7924. }
  7925. async function generateAeroTUNIdentity() {
  7926. const generation = aeroModalGeneration;
  7927. const retry = document.getElementById('aerotun-retry-identity');
  7928. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7929. retry.classList.add('hidden');
  7930. document.getElementById('aerotun-modal-public').value = '';
  7931. try {
  7932. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7933. if (!res.ok) throw new Error(await responseError(res));
  7934. const draft = await res.json();
  7935. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7936. aeroIdentityDraft = draft.draft_id;
  7937. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7938. updateAeroTUNSetupHint();
  7939. } catch (err) {
  7940. if (generation !== aeroModalGeneration) return;
  7941. retry.classList.remove('hidden');
  7942. updateAeroTUNSetupHint();
  7943. showToast('Identity Generation Failed', err.message, 'error');
  7944. }
  7945. }
  7946. function onAeroTUNModeChange() {
  7947. const mode = document.getElementById('aerotun-modal-mode').value;
  7948. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7949. const portInput = document.getElementById('aerotun-modal-port');
  7950. if (mode === 'server') {
  7951. if (!portInput.value) portInput.value = '51830';
  7952. endpointInput.placeholder = 'Optional / learned roaming peer';
  7953. } else {
  7954. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7955. if (!portInput.value) portInput.value = '';
  7956. }
  7957. }
  7958. function onAeroTUNPeerChange() {
  7959. const peer = document.getElementById('aerotun-modal-peer');
  7960. const allowed = document.getElementById('aerotun-modal-allowed');
  7961. const previous = peer.dataset.allowedDefault || '';
  7962. const host = peer.value.trim().split('/')[0];
  7963. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7964. if (allowed.value.trim() === previous) allowed.value = next;
  7965. peer.dataset.allowedDefault = next;
  7966. }
  7967. async function generateAeroTUNKey(automatic = false) {
  7968. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7969. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7970. try {
  7971. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7972. if (!res.ok) throw new Error(await responseError(res));
  7973. const data = await res.json();
  7974. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7975. input.value = data.key;
  7976. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7977. } catch (err) {
  7978. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7979. }
  7980. }
  7981. function updateAeroTUNSetupHint() {
  7982. const version = document.getElementById('aerotun-modal-protocol').value;
  7983. const key = document.getElementById('aerotun-modal-public').value;
  7984. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7985. const hint = document.getElementById('aerotun-setup-hint');
  7986. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7987. if (!hint) return;
  7988. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7989. }
  7990. async function copyAeroTUNPublicKey() {
  7991. const input = document.getElementById('aerotun-modal-public');
  7992. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7993. try {
  7994. await navigator.clipboard.writeText(input.value);
  7995. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7996. } catch {
  7997. input.focus(); input.select();
  7998. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7999. }
  8000. }
  8001. async function copyAeroTUNPSK() {
  8002. const input = document.getElementById('aerotun-modal-psk');
  8003. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  8004. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  8005. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  8006. }
  8007. function openAddAeroTUNModal() {
  8008. if (aeroSaving) return;
  8009. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8010. const tunnels = state.aerotunTunnels || [];
  8011. const usedNames = new Set(tunnels.map(t => t.name));
  8012. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  8013. let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
  8014. if (index >= 256) index = 0;
  8015. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  8016. document.getElementById('aerotun-modal-id').value = '';
  8017. document.getElementById('aerotun-modal-protocol').value='3';
  8018. document.getElementById('aerotun-modal-public').value='';
  8019. document.getElementById('aerotun-modal-peerkey').value='';
  8020. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  8021. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  8022. document.getElementById('aerotun-modal-mode').value = 'server';
  8023. document.getElementById('aerotun-modal-port').value = 51830 + index;
  8024. document.getElementById('aerotun-modal-endpoint').value = '';
  8025. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  8026. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  8027. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  8028. document.getElementById('aerotun-modal-psk').value = '';
  8029. document.getElementById('aerotun-modal-mtu').value = '1420';
  8030. document.getElementById('aerotun-modal-comment').value = '';
  8031. document.getElementById('aerotun-modal-compression').checked = false;
  8032. document.getElementById('aerotun-modal-defroute').checked = false;
  8033. document.getElementById('aerotun-modal-disabled').checked = true;
  8034. document.getElementById('aerotun-modal-psk').type = 'password';
  8035. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8036. onAeroTUNModeChange();
  8037. updateAeroTUNSetupHint();
  8038. document.getElementById('aerotun-modal').classList.remove('hidden');
  8039. generateAeroTUNKey(true);
  8040. generateAeroTUNIdentity();
  8041. }
  8042. function openEditAeroTUNModal(id) {
  8043. if (aeroSaving) return;
  8044. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8045. if (!t) return;
  8046. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8047. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8048. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8049. document.getElementById('aerotun-modal-id').value = t.id;
  8050. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8051. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8052. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8053. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8054. document.getElementById('aerotun-modal-name').value = t.name;
  8055. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8056. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8057. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8058. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8059. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8060. const peerHost = (t.peer_address || '').split('/')[0];
  8061. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8062. document.getElementById('aerotun-modal-psk').value = '';
  8063. document.getElementById('aerotun-modal-psk').type = 'password';
  8064. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8065. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8066. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8067. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8068. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8069. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8070. onAeroTUNModeChange();
  8071. updateAeroTUNSetupHint();
  8072. document.getElementById('aerotun-modal').classList.remove('hidden');
  8073. }
  8074. function closeAeroTUNModal() {
  8075. if (aeroSaving) return;
  8076. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8077. document.getElementById('aerotun-modal-psk').value = '';
  8078. document.getElementById('aerotun-modal').classList.add('hidden');
  8079. }
  8080. async function submitSaveAeroTUN(e) {
  8081. e.preventDefault();
  8082. if (aeroSaving) return;
  8083. const id = document.getElementById('aerotun-modal-id').value;
  8084. const name = document.getElementById('aerotun-modal-name').value.trim();
  8085. const mode = document.getElementById('aerotun-modal-mode').value;
  8086. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8087. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8088. const local = document.getElementById('aerotun-modal-local').value.trim();
  8089. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8090. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8091. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8092. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8093. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8094. const compression = document.getElementById('aerotun-modal-compression').checked;
  8095. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8096. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8097. if (mode === 'client' && !endpoint) {
  8098. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8099. return;
  8100. }
  8101. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8102. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8103. return;
  8104. }
  8105. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8106. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8107. return;
  8108. }
  8109. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8110. if (version === 3 && !id && !aeroIdentityDraft) {
  8111. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8112. return;
  8113. }
  8114. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8115. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8116. document.getElementById('aerotun-modal-allowed').focus();
  8117. return;
  8118. }
  8119. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8120. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8121. return;
  8122. }
  8123. if (!psk && !id) {
  8124. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8125. return;
  8126. }
  8127. aeroSaving = true;
  8128. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8129. if (submit) submit.disabled = true;
  8130. try {
  8131. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8132. method: 'POST',
  8133. headers: { 'Content-Type': 'application/json' },
  8134. body: JSON.stringify({
  8135. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8136. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8137. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8138. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8139. id,
  8140. name,
  8141. mode,
  8142. listen_port: port,
  8143. remote_endpoint: endpoint,
  8144. local_address: local,
  8145. peer_address: peer,
  8146. psk,
  8147. mtu,
  8148. compression,
  8149. default_route: defaultRoute,
  8150. comment,
  8151. disabled
  8152. })
  8153. });
  8154. if (res.ok) {
  8155. await res.json();
  8156. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8157. aeroIdentityDraft = '';
  8158. aeroSaving = false;
  8159. closeAeroTUNModal();
  8160. await loadAeroTUN(false);
  8161. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8162. fetchData(false);
  8163. } else {
  8164. const err = await responseError(res);
  8165. if (err.includes('configuration saved but tunnel failed to start')) {
  8166. aeroIdentityDraft = '';
  8167. aeroSaving = false;
  8168. closeAeroTUNModal();
  8169. await loadAeroTUN(false);
  8170. showToast('Saved, but not started', err, 'error');
  8171. } else showToast('Error Saving Tunnel', err, 'error');
  8172. }
  8173. } catch (err) {
  8174. showToast('Network Error', err.message, 'error');
  8175. } finally {
  8176. aeroSaving = false;
  8177. if (submit) submit.disabled = false;
  8178. }
  8179. }
  8180. async function startAeroTUNTunnel(id) {
  8181. try {
  8182. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8183. if (res.ok) {
  8184. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8185. loadAeroTUN(false);
  8186. fetchData(false);
  8187. } else {
  8188. const err = await res.text();
  8189. showToast('Failed to Start', err, 'error');
  8190. }
  8191. } catch (err) {
  8192. showToast('Error', err.message, 'error');
  8193. }
  8194. }
  8195. async function stopAeroTUNTunnel(id) {
  8196. try {
  8197. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8198. if (res.ok) {
  8199. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8200. loadAeroTUN(false);
  8201. fetchData(false);
  8202. } else {
  8203. const err = await res.text();
  8204. showToast('Failed to Stop', err, 'error');
  8205. }
  8206. } catch (err) {
  8207. showToast('Error', err.message, 'error');
  8208. }
  8209. }
  8210. async function toggleAeroTUNState(id, disabled) {
  8211. try {
  8212. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8213. method: 'POST',
  8214. headers: { 'Content-Type': 'application/json' },
  8215. body: JSON.stringify({ disabled })
  8216. });
  8217. if (res.ok) {
  8218. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8219. loadAeroTUN(false);
  8220. fetchData(false);
  8221. }
  8222. } catch (err) {
  8223. showToast('Error', err.message, 'error');
  8224. }
  8225. }
  8226. async function deleteAeroTUN(id) {
  8227. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8228. try {
  8229. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8230. if (res.ok) {
  8231. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8232. loadAeroTUN(false);
  8233. fetchData(false);
  8234. }
  8235. } catch (err) {
  8236. showToast('Error', err.message, 'error');
  8237. }
  8238. }
  8239. // ======================== PPP Central Hub & Servers ========================
  8240. function switchPPPSubTab(tab) {
  8241. state.pppSubTab = tab;
  8242. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8243. tabs.forEach(t => {
  8244. const panel = document.getElementById(`ppp-subtab-${t}`);
  8245. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8246. if (panel) {
  8247. if (t === tab) panel.classList.remove('hidden');
  8248. else panel.classList.add('hidden');
  8249. }
  8250. if (btn) {
  8251. if (t === tab) {
  8252. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  8253. } else {
  8254. 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';
  8255. }
  8256. }
  8257. });
  8258. const addBtn = document.getElementById('ppp-primary-add-btn');
  8259. if (addBtn) {
  8260. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8261. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8262. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8263. else addBtn.innerHTML = '<span>Save Config</span>';
  8264. }
  8265. if (tab === 'active') loadPPPSessions();
  8266. }
  8267. function openCurrentPPPModal() {
  8268. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8269. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8270. else if (state.pppSubTab === 'active') loadPPPSessions();
  8271. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8272. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8273. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8274. }
  8275. async function loadPPP(populateDropdowns = true) {
  8276. await Promise.all([
  8277. loadPPPSecrets(),
  8278. loadPPPProfiles(),
  8279. loadPPPServers(),
  8280. loadPPPSessions()
  8281. ]);
  8282. }
  8283. async function loadPPPSecrets() {
  8284. try {
  8285. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8286. const data = await res.json();
  8287. state.pppSecrets = Array.isArray(data) ? data : [];
  8288. const b = document.getElementById('ppp-badge-secrets');
  8289. if (b) b.innerText = state.pppSecrets.length;
  8290. const b2 = document.getElementById('secrets-count-badge');
  8291. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8292. renderPPPSecrets();
  8293. } catch (err) {
  8294. console.error('Failed to load PPP secrets:', err);
  8295. }
  8296. }
  8297. function renderPPPSecrets() {
  8298. const tbody = document.getElementById('secrets-table-body');
  8299. const empty = document.getElementById('secrets-empty');
  8300. if (!tbody) return;
  8301. tbody.innerHTML = '';
  8302. const secrets = state.pppSecrets || [];
  8303. if (secrets.length === 0) {
  8304. empty?.classList.remove('hidden');
  8305. return;
  8306. }
  8307. empty?.classList.add('hidden');
  8308. secrets.forEach(s => {
  8309. const tr = document.createElement('tr');
  8310. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8311. tr.innerHTML = `
  8312. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8313. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8314. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8315. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8316. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8317. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8318. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8319. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8320. <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>
  8321. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8322. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8323. </td>
  8324. `;
  8325. tbody.appendChild(tr);
  8326. });
  8327. }
  8328. async function loadPPPProfiles() {
  8329. try {
  8330. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8331. const data = await res.json();
  8332. state.pppProfiles = Array.isArray(data) ? data : [];
  8333. const b = document.getElementById('ppp-badge-profiles');
  8334. if (b) b.innerText = state.pppProfiles.length;
  8335. const b2 = document.getElementById('profiles-count-badge');
  8336. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8337. // Populate profile selects across modals
  8338. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8339. selects.forEach(sid => {
  8340. const el = document.getElementById(sid);
  8341. if (!el) return;
  8342. const cur = el.value;
  8343. el.innerHTML = '';
  8344. state.pppProfiles.forEach(p => {
  8345. const opt = document.createElement('option');
  8346. opt.value = p.name;
  8347. opt.innerText = `${p.name} (${p.remote_address})`;
  8348. if (p.name === cur) opt.selected = true;
  8349. el.appendChild(opt);
  8350. });
  8351. });
  8352. renderPPPProfiles();
  8353. } catch (err) {
  8354. console.error('Failed to load PPP profiles:', err);
  8355. }
  8356. }
  8357. function renderPPPProfiles() {
  8358. const tbody = document.getElementById('profiles-table-body');
  8359. if (!tbody) return;
  8360. tbody.innerHTML = '';
  8361. (state.pppProfiles || []).forEach(p => {
  8362. const isDefault = p.name.startsWith('default');
  8363. const tr = document.createElement('tr');
  8364. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8365. tr.innerHTML = `
  8366. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8367. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8368. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8369. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8370. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8371. <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>
  8372. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8373. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8374. ${!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>`}
  8375. </td>
  8376. `;
  8377. tbody.appendChild(tr);
  8378. });
  8379. }
  8380. async function loadPPPServers() {
  8381. try {
  8382. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8383. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8384. fetch(`${API_BASE}/vpn/servers/pptp`),
  8385. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8386. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8387. ]);
  8388. if (pppoeRes.ok) {
  8389. state.pppoeServer = await pppoeRes.json();
  8390. const s = state.pppoeServer;
  8391. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8392. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8393. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8394. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8395. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8396. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8397. const pill = document.getElementById('pppoe-server-status-pill');
  8398. if (pill) {
  8399. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8400. 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';
  8401. }
  8402. setDotBadge('ppp-badge-pppoe-state', s.running);
  8403. }
  8404. if (pptpRes.ok) {
  8405. state.pptpServer = await pptpRes.json();
  8406. const s = state.pptpServer;
  8407. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8408. document.getElementById('pptp-server-port').value = s.port || 1723;
  8409. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8410. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8411. const pill = document.getElementById('pptp-server-status-pill');
  8412. if (pill) {
  8413. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8414. 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';
  8415. }
  8416. setDotBadge('ppp-badge-pptp-state', s.running);
  8417. }
  8418. if (l2tpRes.ok) {
  8419. state.l2tpServer = await l2tpRes.json();
  8420. const s = state.l2tpServer;
  8421. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8422. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8423. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8424. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8425. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8426. const pill = document.getElementById('l2tp-server-status-pill');
  8427. if (pill) {
  8428. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8429. 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';
  8430. }
  8431. setDotBadge('ppp-badge-l2tp-state', s.running);
  8432. }
  8433. if (ipsecRes.ok) {
  8434. state.ipsecServer = await ipsecRes.json();
  8435. const s = state.ipsecServer;
  8436. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8437. if (modalEn) modalEn.checked = !!s.enabled;
  8438. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8439. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8440. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8441. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8442. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8443. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8444. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8445. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8446. const pill = document.getElementById('modal-ipsec-server-status');
  8447. if (pill) {
  8448. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8449. 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';
  8450. }
  8451. }
  8452. } catch (err) {
  8453. console.error('Failed to load VPN servers:', err);
  8454. }
  8455. }
  8456. async function loadPPPSessions() {
  8457. try {
  8458. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8459. const data = await res.json();
  8460. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8461. const b = document.getElementById('ppp-badge-active');
  8462. if (b) b.innerText = state.pppActiveSessions.length;
  8463. const sideB = document.getElementById('badge-ppp-sessions');
  8464. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8465. renderPPPSessions();
  8466. } catch (err) {
  8467. console.error('Failed to load active PPP sessions:', err);
  8468. }
  8469. }
  8470. function renderPPPSessions() {
  8471. const tbody = document.getElementById('active-ppp-table-body');
  8472. const empty = document.getElementById('active-ppp-empty');
  8473. if (!tbody) return;
  8474. tbody.innerHTML = '';
  8475. const list = state.pppActiveSessions || [];
  8476. if (list.length === 0) {
  8477. empty?.classList.remove('hidden');
  8478. return;
  8479. }
  8480. empty?.classList.add('hidden');
  8481. list.forEach(s => {
  8482. const tr = document.createElement('tr');
  8483. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8484. tr.innerHTML = `
  8485. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8486. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8487. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8488. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8489. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8490. <td class="py-2.5 px-3 text-[11px]">
  8491. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8492. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8493. </td>
  8494. <td class="py-2.5 px-3 text-right font-sans">
  8495. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8496. </td>
  8497. `;
  8498. tbody.appendChild(tr);
  8499. });
  8500. }
  8501. async function disconnectPPPSession(iface) {
  8502. if (!confirm(`Disconnect session ${iface}?`)) return;
  8503. try {
  8504. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8505. if (res.ok) {
  8506. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8507. loadPPPSessions();
  8508. }
  8509. } catch (err) {
  8510. showToast('Error', err.message, 'error');
  8511. }
  8512. }
  8513. // PPP Secret Modal handlers
  8514. function openAddPPPSecretModal() {
  8515. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8516. document.getElementById('secret-modal-id').value = '';
  8517. document.getElementById('secret-modal-name').value = '';
  8518. document.getElementById('secret-modal-password').value = '';
  8519. document.getElementById('secret-modal-service').value = 'any';
  8520. document.getElementById('secret-modal-profile').value = 'default';
  8521. document.getElementById('secret-modal-local').value = '';
  8522. document.getElementById('secret-modal-remote').value = '';
  8523. document.getElementById('secret-modal-comment').value = '';
  8524. document.getElementById('secret-modal-disabled').checked = false;
  8525. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8526. }
  8527. function openEditPPPSecretModal(id) {
  8528. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8529. if (!s) return;
  8530. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8531. document.getElementById('secret-modal-id').value = s.id;
  8532. document.getElementById('secret-modal-name').value = s.name;
  8533. document.getElementById('secret-modal-password').value = s.password;
  8534. document.getElementById('secret-modal-service').value = s.service || 'any';
  8535. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8536. document.getElementById('secret-modal-local').value = s.local_address || '';
  8537. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8538. document.getElementById('secret-modal-comment').value = s.comment || '';
  8539. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8540. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8541. }
  8542. function closePPPSecretModal() {
  8543. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8544. }
  8545. async function submitSavePPPSecret(e) {
  8546. e.preventDefault();
  8547. const id = document.getElementById('secret-modal-id').value;
  8548. const name = document.getElementById('secret-modal-name').value.trim();
  8549. const password = document.getElementById('secret-modal-password').value.trim();
  8550. const service = document.getElementById('secret-modal-service').value;
  8551. const profile = document.getElementById('secret-modal-profile').value;
  8552. const local = document.getElementById('secret-modal-local').value.trim();
  8553. const remote = document.getElementById('secret-modal-remote').value.trim();
  8554. const comment = document.getElementById('secret-modal-comment').value.trim();
  8555. const disabled = document.getElementById('secret-modal-disabled').checked;
  8556. try {
  8557. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8558. method: 'POST',
  8559. headers: { 'Content-Type': 'application/json' },
  8560. body: JSON.stringify({
  8561. id,
  8562. name,
  8563. password,
  8564. service,
  8565. profile,
  8566. local_address: local,
  8567. remote_address: remote,
  8568. comment,
  8569. disabled
  8570. })
  8571. });
  8572. if (res.ok) {
  8573. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8574. closePPPSecretModal();
  8575. loadPPPSecrets();
  8576. } else {
  8577. const err = await res.json();
  8578. showToast('Error', err.message, 'error');
  8579. }
  8580. } catch (err) {
  8581. showToast('Error', err.message, 'error');
  8582. }
  8583. }
  8584. async function togglePPPSecretState(id, disabled) {
  8585. try {
  8586. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8587. method: 'POST',
  8588. headers: { 'Content-Type': 'application/json' },
  8589. body: JSON.stringify({ disabled })
  8590. });
  8591. if (res.ok) {
  8592. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8593. loadPPPSecrets();
  8594. }
  8595. } catch (err) {
  8596. showToast('Error', err.message, 'error');
  8597. }
  8598. }
  8599. async function deletePPPSecret(id) {
  8600. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8601. try {
  8602. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8603. if (res.ok) {
  8604. showToast('Deleted', 'Secret account removed', 'success');
  8605. loadPPPSecrets();
  8606. }
  8607. } catch (err) {
  8608. showToast('Error', err.message, 'error');
  8609. }
  8610. }
  8611. // PPP Profile Modal handlers
  8612. function openAddPPPProfileModal() {
  8613. document.getElementById('profile-modal-name').value = '';
  8614. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8615. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8616. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8617. document.getElementById('profile-modal-encryption').value = 'required';
  8618. document.getElementById('profile-modal-onlyone').checked = true;
  8619. document.getElementById('profile-modal-comment').value = '';
  8620. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8621. }
  8622. function closePPPProfileModal() {
  8623. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8624. }
  8625. async function submitSavePPPProfile(e) {
  8626. e.preventDefault();
  8627. const name = document.getElementById('profile-modal-name').value.trim();
  8628. const local = document.getElementById('profile-modal-local').value.trim();
  8629. const remote = document.getElementById('profile-modal-remote').value.trim();
  8630. const dns = document.getElementById('profile-modal-dns').value.trim();
  8631. const enc = document.getElementById('profile-modal-encryption').value;
  8632. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8633. const comment = document.getElementById('profile-modal-comment').value.trim();
  8634. try {
  8635. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8636. method: 'POST',
  8637. headers: { 'Content-Type': 'application/json' },
  8638. body: JSON.stringify({
  8639. id: name,
  8640. name,
  8641. local_address: local,
  8642. remote_address: remote,
  8643. dns_servers: dns,
  8644. use_encryption: enc,
  8645. only_one: onlyone,
  8646. comment
  8647. })
  8648. });
  8649. if (res.ok) {
  8650. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8651. closePPPProfileModal();
  8652. loadPPPProfiles();
  8653. } else {
  8654. const err = await res.json();
  8655. showToast('Error', err.message, 'error');
  8656. }
  8657. } catch (err) {
  8658. showToast('Error', err.message, 'error');
  8659. }
  8660. }
  8661. async function deletePPPProfile(name) {
  8662. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8663. try {
  8664. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8665. if (res.ok) {
  8666. showToast('Deleted', 'Profile removed', 'success');
  8667. loadPPPProfiles();
  8668. } else {
  8669. const err = await res.json();
  8670. showToast('Error', err.message, 'error');
  8671. }
  8672. } catch (err) {
  8673. showToast('Error', err.message, 'error');
  8674. }
  8675. }
  8676. // Server Config submissions
  8677. async function savePPPoEServerConfig(e) {
  8678. e.preventDefault();
  8679. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8680. const name = document.getElementById('pppoe-server-name').value.trim();
  8681. const iface = document.getElementById('pppoe-server-iface').value;
  8682. const profile = document.getElementById('pppoe-server-profile').value;
  8683. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8684. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8685. try {
  8686. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8687. method: 'POST',
  8688. headers: { 'Content-Type': 'application/json' },
  8689. body: JSON.stringify({
  8690. enabled,
  8691. service_name: name,
  8692. interface: iface,
  8693. default_profile: profile,
  8694. max_mtu: mtu,
  8695. max_mru: mtu,
  8696. one_session_per_host: onesession
  8697. })
  8698. });
  8699. if (res.ok) {
  8700. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8701. loadPPPServers();
  8702. fetchData(false);
  8703. } else {
  8704. const err = await res.json();
  8705. showToast('Error', err.message, 'error');
  8706. }
  8707. } catch (err) {
  8708. showToast('Error', err.message, 'error');
  8709. }
  8710. }
  8711. async function savePPTPServerConfig(e) {
  8712. e.preventDefault();
  8713. const enabled = document.getElementById('pptp-server-enabled').checked;
  8714. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8715. const profile = document.getElementById('pptp-server-profile').value;
  8716. const mppe = document.getElementById('pptp-server-mppe').checked;
  8717. try {
  8718. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8719. method: 'POST',
  8720. headers: { 'Content-Type': 'application/json' },
  8721. body: JSON.stringify({
  8722. enabled,
  8723. port,
  8724. default_profile: profile,
  8725. require_mppe: mppe
  8726. })
  8727. });
  8728. if (res.ok) {
  8729. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8730. loadPPPServers();
  8731. fetchData(false);
  8732. } else {
  8733. const err = await res.json();
  8734. showToast('Error', err.message, 'error');
  8735. }
  8736. } catch (err) {
  8737. showToast('Error', err.message, 'error');
  8738. }
  8739. }
  8740. async function saveL2TPServerConfig(e) {
  8741. e.preventDefault();
  8742. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8743. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8744. const profile = document.getElementById('l2tp-server-profile').value;
  8745. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8746. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8747. try {
  8748. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8749. method: 'POST',
  8750. headers: { 'Content-Type': 'application/json' },
  8751. body: JSON.stringify({
  8752. enabled,
  8753. port,
  8754. default_profile: profile,
  8755. use_ipsec: useipsec,
  8756. ipsec_secret: psk
  8757. })
  8758. });
  8759. if (res.ok) {
  8760. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8761. loadPPPServers();
  8762. fetchData(false);
  8763. } else {
  8764. const err = await res.json();
  8765. showToast('Error', err.message, 'error');
  8766. }
  8767. } catch (err) {
  8768. showToast('Error', err.message, 'error');
  8769. }
  8770. }
  8771. // IPSec Server Modal
  8772. function openIPSecServerModal() {
  8773. loadPPPServers();
  8774. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8775. }
  8776. function closeIPSecServerModal() {
  8777. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8778. }
  8779. async function submitSaveIPSecServer(e) {
  8780. e.preventDefault();
  8781. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8782. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8783. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8784. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8785. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8786. try {
  8787. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8788. method: 'POST',
  8789. headers: { 'Content-Type': 'application/json' },
  8790. body: JSON.stringify({
  8791. enabled,
  8792. preshared_key: psk,
  8793. pool_address: pool,
  8794. dns_servers: dns,
  8795. local_subnet: subnet
  8796. })
  8797. });
  8798. if (res.ok) {
  8799. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8800. closeIPSecServerModal();
  8801. loadPPPServers();
  8802. fetchData(false);
  8803. } else {
  8804. const err = await res.json();
  8805. showToast('Error', err.message, 'error');
  8806. }
  8807. } catch (err) {
  8808. showToast('Error', err.message, 'error');
  8809. }
  8810. }
  8811. // WireGuard Client Config Viewer
  8812. let currentWGClientConf = '';
  8813. async function openWGClientConfModal(iface, clientIP) {
  8814. try {
  8815. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8816. method: 'POST',
  8817. headers: { 'Content-Type': 'application/json' },
  8818. body: JSON.stringify({
  8819. interface: iface,
  8820. address: clientIP || '10.10.0.2/32',
  8821. dns: '1.1.1.1, 8.8.8.8'
  8822. })
  8823. });
  8824. if (res.ok) {
  8825. const data = await res.json();
  8826. currentWGClientConf = data.config;
  8827. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8828. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8829. } else {
  8830. const err = await res.json();
  8831. showToast('Error', err.message, 'error');
  8832. }
  8833. } catch (err) {
  8834. showToast('Error', err.message, 'error');
  8835. }
  8836. }
  8837. function closeWGClientConfModal() {
  8838. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8839. }
  8840. function copyWGClientConf() {
  8841. if (!currentWGClientConf) return;
  8842. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8843. }
  8844. function downloadWGClientConf() {
  8845. if (!currentWGClientConf) return;
  8846. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8847. const a = document.createElement('a');
  8848. a.href = URL.createObjectURL(blob);
  8849. a.download = 'wireguard-client.conf';
  8850. document.body.appendChild(a);
  8851. a.click();
  8852. document.body.removeChild(a);
  8853. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8854. }
  8855. // =========================================================================
  8856. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8857. // =========================================================================
  8858. state.activeDynSubTab = 'bgp-peers';
  8859. state.activeBgpSubTab = 'bgp-peers';
  8860. state.activeOspfTab = 'instances';
  8861. state.bgpInstance = null;
  8862. state.bgpPeers = [];
  8863. state.bgpNets = [];
  8864. state.bgpRoutes = [];
  8865. state.ospfInstance = null;
  8866. state.ospfInstances = [];
  8867. state.ospfAreas = [];
  8868. state.ospfAreaRanges = [];
  8869. state.ospfTemplates = [];
  8870. state.ospfLiveInterfaces = [];
  8871. state.ospfStaticNbrs = [];
  8872. state.ospfNeighbors = [];
  8873. state.ospfLSA = [];
  8874. state.ospfRoutes = [];
  8875. state.selectedOspfRow = {
  8876. instances: null,
  8877. areas: null,
  8878. 'area-ranges': null,
  8879. templates: null,
  8880. interfaces: null,
  8881. 'static-nbrs': null,
  8882. neighbors: null,
  8883. lsa: null,
  8884. };
  8885. state.ospfSort = {
  8886. instances: { col: 'name', asc: true },
  8887. areas: { col: 'name', asc: true },
  8888. ranges: { col: 'area', asc: true },
  8889. templates: { col: 'interfaces', asc: true },
  8890. live_ifaces: { col: 'interface', asc: true },
  8891. snbrs: { col: 'address', asc: true },
  8892. neighbors: { col: 'address', asc: true },
  8893. lsa: { col: 'instance', asc: true },
  8894. };
  8895. function switchBgpSubTab(subTab) {
  8896. state.activeBgpSubTab = subTab;
  8897. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8898. tabs.forEach(t => {
  8899. const el = document.getElementById(`dyn-subtab-${t}`);
  8900. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8901. if (el) el.classList.toggle('hidden', t !== subTab);
  8902. if (btn) {
  8903. if (t === subTab) {
  8904. 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';
  8905. } else {
  8906. 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';
  8907. }
  8908. }
  8909. });
  8910. }
  8911. function switchOspfTab(tabName) {
  8912. state.activeOspfTab = tabName;
  8913. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8914. tabs.forEach(t => {
  8915. const pane = document.getElementById(`ospf-pane-${t}`);
  8916. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8917. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8918. if (btn) {
  8919. if (t === tabName) {
  8920. 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';
  8921. } else {
  8922. 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';
  8923. }
  8924. }
  8925. });
  8926. }
  8927. function switchOspfSubTab(tab) {
  8928. // Legacy alias
  8929. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8930. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8931. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8932. else switchOspfTab('instances');
  8933. }
  8934. function switchDynSubTab(subTab) {
  8935. if (subTab.startsWith('bgp')) {
  8936. if (state.activeTab !== 'bgp') navigate('bgp');
  8937. switchBgpSubTab(subTab);
  8938. } else if (subTab.startsWith('ospf')) {
  8939. if (state.activeTab !== 'ospf') navigate('ospf');
  8940. switchOspfTab('instances');
  8941. }
  8942. }
  8943. async function loadDynamicRouting(showToastMsg = false) {
  8944. try {
  8945. const fetchSafeJson = async (url) => {
  8946. try {
  8947. const r = await fetch(url);
  8948. return r.ok ? await r.json() : null;
  8949. } catch (e) {
  8950. return null;
  8951. }
  8952. };
  8953. const [
  8954. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8955. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8956. commLists, asLists,
  8957. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  8958. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  8959. babelInsts, babelIfaces, babelLiveIfaces, babelNbrs, babelRoutes,
  8960. radvInsts, radvIfaces,
  8961. eigrpInsts, eigrpIfaces, eigrpNets, eigrpNbrs, eigrpTopology
  8962. ] = await Promise.all([
  8963. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8964. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8965. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8966. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8967. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8968. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8969. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8970. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8971. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8972. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8973. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8974. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8975. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8976. fetchSafeJson(`${API_BASE}/routing/filters`),
  8977. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8978. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`),
  8979. fetchSafeJson(`${API_BASE}/routing/rip/instances`),
  8980. fetchSafeJson(`${API_BASE}/routing/rip/interfaces`),
  8981. fetchSafeJson(`${API_BASE}/routing/rip/neighbors-live`),
  8982. fetchSafeJson(`${API_BASE}/routing/rip/routes`),
  8983. fetchSafeJson(`${API_BASE}/routing/bfd/instance`),
  8984. fetchSafeJson(`${API_BASE}/routing/bfd/interfaces`),
  8985. fetchSafeJson(`${API_BASE}/routing/bfd/peers`),
  8986. fetchSafeJson(`${API_BASE}/routing/bfd/sessions`),
  8987. fetchSafeJson(`${API_BASE}/routing/babel/instances`),
  8988. fetchSafeJson(`${API_BASE}/routing/babel/interfaces`),
  8989. fetchSafeJson(`${API_BASE}/routing/babel/interfaces-live`),
  8990. fetchSafeJson(`${API_BASE}/routing/babel/neighbors`),
  8991. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  8992. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  8993. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`),
  8994. fetchSafeJson(`${API_BASE}/routing/eigrp/instances`),
  8995. fetchSafeJson(`${API_BASE}/routing/eigrp/interfaces`),
  8996. fetchSafeJson(`${API_BASE}/routing/eigrp/networks`),
  8997. fetchSafeJson(`${API_BASE}/routing/eigrp/neighbors`),
  8998. fetchSafeJson(`${API_BASE}/routing/eigrp/topology`)
  8999. ]);
  9000. if (sum) state.dynSummary = sum;
  9001. if (bgpInst) state.bgpInstance = bgpInst;
  9002. if (bgpPeers) state.bgpPeers = bgpPeers;
  9003. if (bgpNets) state.bgpNets = bgpNets;
  9004. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  9005. if (ospfInsts) state.ospfInstances = ospfInsts;
  9006. if (ospfAreas) state.ospfAreas = ospfAreas;
  9007. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  9008. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  9009. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  9010. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  9011. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  9012. if (ospfLsa) state.ospfLSA = ospfLsa;
  9013. if (filters) state.routingFilters = filters;
  9014. if (commLists) state.routingCommunityLists = commLists;
  9015. if (asLists) state.routingASLists = asLists;
  9016. if (ripInsts) state.ripInstances = ripInsts;
  9017. if (ripIfaces) state.ripInterfaces = ripIfaces;
  9018. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  9019. if (ripRoutes) state.ripRoutes = ripRoutes;
  9020. if (bfdInst) state.bfdInstance = bfdInst;
  9021. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  9022. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  9023. if (bfdSessions) state.bfdSessions = bfdSessions;
  9024. if (babelInsts) state.babelInstances = babelInsts;
  9025. if (babelIfaces) state.babelInterfaces = babelIfaces;
  9026. if (babelLiveIfaces) state.babelInterfacesLive = babelLiveIfaces;
  9027. if (babelNbrs) state.babelNeighbors = babelNbrs;
  9028. if (babelRoutes) state.babelRoutes = babelRoutes;
  9029. if (radvInsts) state.radvInstances = radvInsts;
  9030. if (radvIfaces) state.radvInterfaces = radvIfaces;
  9031. if (eigrpInsts) state.eigrpInstances = eigrpInsts;
  9032. if (eigrpIfaces) state.eigrpInterfaces = eigrpIfaces;
  9033. if (eigrpNets) state.eigrpNetworks = eigrpNets;
  9034. if (eigrpNbrs) state.eigrpNeighbors = eigrpNbrs;
  9035. if (eigrpTopology) state.eigrpTopology = eigrpTopology;
  9036. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  9037. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  9038. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  9039. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  9040. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  9041. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  9042. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  9043. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  9044. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  9045. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9046. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9047. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9048. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9049. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9050. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9051. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9052. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9053. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9054. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9055. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9056. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9057. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9058. try { renderBabelLiveInterfaces(); } catch(e) { console.error('renderBabelLiveInterfaces error:', e); }
  9059. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9060. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9061. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9062. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9063. try { renderEigrpInstances(); } catch(e) { console.error('renderEigrpInstances error:', e); }
  9064. try { renderEigrpNetworks(); } catch(e) { console.error('renderEigrpNetworks error:', e); }
  9065. try { renderEigrpInterfaces(); } catch(e) { console.error('renderEigrpInterfaces error:', e); }
  9066. try { renderEigrpNeighbors(); } catch(e) { console.error('renderEigrpNeighbors error:', e); }
  9067. try { renderEigrpTopology(); } catch(e) { console.error('renderEigrpTopology error:', e); }
  9068. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9069. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9070. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9071. } catch (err) {
  9072. console.error('Failed to load dynamic routing:', err);
  9073. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9074. }
  9075. }
  9076. async function loadOspfAll() {
  9077. await loadDynamicRouting(true);
  9078. }
  9079. function renderBgpStatusPill() {
  9080. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9081. pills.forEach(pill => {
  9082. const inst = state.bgpInstance;
  9083. if (!inst || !inst.enabled) {
  9084. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  9085. pill.innerText = 'BGP DISABLED';
  9086. } else if (inst.running) {
  9087. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  9088. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9089. } else {
  9090. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  9091. pill.innerText = 'BGP STARTING...';
  9092. }
  9093. });
  9094. }
  9095. function renderBgpPeers() {
  9096. const tbody = document.getElementById('bgp-peers-table-body');
  9097. if (!tbody) return;
  9098. const empty = document.getElementById('bgp-peers-empty');
  9099. const countBadge = document.getElementById('bgp-peers-count-badge');
  9100. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9101. const peers = state.bgpPeers || [];
  9102. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9103. if (navBadge) navBadge.innerText = peers.length;
  9104. if (peers.length === 0) {
  9105. tbody.innerHTML = '';
  9106. if (empty) empty.classList.remove('hidden');
  9107. return;
  9108. }
  9109. if (empty) empty.classList.add('hidden');
  9110. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9111. if (tbody.dataset.sig === sig) return;
  9112. tbody.dataset.sig = sig;
  9113. tbody.innerHTML = peers.map(p => {
  9114. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9115. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9116. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9117. let stateBadge = '';
  9118. if (p.disabled) {
  9119. 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>';
  9120. } else if (p.state === 'Established') {
  9121. 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>';
  9122. } else if (p.state === 'Connect' || p.state === 'Active') {
  9123. 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>`;
  9124. } else {
  9125. 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>`;
  9126. }
  9127. return `
  9128. <tr class="hover:bg-slate-800/40 transition">
  9129. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9130. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9131. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9132. <td class="py-2.5 px-3">
  9133. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9134. ${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>`}
  9135. </td>
  9136. <td class="py-2.5 px-3">${stateBadge}</td>
  9137. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9138. <td class="py-2.5 px-3 text-slate-300">
  9139. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9140. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9141. </td>
  9142. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9143. ${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> ` : ''}
  9144. ${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>` : ''}
  9145. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9146. </td>
  9147. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9148. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9149. <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'}">
  9150. ${p.disabled ? 'Enable' : 'Disable'}
  9151. </button>
  9152. <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">
  9153. Edit
  9154. </button>
  9155. <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">
  9156. Delete
  9157. </button>
  9158. </td>
  9159. </tr>
  9160. `;
  9161. }).join('');
  9162. }
  9163. function renderBgpNetworks() {
  9164. const tbody = document.getElementById('bgp-nets-table-body');
  9165. if (!tbody) return;
  9166. const empty = document.getElementById('bgp-nets-empty');
  9167. const countBadge = document.getElementById('bgp-nets-count-badge');
  9168. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9169. const nets = state.bgpNets || [];
  9170. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9171. if (navBadge) navBadge.innerText = nets.length;
  9172. if (nets.length === 0) {
  9173. tbody.innerHTML = '';
  9174. if (empty) empty.classList.remove('hidden');
  9175. return;
  9176. }
  9177. if (empty) empty.classList.add('hidden');
  9178. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9179. if (tbody.dataset.sig === sig) return;
  9180. tbody.dataset.sig = sig;
  9181. tbody.innerHTML = nets.map(n => `
  9182. <tr class="hover:bg-slate-800/40 transition">
  9183. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9184. <td class="py-2.5 px-3">
  9185. ${n.disabled
  9186. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9187. : '<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>'}
  9188. </td>
  9189. <td class="py-2.5 px-3">
  9190. ${n.disabled
  9191. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9192. : '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-cyan-800/40 font-mono">blackhole (dist 255)</span>'}
  9193. </td>
  9194. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9195. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9196. <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">
  9197. Delete
  9198. </button>
  9199. </td>
  9200. </tr>
  9201. `).join('');
  9202. }
  9203. function renderBgpRoutes() {
  9204. const tbody = document.getElementById('bgp-routes-table-body');
  9205. if (!tbody) return;
  9206. const empty = document.getElementById('bgp-routes-empty');
  9207. const countBadge = document.getElementById('bgp-routes-count-badge');
  9208. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9209. const routes = state.bgpRoutes || [];
  9210. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9211. if (navBadge) navBadge.innerText = routes.length;
  9212. if (routes.length === 0) {
  9213. tbody.innerHTML = '';
  9214. if (empty) empty.classList.remove('hidden');
  9215. return;
  9216. }
  9217. if (empty) empty.classList.add('hidden');
  9218. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9219. if (tbody.dataset.sig === sig) return;
  9220. tbody.dataset.sig = sig;
  9221. tbody.innerHTML = routes.map(r => `
  9222. <tr class="hover:bg-slate-800/40 transition">
  9223. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9224. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9225. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9226. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9227. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9228. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9229. </tr>
  9230. `).join('');
  9231. }
  9232. // =========================================================================
  9233. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9234. // =========================================================================
  9235. function sortOspfTable(tab, col) {
  9236. if (!state.ospfSort) state.ospfSort = {};
  9237. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9238. if (state.ospfSort[tab].col === col) {
  9239. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9240. } else {
  9241. state.ospfSort[tab].col = col;
  9242. state.ospfSort[tab].asc = true;
  9243. }
  9244. const asc = state.ospfSort[tab].asc;
  9245. let list = [];
  9246. if (tab === 'instances') list = state.ospfInstances || [];
  9247. else if (tab === 'areas') list = state.ospfAreas || [];
  9248. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9249. else if (tab === 'templates') list = state.ospfTemplates || [];
  9250. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9251. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9252. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9253. else if (tab === 'lsa') list = state.ospfLSA || [];
  9254. list.sort((a, b) => {
  9255. let valA = a[col] ?? '';
  9256. let valB = b[col] ?? '';
  9257. if (typeof valA === 'number' && typeof valB === 'number') {
  9258. return asc ? valA - valB : valB - valA;
  9259. }
  9260. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9261. });
  9262. if (tab === 'instances') renderOspfInstances();
  9263. else if (tab === 'areas') renderOspfAreas();
  9264. else if (tab === 'ranges') renderOspfAreaRanges();
  9265. else if (tab === 'templates') renderOspfTemplates();
  9266. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9267. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9268. else if (tab === 'neighbors') renderOspfNeighbors();
  9269. else if (tab === 'lsa') renderOspfLSA();
  9270. }
  9271. function selectOspfRow(tab, id) {
  9272. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9273. state.selectedOspfRow[tab] = id;
  9274. if (tab === 'instances') {
  9275. renderOspfInstances();
  9276. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9277. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9278. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9279. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9280. if (btnEn) btnEn.disabled = false;
  9281. if (btnDis) btnDis.disabled = false;
  9282. if (btnRem) btnRem.disabled = false;
  9283. if (btnCom) btnCom.disabled = false;
  9284. } else if (tab === 'areas') {
  9285. renderOspfAreas();
  9286. const btnEn = document.getElementById('btn-ospf-area-enable');
  9287. const btnDis = document.getElementById('btn-ospf-area-disable');
  9288. const btnRem = document.getElementById('btn-ospf-area-remove');
  9289. const btnCom = document.getElementById('btn-ospf-area-comment');
  9290. if (btnEn) btnEn.disabled = false;
  9291. if (btnDis) btnDis.disabled = false;
  9292. if (btnRem) btnRem.disabled = false;
  9293. if (btnCom) btnCom.disabled = false;
  9294. } else if (tab === 'ranges') {
  9295. renderOspfAreaRanges();
  9296. const btnEn = document.getElementById('btn-ospf-range-enable');
  9297. const btnDis = document.getElementById('btn-ospf-range-disable');
  9298. const btnRem = document.getElementById('btn-ospf-range-remove');
  9299. const btnCom = document.getElementById('btn-ospf-range-comment');
  9300. if (btnEn) btnEn.disabled = false;
  9301. if (btnDis) btnDis.disabled = false;
  9302. if (btnRem) btnRem.disabled = false;
  9303. if (btnCom) btnCom.disabled = false;
  9304. } else if (tab === 'templates') {
  9305. renderOspfTemplates();
  9306. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9307. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9308. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9309. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9310. if (btnEn) btnEn.disabled = false;
  9311. if (btnDis) btnDis.disabled = false;
  9312. if (btnRem) btnRem.disabled = false;
  9313. if (btnCom) btnCom.disabled = false;
  9314. } else if (tab === 'snbrs') {
  9315. renderOspfStaticNbrs();
  9316. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9317. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9318. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9319. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9320. if (btnEn) btnEn.disabled = false;
  9321. if (btnDis) btnDis.disabled = false;
  9322. if (btnRem) btnRem.disabled = false;
  9323. if (btnCom) btnCom.disabled = false;
  9324. }
  9325. }
  9326. // TAB 1: INSTANCES
  9327. function renderOspfInstances() {
  9328. const tbody = document.getElementById('ospf-instances-table-body');
  9329. if (!tbody) return;
  9330. const countEl = document.getElementById('ospf-instances-footer-count');
  9331. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9332. let list = state.ospfInstances || [];
  9333. if (filter) {
  9334. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9335. }
  9336. if (countEl) countEl.innerText = list.length;
  9337. const selId = state.selectedOspfRow?.instances;
  9338. tbody.innerHTML = list.map((inst, idx) => {
  9339. const isSel = inst.id === selId;
  9340. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9341. const flagD = inst.disabled
  9342. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  9343. : (inst.running
  9344. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  9345. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  9346. const redist = [];
  9347. if (inst.redistribute_connected) redist.push('conn');
  9348. if (inst.redistribute_static) redist.push('static');
  9349. if (inst.redistribute_bgp) redist.push('bgp');
  9350. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9351. redist.push('default');
  9352. }
  9353. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9354. const origBadge = origDef === 'always'
  9355. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 font-bold border border-amber-500/30">always</span>'
  9356. : (origDef === 'if-installed'
  9357. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 font-bold border border-sky-500/30">if-installed</span>'
  9358. : '<span class="text-slate-500 text-[10px]">never</span>');
  9359. const filterBadges = [];
  9360. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  9361. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  9362. return `
  9363. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9364. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9365. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  9366. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9367. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9368. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9369. ${filterBadges.join(' ')}
  9370. </td>
  9371. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9372. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9373. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9374. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9375. <td class="py-1.5 px-3">${origBadge}</td>
  9376. </tr>
  9377. `;
  9378. }).join('');
  9379. }
  9380. // TAB 2: AREAS
  9381. function renderOspfAreas() {
  9382. const tbody = document.getElementById('ospf-areas-table-body');
  9383. if (!tbody) return;
  9384. const countEl = document.getElementById('ospf-areas-footer-count');
  9385. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9386. let list = state.ospfAreas || [];
  9387. if (filter) {
  9388. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9389. }
  9390. if (countEl) countEl.innerText = list.length;
  9391. const selId = state.selectedOspfRow?.areas;
  9392. tbody.innerHTML = list.map((a, idx) => {
  9393. const isSel = a.id === selId;
  9394. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9395. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9396. return `
  9397. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9398. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9399. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9400. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9401. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9402. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9403. </td>
  9404. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9405. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9406. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9407. </tr>
  9408. `;
  9409. }).join('');
  9410. }
  9411. // TAB 3: AREA RANGES
  9412. function renderOspfAreaRanges() {
  9413. const tbody = document.getElementById('ospf-ranges-table-body');
  9414. if (!tbody) return;
  9415. const countEl = document.getElementById('ospf-ranges-footer-count');
  9416. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9417. let list = state.ospfAreaRanges || [];
  9418. if (filter) {
  9419. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9420. }
  9421. if (countEl) countEl.innerText = list.length;
  9422. const selId = state.selectedOspfRow?.['area-ranges'];
  9423. tbody.innerHTML = list.map((r, idx) => {
  9424. const isSel = r.id === selId;
  9425. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9426. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9427. return `
  9428. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9429. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9430. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9431. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9432. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9433. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9434. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9435. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9436. </tr>
  9437. `;
  9438. }).join('');
  9439. }
  9440. // TAB 4: INTERFACE TEMPLATES
  9441. function renderOspfTemplates() {
  9442. const tbody = document.getElementById('ospf-templates-table-body');
  9443. if (!tbody) return;
  9444. const countEl = document.getElementById('ospf-templates-footer-count');
  9445. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9446. let list = state.ospfTemplates || [];
  9447. if (filter) {
  9448. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9449. }
  9450. if (countEl) countEl.innerText = list.length;
  9451. const selId = state.selectedOspfRow?.templates;
  9452. tbody.innerHTML = list.map((t, idx) => {
  9453. const isSel = t.id === selId;
  9454. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9455. const ifaces = t.interfaces || t.interface || 'all';
  9456. const nets = t.networks || t.network || '';
  9457. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9458. return `
  9459. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9460. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9461. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9462. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9463. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9464. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9465. </td>
  9466. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9467. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9468. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9469. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9470. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9471. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9472. </tr>
  9473. `;
  9474. }).join('');
  9475. }
  9476. // TAB 5: LIVE INTERFACES
  9477. function renderOspfLiveInterfaces() {
  9478. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9479. if (!tbody) return;
  9480. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9481. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9482. let list = state.ospfLiveInterfaces || [];
  9483. if (filter) {
  9484. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9485. }
  9486. if (countEl) countEl.innerText = list.length;
  9487. tbody.innerHTML = list.map(i => `
  9488. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9489. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9490. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9491. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9492. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9493. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9494. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9495. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9496. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9497. </tr>
  9498. `).join('');
  9499. }
  9500. // TAB 6: STATIC NEIGHBORS
  9501. function renderOspfStaticNbrs() {
  9502. const tbody = document.getElementById('ospf-snbrs-table-body');
  9503. if (!tbody) return;
  9504. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9505. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9506. let list = state.ospfStaticNbrs || [];
  9507. if (filter) {
  9508. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9509. }
  9510. if (countEl) countEl.innerText = list.length;
  9511. const selId = state.selectedOspfRow?.['static-nbrs'];
  9512. tbody.innerHTML = list.map((n, idx) => {
  9513. const isSel = n.id === selId;
  9514. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9515. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9516. return `
  9517. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9518. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9519. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9520. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9521. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9522. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9523. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9524. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9525. </tr>
  9526. `;
  9527. }).join('');
  9528. }
  9529. // TAB 7: LIVE NEIGHBORS
  9530. function renderOspfNeighbors() {
  9531. const tbody = document.getElementById('ospf-neighbors-table-body');
  9532. if (!tbody) return;
  9533. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9534. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9535. let list = state.ospfNeighbors || [];
  9536. if (filter) {
  9537. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9538. }
  9539. if (countEl) countEl.innerText = list.length;
  9540. tbody.innerHTML = list.map(n => `
  9541. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9542. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9543. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9544. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9545. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9546. </td>
  9547. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9548. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9549. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9550. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9551. </tr>
  9552. `).join('');
  9553. }
  9554. // TAB 8: LINK-STATE DATABASE (LSA)
  9555. function renderOspfLSA() {
  9556. const tbody = document.getElementById('ospf-lsa-table-body');
  9557. if (!tbody) return;
  9558. const countEl = document.getElementById('ospf-lsa-footer-count');
  9559. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9560. let list = state.ospfLSA || [];
  9561. if (filter) {
  9562. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9563. }
  9564. if (countEl) countEl.innerText = list.length;
  9565. tbody.innerHTML = list.map(l => `
  9566. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9567. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9568. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9569. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9570. </td>
  9571. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9572. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9573. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9574. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9575. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9576. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9577. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9578. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9579. </tr>
  9580. `).join('');
  9581. }
  9582. function renderOspfStatusPill() {
  9583. // Maintained for backward compatibility
  9584. const pill = document.getElementById('ospf-live-status-pill');
  9585. if (!pill) return;
  9586. 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';
  9587. pill.innerText = 'OSPF ACTIVE';
  9588. }
  9589. function renderOspfInterfaces() {
  9590. renderOspfTemplates();
  9591. }
  9592. function renderOspfRoutes() {
  9593. // Routes retained in background
  9594. }
  9595. // BGP Modals & Actions
  9596. function openBgpInstanceModal() {
  9597. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9598. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9599. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9600. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9601. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9602. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9603. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9604. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9605. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9606. document.getElementById('modal-bgp-in-filter').value = inst.in_filter || '';
  9607. document.getElementById('modal-bgp-out-filter').value = inst.out_filter || '';
  9608. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9609. }
  9610. function closeBgpInstanceModal() {
  9611. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9612. }
  9613. async function submitBgpInstance(e) {
  9614. e.preventDefault();
  9615. const payload = {
  9616. enabled: document.getElementById('modal-bgp-enabled').checked,
  9617. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9618. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9619. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9620. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9621. in_filter: (document.getElementById('modal-bgp-in-filter')?.value || '').trim(),
  9622. out_filter: (document.getElementById('modal-bgp-out-filter')?.value || '').trim(),
  9623. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9624. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9625. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9626. };
  9627. try {
  9628. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9629. method: 'POST',
  9630. headers: { 'Content-Type': 'application/json' },
  9631. body: JSON.stringify(payload)
  9632. });
  9633. if (res.ok) {
  9634. closeBgpInstanceModal();
  9635. showToast('Success', 'BGP instance configuration updated', 'success');
  9636. loadDynamicRouting();
  9637. } else {
  9638. const err = await res.json();
  9639. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9640. }
  9641. } catch (err) {
  9642. showToast('Error', err.message, 'error');
  9643. }
  9644. }
  9645. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9646. function switchBgpPeerModalTab(tab) {
  9647. // Normalize legacy tab names
  9648. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9649. if (tab === 'attributes') tab = 'networks';
  9650. const tabs = ['general', 'filters', 'networks'];
  9651. tabs.forEach(t => {
  9652. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9653. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9654. if (t === tab) {
  9655. if (pane) pane.classList.remove('hidden');
  9656. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9657. } else {
  9658. if (pane) pane.classList.add('hidden');
  9659. 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';
  9660. }
  9661. });
  9662. }
  9663. function addOutputNetworkRow(val = '') {
  9664. const container = document.getElementById('modal-bgp-output-networks-container');
  9665. if (!container) return;
  9666. const row = document.createElement('div');
  9667. row.className = 'flex items-center gap-2 output-net-row';
  9668. row.innerHTML = `
  9669. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.100.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">
  9670. <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>
  9671. `;
  9672. container.appendChild(row);
  9673. }
  9674. function parseBgpTime(val) {
  9675. if (!val) return 0;
  9676. val = String(val).trim();
  9677. if (val.includes(':')) {
  9678. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9679. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9680. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9681. }
  9682. return parseInt(val, 10) || 0;
  9683. }
  9684. function formatBgpTime(secs) {
  9685. if (!secs || secs <= 0) return '30';
  9686. return String(secs);
  9687. }
  9688. function populateBgpRoutingTables() {
  9689. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9690. if (!sel) return;
  9691. const cur = sel.value || 'main';
  9692. sel.innerHTML = '<option value="main">main</option>';
  9693. (state.routingTables || []).forEach(t => {
  9694. if (t.name !== 'main') {
  9695. const opt = document.createElement('option');
  9696. opt.value = t.name;
  9697. opt.innerText = t.name;
  9698. sel.appendChild(opt);
  9699. }
  9700. });
  9701. sel.value = cur;
  9702. }
  9703. function populateBgpLocalAddrDatalist() {
  9704. const dlBgp = document.getElementById('bgp-peer-local-addr-datalist');
  9705. if (!dlBgp) return;
  9706. const addrs = [];
  9707. (state.interfaces || []).forEach(iface => {
  9708. if (iface.ip) addrs.push(iface.ip.split('/')[0]);
  9709. (iface.addresses || []).forEach(a => addrs.push(a.split('/')[0]));
  9710. });
  9711. dlBgp.innerHTML = Array.from(new Set(addrs.filter(Boolean))).map(ip => `<option value="${escapeHtml(ip)}">`).join('');
  9712. }
  9713. function openAddBgpPeerModal() {
  9714. document.getElementById('bgp-peer-form').reset();
  9715. document.getElementById('modal-bgp-peer-id').value = '';
  9716. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9717. populateBgpLocalAddrDatalist();
  9718. // General Tab
  9719. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9720. document.getElementById('modal-bgp-peer-name').value = '';
  9721. document.getElementById('modal-bgp-peer-comment').value = '';
  9722. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9723. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9724. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9725. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9726. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9727. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9728. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9729. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9730. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9731. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9732. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9733. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9734. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9735. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9736. // Filters Tab
  9737. populateFilterChainsDatalist();
  9738. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9739. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9740. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9741. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9742. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9743. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9744. // Advertised Networks Tab
  9745. const container = document.getElementById('modal-bgp-output-networks-container');
  9746. if (container) {
  9747. container.innerHTML = '';
  9748. addOutputNetworkRow('');
  9749. }
  9750. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9751. if (removeBtn) removeBtn.classList.add('hidden');
  9752. switchBgpPeerModalTab('general');
  9753. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9754. }
  9755. function populateFilterChainsDatalist() {
  9756. const dl = document.getElementById('filter-chains-list');
  9757. if (!dl) return;
  9758. const chains = new Set();
  9759. (state.routingFilters || []).forEach(f => {
  9760. if (f.chain) chains.add(f.chain);
  9761. });
  9762. if (chains.size === 0) {
  9763. chains.add('awmn');
  9764. chains.add('Internal');
  9765. chains.add('bgp-in');
  9766. chains.add('bgp-out');
  9767. }
  9768. dl.innerHTML = '';
  9769. chains.forEach(c => {
  9770. const opt = document.createElement('option');
  9771. opt.value = c;
  9772. dl.appendChild(opt);
  9773. });
  9774. }
  9775. function openEditBgpPeerModal(id) {
  9776. const p = (state.bgpPeers || []).find(item => item.id === id);
  9777. if (!p) return;
  9778. populateFilterChainsDatalist();
  9779. populateBgpLocalAddrDatalist();
  9780. document.getElementById('modal-bgp-peer-id').value = p.id;
  9781. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9782. // General Tab
  9783. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9784. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9785. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9786. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9787. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9788. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9789. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9790. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9791. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9792. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9793. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9794. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9795. // Passive mode
  9796. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9797. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9798. // Next-hop self
  9799. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9800. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9801. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9802. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9803. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9804. // Filters Tab
  9805. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9806. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9807. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9808. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9809. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9810. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9811. // Advertised Networks Tab
  9812. const container = document.getElementById('modal-bgp-output-networks-container');
  9813. if (container) {
  9814. container.innerHTML = '';
  9815. if (p.output_networks && p.output_networks.length > 0) {
  9816. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9817. } else {
  9818. addOutputNetworkRow('');
  9819. }
  9820. }
  9821. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9822. if (removeBtn) removeBtn.classList.remove('hidden');
  9823. switchBgpPeerModalTab('general');
  9824. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9825. }
  9826. function copyCurrentBgpPeer() {
  9827. document.getElementById('modal-bgp-peer-id').value = '';
  9828. const nameEl = document.getElementById('modal-bgp-peer-name');
  9829. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9830. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9831. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9832. if (removeBtn) removeBtn.classList.add('hidden');
  9833. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9834. }
  9835. function removeCurrentBgpPeer() {
  9836. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9837. if (!id) return;
  9838. deleteBgpPeer(id);
  9839. closeBgpPeerModal();
  9840. }
  9841. function closeBgpPeerModal() {
  9842. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9843. }
  9844. function getBgpPeerFormData() {
  9845. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9846. const outputNetworks = [];
  9847. netInputs.forEach(inp => {
  9848. const v = inp.value.trim();
  9849. if (v) outputNetworks.push(v);
  9850. });
  9851. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9852. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9853. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9854. const useBfd = document.getElementById('modal-bgp-peer-use-bfd')?.checked || false;
  9855. return {
  9856. id: document.getElementById('modal-bgp-peer-id').value,
  9857. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9858. enabled: enabled,
  9859. disabled: !enabled,
  9860. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9861. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9862. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9863. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9864. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9865. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9866. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9867. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9868. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9869. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9870. use_bfd: useBfd,
  9871. passive: isPassive,
  9872. connect: !isPassive,
  9873. listen: true,
  9874. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9875. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9876. nexthop_self: isNexthopSelf,
  9877. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9878. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9879. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9880. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9881. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9882. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9883. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9884. output_networks: outputNetworks
  9885. };
  9886. }
  9887. async function submitBgpPeer(e) {
  9888. if (e) e.preventDefault();
  9889. const payload = getBgpPeerFormData();
  9890. try {
  9891. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9892. method: 'POST',
  9893. headers: { 'Content-Type': 'application/json' },
  9894. body: JSON.stringify(payload)
  9895. });
  9896. if (res.ok) {
  9897. closeBgpPeerModal();
  9898. showToast('Success', 'BGP Connection saved', 'success');
  9899. loadDynamicRouting();
  9900. } else {
  9901. const err = await res.json();
  9902. showToast('Error', err.error || 'Failed to save peer', 'error');
  9903. }
  9904. } catch (err) {
  9905. showToast('Error', err.message, 'error');
  9906. }
  9907. }
  9908. async function applyBgpPeerModal(e) {
  9909. if (e) e.preventDefault();
  9910. const payload = getBgpPeerFormData();
  9911. try {
  9912. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9913. method: 'POST',
  9914. headers: { 'Content-Type': 'application/json' },
  9915. body: JSON.stringify(payload)
  9916. });
  9917. if (res.ok) {
  9918. const data = await res.json();
  9919. if (data.peer && data.peer.id) {
  9920. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9921. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9922. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9923. }
  9924. showToast('Applied', 'BGP Connection applied', 'success');
  9925. loadDynamicRouting();
  9926. } else {
  9927. const err = await res.json();
  9928. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9929. }
  9930. } catch (err) {
  9931. showToast('Error', err.message, 'error');
  9932. }
  9933. }
  9934. async function deleteBgpPeer(id) {
  9935. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9936. try {
  9937. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9938. if (res.ok) {
  9939. showToast('Deleted', 'BGP peer removed', 'success');
  9940. loadDynamicRouting();
  9941. }
  9942. } catch (err) {
  9943. showToast('Error', err.message, 'error');
  9944. }
  9945. }
  9946. async function toggleBgpPeerState(id, disabled) {
  9947. try {
  9948. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9949. method: 'POST',
  9950. headers: { 'Content-Type': 'application/json' },
  9951. body: JSON.stringify({ disabled })
  9952. });
  9953. if (res.ok) {
  9954. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9955. loadDynamicRouting();
  9956. }
  9957. } catch (err) {
  9958. showToast('Error', err.message, 'error');
  9959. }
  9960. }
  9961. function openAddBgpNetworkModal() {
  9962. document.getElementById('bgp-network-form').reset();
  9963. document.getElementById('modal-bgp-net-id').value = '';
  9964. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9965. }
  9966. function closeBgpNetworkModal() {
  9967. document.getElementById('bgp-network-modal').classList.add('hidden');
  9968. }
  9969. async function submitBgpNetwork(e) {
  9970. e.preventDefault();
  9971. const payload = {
  9972. id: document.getElementById('modal-bgp-net-id').value,
  9973. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9974. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9975. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9976. };
  9977. try {
  9978. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9979. method: 'POST',
  9980. headers: { 'Content-Type': 'application/json' },
  9981. body: JSON.stringify(payload)
  9982. });
  9983. if (res.ok) {
  9984. closeBgpNetworkModal();
  9985. showToast('Success', 'BGP network advertisement saved', 'success');
  9986. loadDynamicRouting();
  9987. } else {
  9988. const err = await res.json();
  9989. showToast('Error', err.error || 'Failed to save network', 'error');
  9990. }
  9991. } catch (err) {
  9992. showToast('Error', err.message, 'error');
  9993. }
  9994. }
  9995. async function deleteBgpNetwork(id) {
  9996. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9997. try {
  9998. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9999. if (res.ok) {
  10000. showToast('Deleted', 'Network advertisement removed', 'success');
  10001. loadDynamicRouting();
  10002. }
  10003. } catch (err) {
  10004. showToast('Error', err.message, 'error');
  10005. }
  10006. }
  10007. // =========================================================================
  10008. // DEBTIK v7 OSPF MODALS & ACTIONS
  10009. // =========================================================================
  10010. // --- 1. OSPF INSTANCE ---
  10011. function openOspfInstanceModal(id = null) {
  10012. const isEdit = !!id;
  10013. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  10014. id: '',
  10015. name: 'Default',
  10016. version: 2,
  10017. vrf: 'main',
  10018. router_id: '192.168.131.56',
  10019. routing_table: 'main',
  10020. enabled: true,
  10021. redistribute_connected: false,
  10022. redistribute_static: true,
  10023. redistribute_bgp: false,
  10024. comment: ''
  10025. };
  10026. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  10027. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  10028. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  10029. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  10030. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  10031. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  10032. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  10033. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  10034. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  10035. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  10036. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  10037. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  10038. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  10039. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  10040. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  10041. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  10042. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  10043. document.getElementById('modal-ospf-inst-in-filter').value = inst.in_filter || '';
  10044. document.getElementById('modal-ospf-inst-out-filter').value = inst.out_filter || '';
  10045. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  10046. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10047. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  10048. }
  10049. function toggleOspfDefaultModeUI() {
  10050. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  10051. const select = document.getElementById('modal-ospf-inst-originate-default');
  10052. if (!select) return;
  10053. if (isChecked) {
  10054. if (select.value === 'never') select.value = 'if-installed';
  10055. } else {
  10056. select.value = 'never';
  10057. }
  10058. }
  10059. function onOspfOriginateDefaultChange() {
  10060. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  10061. const chk = document.getElementById('modal-ospf-inst-redist-default');
  10062. if (chk) chk.checked = val !== 'never';
  10063. }
  10064. function openEditOspfInstanceModal(id) {
  10065. openOspfInstanceModal(id);
  10066. }
  10067. function closeOspfInstanceModal() {
  10068. document.getElementById('ospf-instance-modal').classList.add('hidden');
  10069. }
  10070. async function submitOspfInstance(e) {
  10071. if (e) e.preventDefault();
  10072. const payload = {
  10073. id: document.getElementById('modal-ospf-inst-id').value,
  10074. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  10075. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  10076. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  10077. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  10078. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10079. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10080. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10081. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10082. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10083. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10084. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10085. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10086. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10087. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0,
  10088. in_filter: (document.getElementById('modal-ospf-inst-in-filter')?.value || '').trim(),
  10089. out_filter: (document.getElementById('modal-ospf-inst-out-filter')?.value || '').trim()
  10090. };
  10091. try {
  10092. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10093. method: 'POST',
  10094. headers: { 'Content-Type': 'application/json' },
  10095. body: JSON.stringify(payload)
  10096. });
  10097. if (res.ok) {
  10098. closeOspfInstanceModal();
  10099. showToast('Saved', 'OSPF instance updated', 'success');
  10100. loadDynamicRouting();
  10101. } else {
  10102. const err = await res.json();
  10103. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10104. }
  10105. } catch (err) {
  10106. showToast('Error', err.message, 'error');
  10107. }
  10108. }
  10109. function applyOspfInstanceForm() {
  10110. submitOspfInstance(null);
  10111. }
  10112. function copyOspfInstance() {
  10113. document.getElementById('modal-ospf-inst-id').value = '';
  10114. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10115. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10116. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10117. }
  10118. async function deleteCurrentOspfInstance() {
  10119. const id = document.getElementById('modal-ospf-inst-id').value;
  10120. if (!id) return;
  10121. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10122. try {
  10123. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10124. if (res.ok) {
  10125. closeOspfInstanceModal();
  10126. showToast('Removed', 'OSPF instance deleted', 'success');
  10127. loadDynamicRouting();
  10128. }
  10129. } catch (err) {
  10130. showToast('Error', err.message, 'error');
  10131. }
  10132. }
  10133. async function enableSelectedOspfInstance() {
  10134. const id = state.selectedOspfRow?.instances;
  10135. if (!id) return;
  10136. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10137. method: 'POST',
  10138. headers: { 'Content-Type': 'application/json' },
  10139. body: JSON.stringify({ disabled: false })
  10140. });
  10141. loadDynamicRouting();
  10142. }
  10143. async function disableSelectedOspfInstance() {
  10144. const id = state.selectedOspfRow?.instances;
  10145. if (!id) return;
  10146. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10147. method: 'POST',
  10148. headers: { 'Content-Type': 'application/json' },
  10149. body: JSON.stringify({ disabled: true })
  10150. });
  10151. loadDynamicRouting();
  10152. }
  10153. async function removeSelectedOspfInstance() {
  10154. const id = state.selectedOspfRow?.instances;
  10155. if (!id) return;
  10156. if (!confirm('Delete selected OSPF instance?')) return;
  10157. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10158. loadDynamicRouting();
  10159. }
  10160. async function promptCommentOspfInstance() {
  10161. const id = state.selectedOspfRow?.instances;
  10162. if (!id) return;
  10163. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10164. if (!inst) return;
  10165. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10166. if (comment === null) return;
  10167. inst.comment = comment;
  10168. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10169. method: 'POST',
  10170. headers: { 'Content-Type': 'application/json' },
  10171. body: JSON.stringify(inst)
  10172. });
  10173. loadDynamicRouting();
  10174. }
  10175. // --- 2. OSPF AREA ---
  10176. function populateOspfAreaDropdowns() {
  10177. const instSelect = document.getElementById('modal-ospf-area-instance');
  10178. if (instSelect) {
  10179. const cur = instSelect.value;
  10180. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10181. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10182. if (cur) instSelect.value = cur;
  10183. }
  10184. }
  10185. function openOspfAreaModal(id = null) {
  10186. const isEdit = !!id;
  10187. populateOspfAreaDropdowns();
  10188. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10189. id: '',
  10190. name: 'Default',
  10191. instance: 'Default',
  10192. area_id: '0.0.0.0',
  10193. area_type: 'default',
  10194. default_cost: 1,
  10195. no_summaries: false,
  10196. disabled: false,
  10197. comment: ''
  10198. };
  10199. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10200. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10201. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10202. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10203. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10204. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10205. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10206. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10207. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10208. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10209. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10210. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10211. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10212. }
  10213. function openEditOspfAreaModal(id) {
  10214. openOspfAreaModal(id);
  10215. }
  10216. function closeOspfAreaModal() {
  10217. document.getElementById('ospf-area-modal').classList.add('hidden');
  10218. }
  10219. async function submitOspfArea(e) {
  10220. if (e) e.preventDefault();
  10221. const payload = {
  10222. id: document.getElementById('modal-ospf-area-id').value,
  10223. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10224. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10225. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10226. area_type: document.getElementById('modal-ospf-area-type').value,
  10227. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10228. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10229. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10230. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10231. };
  10232. try {
  10233. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10234. method: 'POST',
  10235. headers: { 'Content-Type': 'application/json' },
  10236. body: JSON.stringify(payload)
  10237. });
  10238. if (res.ok) {
  10239. closeOspfAreaModal();
  10240. showToast('Saved', 'OSPF area saved', 'success');
  10241. loadDynamicRouting();
  10242. } else {
  10243. const err = await res.json();
  10244. showToast('Error', err.error || 'Failed to save area', 'error');
  10245. }
  10246. } catch (err) {
  10247. showToast('Error', err.message, 'error');
  10248. }
  10249. }
  10250. function applyOspfAreaForm() {
  10251. submitOspfArea(null);
  10252. }
  10253. function copyOspfArea() {
  10254. document.getElementById('modal-ospf-area-id').value = '';
  10255. document.getElementById('modal-ospf-area-name').value += '-copy';
  10256. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10257. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10258. }
  10259. async function deleteCurrentOspfArea() {
  10260. const id = document.getElementById('modal-ospf-area-id').value;
  10261. if (!id) return;
  10262. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10263. try {
  10264. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10265. if (res.ok) {
  10266. closeOspfAreaModal();
  10267. showToast('Removed', 'OSPF area deleted', 'success');
  10268. loadDynamicRouting();
  10269. }
  10270. } catch (err) {
  10271. showToast('Error', err.message, 'error');
  10272. }
  10273. }
  10274. async function enableSelectedOspfArea() {
  10275. const id = state.selectedOspfRow?.areas;
  10276. if (!id) return;
  10277. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10278. method: 'POST',
  10279. headers: { 'Content-Type': 'application/json' },
  10280. body: JSON.stringify({ disabled: false })
  10281. });
  10282. loadDynamicRouting();
  10283. }
  10284. async function disableSelectedOspfArea() {
  10285. const id = state.selectedOspfRow?.areas;
  10286. if (!id) return;
  10287. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10288. method: 'POST',
  10289. headers: { 'Content-Type': 'application/json' },
  10290. body: JSON.stringify({ disabled: true })
  10291. });
  10292. loadDynamicRouting();
  10293. }
  10294. async function removeSelectedOspfArea() {
  10295. const id = state.selectedOspfRow?.areas;
  10296. if (!id) return;
  10297. if (!confirm('Delete selected OSPF area?')) return;
  10298. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10299. loadDynamicRouting();
  10300. }
  10301. async function promptCommentOspfArea() {
  10302. const id = state.selectedOspfRow?.areas;
  10303. if (!id) return;
  10304. const area = (state.ospfAreas || []).find(a => a.id === id);
  10305. if (!area) return;
  10306. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10307. if (comment === null) return;
  10308. area.comment = comment;
  10309. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10310. method: 'POST',
  10311. headers: { 'Content-Type': 'application/json' },
  10312. body: JSON.stringify(area)
  10313. });
  10314. loadDynamicRouting();
  10315. }
  10316. // --- 3. OSPF AREA RANGE ---
  10317. function populateAreaRangeDropdowns() {
  10318. const select = document.getElementById('modal-ospf-range-area');
  10319. if (select) {
  10320. const cur = select.value;
  10321. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10322. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10323. if (cur) select.value = cur;
  10324. }
  10325. }
  10326. function openOspfAreaRangeModal(id = null) {
  10327. const isEdit = !!id;
  10328. populateAreaRangeDropdowns();
  10329. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10330. id: '',
  10331. area: 'Default',
  10332. prefix: '',
  10333. cost: 1,
  10334. advertise: true,
  10335. disabled: false,
  10336. comment: ''
  10337. };
  10338. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10339. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10340. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10341. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10342. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10343. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10344. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10345. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10346. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10347. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10348. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10349. }
  10350. function openEditOspfAreaRangeModal(id) {
  10351. openOspfAreaRangeModal(id);
  10352. }
  10353. function closeOspfAreaRangeModal() {
  10354. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10355. }
  10356. async function submitOspfAreaRange(e) {
  10357. if (e) e.preventDefault();
  10358. const payload = {
  10359. id: document.getElementById('modal-ospf-range-id').value,
  10360. area: document.getElementById('modal-ospf-range-area').value,
  10361. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10362. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10363. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10364. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10365. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10366. };
  10367. try {
  10368. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10369. method: 'POST',
  10370. headers: { 'Content-Type': 'application/json' },
  10371. body: JSON.stringify(payload)
  10372. });
  10373. if (res.ok) {
  10374. closeOspfAreaRangeModal();
  10375. showToast('Saved', 'Area range saved', 'success');
  10376. loadDynamicRouting();
  10377. } else {
  10378. const err = await res.json();
  10379. showToast('Error', err.error || 'Failed to save area range', 'error');
  10380. }
  10381. } catch (err) {
  10382. showToast('Error', err.message, 'error');
  10383. }
  10384. }
  10385. function applyOspfAreaRangeForm() {
  10386. submitOspfAreaRange(null);
  10387. }
  10388. async function deleteCurrentOspfAreaRange() {
  10389. const id = document.getElementById('modal-ospf-range-id').value;
  10390. if (!id) return;
  10391. if (!confirm('Delete this area range?')) return;
  10392. try {
  10393. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10394. closeOspfAreaRangeModal();
  10395. showToast('Removed', 'Area range removed', 'success');
  10396. loadDynamicRouting();
  10397. } catch (err) {
  10398. showToast('Error', err.message, 'error');
  10399. }
  10400. }
  10401. async function enableSelectedOspfAreaRange() {
  10402. const id = state.selectedOspfRow?.['area-ranges'];
  10403. if (!id) return;
  10404. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10405. if (!r) return;
  10406. r.disabled = false;
  10407. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10408. loadDynamicRouting();
  10409. }
  10410. async function disableSelectedOspfAreaRange() {
  10411. const id = state.selectedOspfRow?.['area-ranges'];
  10412. if (!id) return;
  10413. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10414. if (!r) return;
  10415. r.disabled = true;
  10416. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10417. loadDynamicRouting();
  10418. }
  10419. async function removeSelectedOspfAreaRange() {
  10420. const id = state.selectedOspfRow?.['area-ranges'];
  10421. if (!id) return;
  10422. if (!confirm('Delete selected area range?')) return;
  10423. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10424. loadDynamicRouting();
  10425. }
  10426. async function promptCommentOspfAreaRange() {
  10427. const id = state.selectedOspfRow?.['area-ranges'];
  10428. if (!id) return;
  10429. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10430. if (!r) return;
  10431. const comment = prompt('Enter comment for area range:', r.comment || '');
  10432. if (comment === null) return;
  10433. r.comment = comment;
  10434. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10435. loadDynamicRouting();
  10436. }
  10437. // --- 4. OSPF INTERFACE TEMPLATE ---
  10438. function switchOspfTemplateTab(tab) {
  10439. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10440. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10441. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10442. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10443. if (tab === 'general') {
  10444. if (tabGen) tabGen.classList.remove('hidden');
  10445. if (tabAuth) tabAuth.classList.add('hidden');
  10446. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10447. 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';
  10448. } else {
  10449. if (tabGen) tabGen.classList.add('hidden');
  10450. if (tabAuth) tabAuth.classList.remove('hidden');
  10451. 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';
  10452. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10453. }
  10454. }
  10455. function populateTemplateAreaDropdowns() {
  10456. const select = document.getElementById('modal-ospf-tmpl-area');
  10457. if (select) {
  10458. const cur = select.value;
  10459. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10460. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10461. if (cur) select.value = cur;
  10462. }
  10463. }
  10464. function openOspfTemplateModal(id = null) {
  10465. const isEdit = !!id;
  10466. populateTemplateAreaDropdowns();
  10467. switchOspfTemplateTab('general');
  10468. const dl = document.getElementById('ospf-tmpl-iface-datalist');
  10469. if (dl) {
  10470. dl.innerHTML = '<option value="*"><option value="all">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  10471. }
  10472. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10473. id: '',
  10474. interfaces: '',
  10475. area: 'Default',
  10476. networks: '',
  10477. network_type: 'broadcast',
  10478. cost: 1,
  10479. priority: 128,
  10480. passive: false,
  10481. hello_interval: 10,
  10482. dead_interval: 40,
  10483. auth: 'none',
  10484. auth_key: '',
  10485. disabled: false,
  10486. comment: ''
  10487. };
  10488. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10489. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10490. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10491. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10492. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10493. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10494. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10495. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10496. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10497. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10498. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10499. if (document.getElementById('modal-ospf-tmpl-bfd')) document.getElementById('modal-ospf-tmpl-bfd').checked = !!tmpl.use_bfd;
  10500. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10501. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10502. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10503. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10504. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10505. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10506. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10507. }
  10508. function openEditOspfTemplateModal(id) {
  10509. openOspfTemplateModal(id);
  10510. }
  10511. function closeOspfTemplateModal() {
  10512. document.getElementById('ospf-template-modal').classList.add('hidden');
  10513. }
  10514. async function submitOspfTemplate(e) {
  10515. if (e) e.preventDefault();
  10516. const payload = {
  10517. id: document.getElementById('modal-ospf-tmpl-id').value,
  10518. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10519. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10520. area: document.getElementById('modal-ospf-tmpl-area').value,
  10521. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10522. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10523. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10524. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10525. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10526. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10527. use_bfd: document.getElementById('modal-ospf-tmpl-bfd')?.checked || false,
  10528. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10529. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10530. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10531. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10532. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10533. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10534. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10535. };
  10536. try {
  10537. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10538. method: 'POST',
  10539. headers: { 'Content-Type': 'application/json' },
  10540. body: JSON.stringify(payload)
  10541. });
  10542. if (res.ok) {
  10543. closeOspfTemplateModal();
  10544. showToast('Saved', 'Interface template saved', 'success');
  10545. loadDynamicRouting();
  10546. } else {
  10547. const err = await res.json();
  10548. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10549. }
  10550. } catch (err) {
  10551. showToast('Error', err.message, 'error');
  10552. }
  10553. }
  10554. function applyOspfTemplateForm() {
  10555. submitOspfTemplate(null);
  10556. }
  10557. function copyOspfTemplate() {
  10558. document.getElementById('modal-ospf-tmpl-id').value = '';
  10559. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10560. showToast('Copied', 'Duplicated as new template', 'info');
  10561. }
  10562. async function deleteCurrentOspfTemplate() {
  10563. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10564. if (!id) return;
  10565. if (!confirm('Delete this interface template?')) return;
  10566. try {
  10567. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10568. closeOspfTemplateModal();
  10569. showToast('Removed', 'Interface template deleted', 'success');
  10570. loadDynamicRouting();
  10571. } catch (err) {
  10572. showToast('Error', err.message, 'error');
  10573. }
  10574. }
  10575. async function enableSelectedOspfTemplate() {
  10576. const id = state.selectedOspfRow?.templates;
  10577. if (!id) return;
  10578. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10579. method: 'POST',
  10580. headers: { 'Content-Type': 'application/json' },
  10581. body: JSON.stringify({ disabled: false })
  10582. });
  10583. loadDynamicRouting();
  10584. }
  10585. async function disableSelectedOspfTemplate() {
  10586. const id = state.selectedOspfRow?.templates;
  10587. if (!id) return;
  10588. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10589. method: 'POST',
  10590. headers: { 'Content-Type': 'application/json' },
  10591. body: JSON.stringify({ disabled: true })
  10592. });
  10593. loadDynamicRouting();
  10594. }
  10595. async function removeSelectedOspfTemplate() {
  10596. const id = state.selectedOspfRow?.templates;
  10597. if (!id) return;
  10598. if (!confirm('Delete selected interface template?')) return;
  10599. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10600. loadDynamicRouting();
  10601. }
  10602. async function promptCommentOspfTemplate() {
  10603. const id = state.selectedOspfRow?.templates;
  10604. if (!id) return;
  10605. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10606. if (!tmpl) return;
  10607. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10608. if (comment === null) return;
  10609. tmpl.comment = comment;
  10610. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10611. method: 'POST',
  10612. headers: { 'Content-Type': 'application/json' },
  10613. body: JSON.stringify(tmpl)
  10614. });
  10615. loadDynamicRouting();
  10616. }
  10617. // --- 5. OSPF STATIC NEIGHBOR ---
  10618. function populateStaticNbrAreaDropdowns() {
  10619. const select = document.getElementById('modal-ospf-snbr-area');
  10620. if (select) {
  10621. const cur = select.value;
  10622. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10623. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10624. if (cur) select.value = cur;
  10625. }
  10626. }
  10627. function openOspfStaticNbrModal(id = null) {
  10628. const isEdit = !!id;
  10629. populateStaticNbrAreaDropdowns();
  10630. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10631. id: '',
  10632. address: '',
  10633. area: 'Default',
  10634. poll_interval: 120,
  10635. cost: 1,
  10636. disabled: false,
  10637. comment: ''
  10638. };
  10639. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10640. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10641. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10642. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10643. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10644. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10645. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10646. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10647. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10648. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10649. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10650. }
  10651. function openEditOspfStaticNbrModal(id) {
  10652. openOspfStaticNbrModal(id);
  10653. }
  10654. function closeOspfStaticNbrModal() {
  10655. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10656. }
  10657. async function submitOspfStaticNbr(e) {
  10658. if (e) e.preventDefault();
  10659. const payload = {
  10660. id: document.getElementById('modal-ospf-snbr-id').value,
  10661. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10662. area: document.getElementById('modal-ospf-snbr-area').value,
  10663. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10664. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10665. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10666. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10667. };
  10668. try {
  10669. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10670. method: 'POST',
  10671. headers: { 'Content-Type': 'application/json' },
  10672. body: JSON.stringify(payload)
  10673. });
  10674. if (res.ok) {
  10675. closeOspfStaticNbrModal();
  10676. showToast('Saved', 'Static neighbor saved', 'success');
  10677. loadDynamicRouting();
  10678. } else {
  10679. const err = await res.json();
  10680. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10681. }
  10682. } catch (err) {
  10683. showToast('Error', err.message, 'error');
  10684. }
  10685. }
  10686. function applyOspfStaticNbrForm() {
  10687. submitOspfStaticNbr(null);
  10688. }
  10689. async function deleteCurrentOspfStaticNbr() {
  10690. const id = document.getElementById('modal-ospf-snbr-id').value;
  10691. if (!id) return;
  10692. if (!confirm('Delete this static neighbor?')) return;
  10693. try {
  10694. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10695. closeOspfStaticNbrModal();
  10696. showToast('Removed', 'Static neighbor removed', 'success');
  10697. loadDynamicRouting();
  10698. } catch (err) {
  10699. showToast('Error', err.message, 'error');
  10700. }
  10701. }
  10702. async function enableSelectedOspfStaticNbr() {
  10703. const id = state.selectedOspfRow?.['static-nbrs'];
  10704. if (!id) return;
  10705. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10706. loadDynamicRouting();
  10707. }
  10708. async function disableSelectedOspfStaticNbr() {
  10709. const id = state.selectedOspfRow?.['static-nbrs'];
  10710. if (!id) return;
  10711. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10712. loadDynamicRouting();
  10713. }
  10714. async function removeSelectedOspfStaticNbr() {
  10715. const id = state.selectedOspfRow?.['static-nbrs'];
  10716. if (!id) return;
  10717. if (!confirm('Delete selected static neighbor?')) return;
  10718. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10719. loadDynamicRouting();
  10720. }
  10721. async function promptCommentOspfStaticNbr() {
  10722. const id = state.selectedOspfRow?.['static-nbrs'];
  10723. if (!id) return;
  10724. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10725. if (!n) return;
  10726. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10727. if (comment === null) return;
  10728. n.comment = comment;
  10729. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10730. loadDynamicRouting();
  10731. }
  10732. // Backward-compat aliases
  10733. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10734. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10735. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10736. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10737. function deleteOspfInterface(id) {
  10738. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10739. }
  10740. function toggleOspfInterfaceState(id, disabled) {
  10741. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10742. method: 'POST',
  10743. headers: { 'Content-Type': 'application/json' },
  10744. body: JSON.stringify({ disabled })
  10745. }).then(() => loadDynamicRouting());
  10746. }
  10747. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10748. function deleteOspfArea(id) {
  10749. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10750. }
  10751. // ============================================================================
  10752. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10753. // ============================================================================
  10754. function switchBridgeSubTab(tab) {
  10755. state.bridgeSubTab = tab;
  10756. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10757. tabs.forEach(t => {
  10758. const panel = document.getElementById(`bridge-subtab-${t}`);
  10759. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10760. if (panel) {
  10761. if (t === tab) panel.classList.remove('hidden');
  10762. else panel.classList.add('hidden');
  10763. }
  10764. if (btn) {
  10765. if (t === tab) {
  10766. 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';
  10767. } else {
  10768. 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';
  10769. }
  10770. }
  10771. });
  10772. const addBtn = document.getElementById('bridge-top-action-btn');
  10773. if (addBtn) {
  10774. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10775. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10776. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10777. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10778. }
  10779. if (tab === 'hosts') loadBridgeHosts();
  10780. setTimeout(initTableSorting, 50);
  10781. }
  10782. function openCurrentBridgeModal() {
  10783. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10784. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10785. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10786. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10787. }
  10788. async function loadBridge() {
  10789. try {
  10790. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10791. fetch(`${API_BASE}/bridge/bridges`),
  10792. fetch(`${API_BASE}/bridge/ports`),
  10793. fetch(`${API_BASE}/bridge/vlans`),
  10794. fetch(`${API_BASE}/bridge/summary`),
  10795. fetch(`${API_BASE}/vpn/eoip`),
  10796. fetch(`${API_BASE}/vpn/vxlan`),
  10797. fetch(`${API_BASE}/vlans`)
  10798. ]);
  10799. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10800. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10801. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10802. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10803. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10804. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10805. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10806. // Badges & Stats
  10807. const bBridges = document.getElementById('bridge-badge-bridges');
  10808. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10809. const bPorts = document.getElementById('bridge-badge-ports');
  10810. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10811. const bVlans = document.getElementById('bridge-badge-vlans');
  10812. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10813. const bHosts = document.getElementById('bridge-badge-hosts');
  10814. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10815. const sBr = document.getElementById('bridge-stat-bridges');
  10816. if (sBr) sBr.innerText = (state.bridges || []).length;
  10817. const sPorts = document.getElementById('bridge-stat-ports');
  10818. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10819. const sHosts = document.getElementById('bridge-stat-hosts');
  10820. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10821. renderBridges();
  10822. renderBridgePorts();
  10823. renderBridgeVLANs();
  10824. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10825. } catch (err) {
  10826. console.error('Failed to load bridge subsystem:', err);
  10827. }
  10828. }
  10829. // ----------------- Bridges -----------------
  10830. function renderBridges() {
  10831. const tbody = document.getElementById('bridge-table-body');
  10832. const empty = document.getElementById('bridge-empty-bridges');
  10833. const countBadge = document.getElementById('bridge-count-badge');
  10834. if (!tbody) return;
  10835. tbody.innerHTML = '';
  10836. const bridges = state.bridges || [];
  10837. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10838. if (bridges.length === 0) {
  10839. empty?.classList.remove('hidden');
  10840. return;
  10841. }
  10842. empty?.classList.add('hidden');
  10843. bridges.forEach((b, idx) => {
  10844. const tr = document.createElement('tr');
  10845. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10846. // Format IP addresses pill list
  10847. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10848. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10849. ipsHtml = b.ip_addresses.map(ip => `
  10850. <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">
  10851. <span>${ip}</span>
  10852. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10853. </span>
  10854. `).join(' ');
  10855. }
  10856. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10857. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10858. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10859. tr.innerHTML = `
  10860. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10861. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10862. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10863. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10864. </td>
  10865. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10866. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10867. <td class="py-2.5 px-3">
  10868. <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>
  10869. </td>
  10870. <td class="py-2.5 px-3 text-center">
  10871. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10872. </td>
  10873. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10874. <td class="py-2.5 px-3">
  10875. <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>
  10876. </td>
  10877. <td class="py-2.5 px-3">
  10878. <div class="flex items-center gap-1.5 flex-wrap">
  10879. ${ipsHtml}
  10880. <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>
  10881. </div>
  10882. </td>
  10883. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10884. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10885. </td>
  10886. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10887. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10888. <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>
  10889. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10890. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10891. </td>
  10892. `;
  10893. tbody.appendChild(tr);
  10894. });
  10895. }
  10896. function openAddBridgeModal() {
  10897. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10898. document.getElementById('bridge-modal-id').value = '';
  10899. document.getElementById('bridge-modal-name').value = 'bridge1';
  10900. document.getElementById('bridge-modal-name').disabled = false;
  10901. document.getElementById('bridge-modal-mtu').value = '1500';
  10902. document.getElementById('bridge-modal-mac').value = '';
  10903. document.getElementById('bridge-modal-stp').value = 'stp';
  10904. document.getElementById('bridge-modal-priority').value = '32768';
  10905. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10906. document.getElementById('bridge-modal-pvid').value = '1';
  10907. document.getElementById('bridge-modal-fastforward').checked = true;
  10908. document.getElementById('bridge-modal-comment').value = '';
  10909. document.getElementById('bridge-modal-disabled').checked = false;
  10910. toggleBridgeModalVlanFiltering();
  10911. document.getElementById('bridge-modal').classList.remove('hidden');
  10912. }
  10913. function openEditBridgeModal(id) {
  10914. const b = (state.bridges || []).find(x => x.id === id);
  10915. if (!b) return;
  10916. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10917. document.getElementById('bridge-modal-id').value = b.id;
  10918. document.getElementById('bridge-modal-name').value = b.name;
  10919. document.getElementById('bridge-modal-name').disabled = true;
  10920. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10921. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10922. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10923. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10924. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10925. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10926. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10927. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10928. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10929. toggleBridgeModalVlanFiltering();
  10930. document.getElementById('bridge-modal').classList.remove('hidden');
  10931. }
  10932. function closeBridgeModal() {
  10933. document.getElementById('bridge-modal').classList.add('hidden');
  10934. }
  10935. function toggleBridgeModalVlanFiltering() {
  10936. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10937. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10938. if (pvidBox) {
  10939. if (chk) pvidBox.classList.remove('opacity-40');
  10940. else pvidBox.classList.add('opacity-40');
  10941. }
  10942. }
  10943. async function submitSaveBridge(e) {
  10944. e.preventDefault();
  10945. const id = document.getElementById('bridge-modal-id').value;
  10946. const name = document.getElementById('bridge-modal-name').value.trim();
  10947. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10948. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10949. const stp = document.getElementById('bridge-modal-stp').value;
  10950. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10951. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10952. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10953. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10954. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10955. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10956. try {
  10957. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10958. method: 'POST',
  10959. headers: { 'Content-Type': 'application/json' },
  10960. body: JSON.stringify({
  10961. id,
  10962. name,
  10963. mtu,
  10964. mac_address: mac,
  10965. stp,
  10966. priority,
  10967. vlan_filtering: vlanFiltering,
  10968. pvid,
  10969. fast_forward: fastForward,
  10970. comment,
  10971. disabled
  10972. })
  10973. });
  10974. if (res.ok) {
  10975. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10976. closeBridgeModal();
  10977. loadBridge();
  10978. fetchData(false);
  10979. } else {
  10980. const err = await res.json();
  10981. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10982. }
  10983. } catch (err) {
  10984. showToast('Error', err.message, 'error');
  10985. }
  10986. }
  10987. async function toggleBridgeState(id, disabled) {
  10988. try {
  10989. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10990. method: 'POST',
  10991. headers: { 'Content-Type': 'application/json' },
  10992. body: JSON.stringify({ disabled })
  10993. });
  10994. if (res.ok) {
  10995. loadBridge();
  10996. fetchData(false);
  10997. }
  10998. } catch (err) {
  10999. showToast('Error', err.message, 'error');
  11000. }
  11001. }
  11002. async function deleteBridge(id) {
  11003. const b = (state.bridges || []).find(x => x.id === id);
  11004. const name = b ? b.name : id;
  11005. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  11006. try {
  11007. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11008. if (res.ok) {
  11009. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  11010. loadBridge();
  11011. fetchData(false);
  11012. } else {
  11013. const err = await res.json();
  11014. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  11015. }
  11016. } catch (err) {
  11017. showToast('Error', err.message, 'error');
  11018. }
  11019. }
  11020. // ----------------- Bridge IP Assignments -----------------
  11021. function openAddBridgeIPModal(id, name) {
  11022. document.getElementById('bridge-ip-modal-id').value = id;
  11023. document.getElementById('bridge-ip-modal-sub').innerText = name;
  11024. document.getElementById('bridge-ip-modal-cidr').value = '';
  11025. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  11026. }
  11027. function closeBridgeIPModal() {
  11028. document.getElementById('bridge-ip-modal').classList.add('hidden');
  11029. }
  11030. async function submitAddBridgeIP(e) {
  11031. e.preventDefault();
  11032. const id = document.getElementById('bridge-ip-modal-id').value;
  11033. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  11034. try {
  11035. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11036. method: 'POST',
  11037. headers: { 'Content-Type': 'application/json' },
  11038. body: JSON.stringify({ ip })
  11039. });
  11040. if (res.ok) {
  11041. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  11042. closeBridgeIPModal();
  11043. loadBridge();
  11044. fetchData(false);
  11045. } else {
  11046. const err = await res.json();
  11047. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  11048. }
  11049. } catch (err) {
  11050. showToast('Error', err.message, 'error');
  11051. }
  11052. }
  11053. async function deleteBridgeIP(id, ip) {
  11054. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  11055. try {
  11056. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11057. method: 'DELETE',
  11058. headers: { 'Content-Type': 'application/json' },
  11059. body: JSON.stringify({ ip })
  11060. });
  11061. if (res.ok) {
  11062. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  11063. loadBridge();
  11064. fetchData(false);
  11065. }
  11066. } catch (err) {
  11067. showToast('Error', err.message, 'error');
  11068. }
  11069. }
  11070. // ----------------- Bridge Ports -----------------
  11071. function renderBridgePorts() {
  11072. const tbody = document.getElementById('bridge-ports-table-body');
  11073. const empty = document.getElementById('bridge-empty-ports');
  11074. const countBadge = document.getElementById('bridge-ports-count-badge');
  11075. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  11076. if (!tbody) return;
  11077. tbody.innerHTML = '';
  11078. // Update filter select
  11079. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  11080. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  11081. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  11082. if (ports.length === 0) {
  11083. empty?.classList.remove('hidden');
  11084. return;
  11085. }
  11086. empty?.classList.add('hidden');
  11087. ports.forEach((p, idx) => {
  11088. const tr = document.createElement('tr');
  11089. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11090. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11091. tr.innerHTML = `
  11092. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11093. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11094. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11095. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11096. </td>
  11097. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11098. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11099. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11100. <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>
  11101. <td class="py-2.5 px-3">
  11102. ${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>'}
  11103. </td>
  11104. <td class="py-2.5 px-3">
  11105. <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>
  11106. </td>
  11107. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11108. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11109. <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>
  11110. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11111. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11112. </td>
  11113. `;
  11114. tbody.appendChild(tr);
  11115. });
  11116. }
  11117. function openAddBridgePortModal() {
  11118. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11119. document.getElementById('bridge-port-modal-id').value = '';
  11120. populateBridgeSelect('bridge-port-modal-bridge');
  11121. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11122. document.getElementById('bridge-port-modal-pvid').value = '1';
  11123. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11124. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11125. document.getElementById('bridge-port-modal-horizon').value = '0';
  11126. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11127. document.getElementById('bridge-port-modal-priority').value = '128';
  11128. document.getElementById('bridge-port-modal-learn').checked = true;
  11129. document.getElementById('bridge-port-modal-comment').value = '';
  11130. document.getElementById('bridge-port-modal-disabled').checked = false;
  11131. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11132. }
  11133. function openEditBridgePortModal(id) {
  11134. const p = (state.bridgePorts || []).find(x => x.id === id);
  11135. if (!p) return;
  11136. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11137. document.getElementById('bridge-port-modal-id').value = p.id;
  11138. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11139. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11140. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11141. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11142. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11143. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11144. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11145. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11146. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11147. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11148. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11149. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11150. }
  11151. function closeBridgePortModal() {
  11152. document.getElementById('bridge-port-modal').classList.add('hidden');
  11153. }
  11154. async function submitSaveBridgePort(e) {
  11155. e.preventDefault();
  11156. const id = document.getElementById('bridge-port-modal-id').value;
  11157. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11158. const iface = document.getElementById('bridge-port-modal-interface').value;
  11159. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11160. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11161. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11162. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11163. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11164. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11165. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11166. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11167. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11168. try {
  11169. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11170. method: 'POST',
  11171. headers: { 'Content-Type': 'application/json' },
  11172. body: JSON.stringify({
  11173. id,
  11174. bridge,
  11175. interface: iface,
  11176. pvid,
  11177. frame_types: frameTypes,
  11178. ingress_filtering: ingressFiltering,
  11179. horizon,
  11180. path_cost: pathCost,
  11181. priority,
  11182. learn,
  11183. comment,
  11184. disabled
  11185. })
  11186. });
  11187. if (res.ok) {
  11188. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11189. closeBridgePortModal();
  11190. loadBridge();
  11191. fetchData(false);
  11192. } else {
  11193. const err = await res.json();
  11194. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11195. }
  11196. } catch (err) {
  11197. showToast('Error', err.message, 'error');
  11198. }
  11199. }
  11200. async function toggleBridgePortState(id, disabled) {
  11201. try {
  11202. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11203. method: 'POST',
  11204. headers: { 'Content-Type': 'application/json' },
  11205. body: JSON.stringify({ disabled })
  11206. });
  11207. if (res.ok) {
  11208. loadBridge();
  11209. fetchData(false);
  11210. }
  11211. } catch (err) {
  11212. showToast('Error', err.message, 'error');
  11213. }
  11214. }
  11215. async function deleteBridgePort(id) {
  11216. const p = (state.bridgePorts || []).find(x => x.id === id);
  11217. const iface = p ? p.interface : id;
  11218. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11219. try {
  11220. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11221. if (res.ok) {
  11222. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11223. loadBridge();
  11224. fetchData(false);
  11225. }
  11226. } catch (err) {
  11227. showToast('Error', err.message, 'error');
  11228. }
  11229. }
  11230. // ----------------- Bridge VLANs -----------------
  11231. function renderBridgeVLANs() {
  11232. const tbody = document.getElementById('bridge-vlans-table-body');
  11233. const empty = document.getElementById('bridge-empty-vlans');
  11234. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11235. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11236. if (!tbody) return;
  11237. tbody.innerHTML = '';
  11238. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11239. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11240. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11241. if (vlans.length === 0) {
  11242. empty?.classList.remove('hidden');
  11243. return;
  11244. }
  11245. empty?.classList.add('hidden');
  11246. vlans.forEach((v, idx) => {
  11247. const tr = document.createElement('tr');
  11248. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11249. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11250. ? 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(' ')
  11251. : '<span class="text-slate-600">none</span>';
  11252. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11253. ? 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(' ')
  11254. : '<span class="text-slate-600">none</span>';
  11255. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11256. tr.innerHTML = `
  11257. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11258. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11259. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11260. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11261. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11262. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11263. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11264. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11265. <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>
  11266. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11267. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11268. </td>
  11269. `;
  11270. tbody.appendChild(tr);
  11271. });
  11272. }
  11273. function openAddBridgeVLANModal() {
  11274. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11275. document.getElementById('bridge-vlan-modal-id').value = '';
  11276. populateBridgeSelect('bridge-vlan-modal-bridge');
  11277. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11278. document.getElementById('bridge-vlan-modal-comment').value = '';
  11279. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11280. updateBridgeVlanPortCheckboxes();
  11281. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11282. }
  11283. function openEditBridgeVLANModal(id) {
  11284. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11285. if (!v) return;
  11286. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11287. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11288. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11289. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11290. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11291. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11292. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11293. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11294. }
  11295. function closeBridgeVlanModal() {
  11296. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11297. }
  11298. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11299. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11300. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11301. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11302. if (!taggedBox || !untaggedBox) return;
  11303. // Ports belonging to the selected bridge
  11304. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11305. if (memberPorts.length === 0) {
  11306. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11307. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11308. return;
  11309. }
  11310. taggedBox.innerHTML = memberPorts.map(p => `
  11311. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11312. <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">
  11313. <span>${p.interface}</span>
  11314. </label>
  11315. `).join('');
  11316. untaggedBox.innerHTML = memberPorts.map(p => `
  11317. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11318. <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">
  11319. <span>${p.interface}</span>
  11320. </label>
  11321. `).join('');
  11322. }
  11323. async function submitSaveBridgeVLAN(e) {
  11324. e.preventDefault();
  11325. const id = document.getElementById('bridge-vlan-modal-id').value;
  11326. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11327. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11328. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11329. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11330. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11331. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11332. try {
  11333. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11334. method: 'POST',
  11335. headers: { 'Content-Type': 'application/json' },
  11336. body: JSON.stringify({
  11337. id,
  11338. bridge,
  11339. vlan_ids: vlanIDs,
  11340. tagged,
  11341. untagged,
  11342. comment,
  11343. disabled
  11344. })
  11345. });
  11346. if (res.ok) {
  11347. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11348. closeBridgeVlanModal();
  11349. loadBridge();
  11350. } else {
  11351. const err = await res.json();
  11352. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11353. }
  11354. } catch (err) {
  11355. showToast('Error', err.message, 'error');
  11356. }
  11357. }
  11358. async function toggleBridgeVLANState(id, disabled) {
  11359. try {
  11360. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11361. method: 'POST',
  11362. headers: { 'Content-Type': 'application/json' },
  11363. body: JSON.stringify({ disabled })
  11364. });
  11365. if (res.ok) loadBridge();
  11366. } catch (err) {
  11367. showToast('Error', err.message, 'error');
  11368. }
  11369. }
  11370. async function deleteBridgeVLAN(id) {
  11371. if (!confirm('Delete this bridge VLAN entry?')) return;
  11372. try {
  11373. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11374. if (res.ok) {
  11375. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11376. loadBridge();
  11377. }
  11378. } catch (err) {
  11379. showToast('Error', err.message, 'error');
  11380. }
  11381. }
  11382. // ----------------- Hosts / MAC Table -----------------
  11383. async function loadBridgeHosts() {
  11384. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11385. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11386. try {
  11387. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11388. const res = await fetch(url);
  11389. if (res.ok) {
  11390. state.bridgeHosts = await res.json();
  11391. renderBridgeHosts();
  11392. }
  11393. } catch (err) {
  11394. console.error('Failed to load bridge hosts:', err);
  11395. }
  11396. }
  11397. function renderBridgeHosts() {
  11398. const tbody = document.getElementById('bridge-hosts-table-body');
  11399. const empty = document.getElementById('bridge-empty-hosts');
  11400. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11401. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11402. if (!tbody) return;
  11403. tbody.innerHTML = '';
  11404. const hosts = (state.bridgeHosts || []).filter(h => {
  11405. if (!search) return true;
  11406. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11407. });
  11408. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11409. if (hosts.length === 0) {
  11410. empty?.classList.remove('hidden');
  11411. return;
  11412. }
  11413. empty?.classList.add('hidden');
  11414. hosts.forEach(h => {
  11415. const tr = document.createElement('tr');
  11416. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11417. let flagBadges = '';
  11418. 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>';
  11419. 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>';
  11420. 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>';
  11421. tr.innerHTML = `
  11422. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11423. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11424. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11425. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11426. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11427. <td class="py-2.5 px-3">${flagBadges}</td>
  11428. `;
  11429. tbody.appendChild(tr);
  11430. });
  11431. }
  11432. async function flushBridgeHosts() {
  11433. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11434. if (!selBridge) {
  11435. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11436. return;
  11437. }
  11438. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11439. try {
  11440. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11441. method: 'POST',
  11442. headers: { 'Content-Type': 'application/json' },
  11443. body: JSON.stringify({ bridge: selBridge })
  11444. });
  11445. if (res.ok) {
  11446. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11447. loadBridgeHosts();
  11448. }
  11449. } catch (err) {
  11450. showToast('Error', err.message, 'error');
  11451. }
  11452. }
  11453. // ----------------- Helpers -----------------
  11454. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11455. const sel = document.getElementById(selectId);
  11456. if (!sel) return;
  11457. const prevVal = currentVal || sel.value;
  11458. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11459. (state.bridges || []).forEach(b => {
  11460. const opt = document.createElement('option');
  11461. opt.value = b.name;
  11462. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11463. if (b.name === prevVal) opt.selected = true;
  11464. sel.appendChild(opt);
  11465. });
  11466. }
  11467. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11468. const sel = document.getElementById(selectId);
  11469. if (!sel) return;
  11470. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11471. // 1. Physical Interfaces
  11472. const grpPhys = document.createElement('optgroup');
  11473. grpPhys.label = 'Physical Interfaces';
  11474. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11475. const opt = document.createElement('option');
  11476. opt.value = i.name;
  11477. opt.innerText = `${i.name} (${i.role || i.type})`;
  11478. if (i.name === currentVal) opt.selected = true;
  11479. grpPhys.appendChild(opt);
  11480. });
  11481. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11482. // 2. VLAN Sub-interfaces
  11483. const grpVlans = document.createElement('optgroup');
  11484. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11485. (state.vlans || []).forEach(v => {
  11486. const opt = document.createElement('option');
  11487. opt.value = v.name;
  11488. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11489. if (v.name === currentVal) opt.selected = true;
  11490. grpVlans.appendChild(opt);
  11491. });
  11492. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11493. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11494. const grpEoip = document.createElement('optgroup');
  11495. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11496. (state.eoipTunnels || []).forEach(t => {
  11497. const opt = document.createElement('option');
  11498. opt.value = t.name;
  11499. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11500. if (t.name === currentVal) opt.selected = true;
  11501. grpEoip.appendChild(opt);
  11502. });
  11503. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11504. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11505. const grpVxlan = document.createElement('optgroup');
  11506. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11507. (state.vxlanTunnels || []).forEach(t => {
  11508. const opt = document.createElement('option');
  11509. opt.value = t.name;
  11510. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11511. if (t.name === currentVal) opt.selected = true;
  11512. grpVxlan.appendChild(opt);
  11513. });
  11514. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11515. }
  11516. // -------------------------------------------------------------
  11517. // DebTik Routing Filters Management (/routing filter)
  11518. // -------------------------------------------------------------
  11519. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11520. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11521. if (!state.rfSort) state.rfSort = {};
  11522. function switchRoutingFilterTab(tab) {
  11523. state.activeRoutingFilterTab = tab;
  11524. const tabs = ['rules', 'community-lists', 'as-lists'];
  11525. tabs.forEach(t => {
  11526. const btn = document.getElementById(`tab-rf-${t}`);
  11527. const content = document.getElementById(`tab-content-rf-${t}`);
  11528. if (btn) {
  11529. if (t === tab) {
  11530. 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';
  11531. } else {
  11532. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11533. }
  11534. }
  11535. if (content) {
  11536. if (t === tab) content.classList.remove('hidden');
  11537. else content.classList.add('hidden');
  11538. }
  11539. });
  11540. const chainContainer = document.getElementById('rf-chain-filter-container');
  11541. if (chainContainer) {
  11542. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11543. else chainContainer.classList.add('hidden');
  11544. }
  11545. renderRoutingFilters();
  11546. }
  11547. function selectFilterRow(tab, id) {
  11548. if (state.selectedFilterRow[tab] === id) {
  11549. delete state.selectedFilterRow[tab];
  11550. } else {
  11551. state.selectedFilterRow[tab] = id;
  11552. }
  11553. if (tab === 'rules') renderRoutingFilterRules();
  11554. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11555. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11556. }
  11557. function openRoutingFilterNewModal() {
  11558. const tab = state.activeRoutingFilterTab || 'rules';
  11559. if (tab === 'rules') openAddRoutingFilterModal();
  11560. else if (tab === 'community-lists') openAddCommunityListModal();
  11561. else if (tab === 'as-lists') openAddASListModal();
  11562. }
  11563. function toggleSelectedRoutingFilter(disabled) {
  11564. const tab = state.activeRoutingFilterTab || 'rules';
  11565. const id = state.selectedFilterRow[tab];
  11566. if (!id) {
  11567. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11568. return;
  11569. }
  11570. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11571. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11572. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11573. }
  11574. function removeSelectedRoutingFilter() {
  11575. const tab = state.activeRoutingFilterTab || 'rules';
  11576. const id = state.selectedFilterRow[tab];
  11577. if (!id) {
  11578. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11579. return;
  11580. }
  11581. if (tab === 'rules') deleteRoutingFilter(id);
  11582. else if (tab === 'community-lists') deleteCommunityList(id);
  11583. else if (tab === 'as-lists') deleteASList(id);
  11584. }
  11585. function searchRoutingFilters(q) {
  11586. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11587. renderRoutingFilters();
  11588. }
  11589. function sortFilterTable(tab, col) {
  11590. if (!state.rfSort) state.rfSort = {};
  11591. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11592. if (state.rfSort[tab].col === col) {
  11593. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11594. } else {
  11595. state.rfSort[tab].col = col;
  11596. state.rfSort[tab].asc = true;
  11597. }
  11598. const asc = state.rfSort[tab].asc;
  11599. let list = [];
  11600. if (tab === 'rules') list = state.routingFilters || [];
  11601. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11602. else if (tab === 'as-lists') list = state.routingASLists || [];
  11603. list.sort((a, b) => {
  11604. let valA = a[col] ?? '';
  11605. let valB = b[col] ?? '';
  11606. if (col === 'flags') {
  11607. valA = a.disabled ? 'X' : 'A';
  11608. valB = b.disabled ? 'X' : 'A';
  11609. }
  11610. if (typeof valA === 'number' && typeof valB === 'number') {
  11611. return asc ? valA - valB : valB - valA;
  11612. }
  11613. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11614. });
  11615. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11616. allCols.forEach(c => {
  11617. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11618. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11619. });
  11620. if (tab === 'rules') renderRoutingFilterRules();
  11621. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11622. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11623. }
  11624. function renderRoutingFilters() {
  11625. const navBadge = document.getElementById('badge-filters-count');
  11626. const allRules = state.routingFilters || [];
  11627. if (navBadge) navBadge.innerText = allRules.length;
  11628. // Populate chain filter select options and datalist
  11629. const chainSelect = document.getElementById('routing-filter-chain-select');
  11630. const chainDatalist = document.getElementById('dl-routing-chains');
  11631. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11632. if (chainSelect) {
  11633. const currentVal = state.filterChainSelected || 'all';
  11634. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11635. uniqueChains.map(ch => {
  11636. const count = allRules.filter(r => r.chain === ch).length;
  11637. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11638. }).join('');
  11639. chainSelect.value = currentVal;
  11640. }
  11641. if (chainDatalist) {
  11642. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11643. }
  11644. renderRoutingFilterRules();
  11645. renderRoutingFilterCommunityLists();
  11646. renderRoutingFilterASLists();
  11647. }
  11648. function filterRoutingFiltersByChain(chain) {
  11649. state.filterChainSelected = chain;
  11650. renderRoutingFilters();
  11651. }
  11652. // -------------------------------------------------------------
  11653. // TAB 1: RULES (/routing filter rule)
  11654. // -------------------------------------------------------------
  11655. function renderRoutingFilterRules() {
  11656. const tbody = document.getElementById('routing-filter-rules-tbody');
  11657. if (!tbody) return;
  11658. const empty = document.getElementById('rf-rules-empty');
  11659. const statusCount = document.getElementById('rf-status-count');
  11660. let list = (state.routingFilters || []).slice();
  11661. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11662. list = list.filter(r => r.chain === state.filterChainSelected);
  11663. }
  11664. const q = state.rfSearchQuery;
  11665. if (q) {
  11666. list = list.filter(r =>
  11667. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11668. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11669. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11670. (r.comment && r.comment.toLowerCase().includes(q))
  11671. );
  11672. }
  11673. if (!state.rfSort?.['rules']) {
  11674. list.sort((a, b) => {
  11675. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11676. return (a.rule_order || 0) - (b.rule_order || 0);
  11677. });
  11678. }
  11679. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11680. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11681. }
  11682. if (list.length === 0) {
  11683. tbody.innerHTML = '';
  11684. if (empty) empty.classList.remove('hidden');
  11685. return;
  11686. }
  11687. if (empty) empty.classList.add('hidden');
  11688. tbody.innerHTML = list.map(r => {
  11689. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11690. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11691. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11692. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11693. let ruleDisplay = '';
  11694. if (r.rule && r.rule.trim() !== '') {
  11695. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11696. } else {
  11697. let conds = [];
  11698. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11699. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11700. let act = r.action || 'accept';
  11701. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11702. }
  11703. return `
  11704. <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'}">
  11705. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11706. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11707. <td class="py-2 px-3">
  11708. <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>
  11709. </td>
  11710. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11711. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11712. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11713. <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>
  11714. <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>
  11715. <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'}">
  11716. ${r.disabled ? 'Enable' : 'Disable'}
  11717. </button>
  11718. <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">
  11719. Edit
  11720. </button>
  11721. <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">
  11722. ✕
  11723. </button>
  11724. </td>
  11725. </tr>
  11726. `;
  11727. }).join('');
  11728. }
  11729. // -------------------------------------------------------------
  11730. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11731. // -------------------------------------------------------------
  11732. function renderRoutingFilterCommunityLists() {
  11733. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11734. if (!tbody) return;
  11735. const empty = document.getElementById('rf-comm-lists-empty');
  11736. const statusCount = document.getElementById('rf-status-count');
  11737. let list = (state.routingCommunityLists || []).slice();
  11738. const q = state.rfSearchQuery;
  11739. if (q) {
  11740. list = list.filter(cl =>
  11741. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11742. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11743. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11744. );
  11745. }
  11746. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11747. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11748. }
  11749. if (list.length === 0) {
  11750. tbody.innerHTML = '';
  11751. if (empty) empty.classList.remove('hidden');
  11752. return;
  11753. }
  11754. if (empty) empty.classList.add('hidden');
  11755. tbody.innerHTML = list.map(cl => {
  11756. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11757. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11758. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11759. const commBadges = (cl.communities || []).map(c =>
  11760. `<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>`
  11761. ).join(' ');
  11762. return `
  11763. <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'}">
  11764. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11765. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11766. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11767. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11768. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11769. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11770. <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'}">
  11771. ${cl.disabled ? 'Enable' : 'Disable'}
  11772. </button>
  11773. <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">
  11774. Edit
  11775. </button>
  11776. <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">
  11777. ✕
  11778. </button>
  11779. </td>
  11780. </tr>
  11781. `;
  11782. }).join('');
  11783. }
  11784. // -------------------------------------------------------------
  11785. // TAB 4: AS LISTS (/routing filter num-list)
  11786. // -------------------------------------------------------------
  11787. function renderRoutingFilterASLists() {
  11788. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11789. if (!tbody) return;
  11790. const empty = document.getElementById('rf-as-lists-empty');
  11791. const statusCount = document.getElementById('rf-status-count');
  11792. let list = (state.routingASLists || []).slice();
  11793. const q = state.rfSearchQuery;
  11794. if (q) {
  11795. list = list.filter(al =>
  11796. (al.name && al.name.toLowerCase().includes(q)) ||
  11797. (al.range && al.range.toLowerCase().includes(q)) ||
  11798. (al.comment && al.comment.toLowerCase().includes(q))
  11799. );
  11800. }
  11801. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11802. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11803. }
  11804. if (list.length === 0) {
  11805. tbody.innerHTML = '';
  11806. if (empty) empty.classList.remove('hidden');
  11807. return;
  11808. }
  11809. if (empty) empty.classList.add('hidden');
  11810. tbody.innerHTML = list.map(al => {
  11811. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11812. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11813. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11814. return `
  11815. <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'}">
  11816. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11817. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11818. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11819. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11820. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11821. <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'}">
  11822. ${al.disabled ? 'Enable' : 'Disable'}
  11823. </button>
  11824. <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">
  11825. Edit
  11826. </button>
  11827. <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">
  11828. ✕
  11829. </button>
  11830. </td>
  11831. </tr>
  11832. `;
  11833. }).join('');
  11834. }
  11835. // -------------------------------------------------------------
  11836. // SNIPPETS & WIZARD HELPERS
  11837. // -------------------------------------------------------------
  11838. function insertRuleSnippet(type) {
  11839. const textarea = document.getElementById('modal-rf-rule');
  11840. if (!textarea) return;
  11841. let snippet = '';
  11842. switch (type) {
  11843. case 'accept-default':
  11844. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11845. break;
  11846. case 'drop-rfc1918':
  11847. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11848. break;
  11849. case 'len-24':
  11850. snippet = 'if (dst-len > 24) { reject; }';
  11851. break;
  11852. case 'local-pref-150':
  11853. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11854. break;
  11855. case 'as-prepend-2':
  11856. snippet = 'set bgp-path-prepend 2; accept;';
  11857. break;
  11858. case 'set-comm':
  11859. snippet = 'set bgp-communities.add 65000:100; accept;';
  11860. break;
  11861. case 'match-comm':
  11862. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11863. break;
  11864. case 'reject-all':
  11865. snippet = 'reject;';
  11866. break;
  11867. }
  11868. if (!snippet) return;
  11869. if (!textarea.value.trim()) {
  11870. textarea.value = snippet;
  11871. } else {
  11872. textarea.value = textarea.value.trim() + '\n' + snippet;
  11873. }
  11874. }
  11875. function generateScriptFromWizard() {
  11876. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11877. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11878. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11879. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11880. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11881. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11882. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11883. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11884. const conds = [];
  11885. if (pfx) {
  11886. if (pfxLen) {
  11887. if (pfxLen.includes('-')) {
  11888. const parts = pfxLen.split('-');
  11889. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11890. } else {
  11891. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11892. }
  11893. } else {
  11894. conds.push(`dst in ${pfx}`);
  11895. }
  11896. }
  11897. if (proto && proto !== 'any') {
  11898. conds.push(`protocol ${proto}`);
  11899. }
  11900. if (asp) {
  11901. conds.push(`bgp-as-path "${asp}"`);
  11902. }
  11903. if (comm) {
  11904. conds.push(`bgp-communities includes ${comm}`);
  11905. }
  11906. const actions = [];
  11907. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11908. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11909. if (act && act !== 'passthrough') {
  11910. actions.push(`${act};`);
  11911. }
  11912. let code = '';
  11913. if (conds.length > 0) {
  11914. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11915. } else {
  11916. code = actions.join(' ');
  11917. }
  11918. const textarea = document.getElementById('modal-rf-rule');
  11919. if (textarea) textarea.value = code;
  11920. }
  11921. // -------------------------------------------------------------
  11922. // MODAL CRUD: RULES (/routing filter rule)
  11923. // -------------------------------------------------------------
  11924. function openAddRoutingFilterModal(defaultChain = '') {
  11925. const form = document.getElementById('routing-filter-form');
  11926. if (form) form.reset();
  11927. const idEl = document.getElementById('modal-rf-id');
  11928. if (idEl) idEl.value = '';
  11929. const titleEl = document.getElementById('modal-rf-title');
  11930. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11931. const chainEl = document.getElementById('modal-rf-chain');
  11932. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11933. const orderEl = document.getElementById('modal-rf-order');
  11934. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11935. const ruleEl = document.getElementById('modal-rf-rule');
  11936. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11937. const disEl = document.getElementById('modal-rf-disabled');
  11938. if (disEl) disEl.checked = false;
  11939. const modal = document.getElementById('modal-routing-filter');
  11940. if (modal) modal.classList.remove('hidden');
  11941. }
  11942. function openEditRoutingFilterModal(id) {
  11943. const r = (state.routingFilters || []).find(item => item.id === id);
  11944. if (!r) return;
  11945. const idEl = document.getElementById('modal-rf-id');
  11946. if (idEl) idEl.value = r.id;
  11947. const titleEl = document.getElementById('modal-rf-title');
  11948. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11949. const chainEl = document.getElementById('modal-rf-chain');
  11950. if (chainEl) chainEl.value = r.chain || '';
  11951. const orderEl = document.getElementById('modal-rf-order');
  11952. if (orderEl) orderEl.value = r.rule_order || 10;
  11953. const ruleEl = document.getElementById('modal-rf-rule');
  11954. if (ruleEl) {
  11955. if (r.rule) {
  11956. ruleEl.value = r.rule;
  11957. } else {
  11958. let conds = [];
  11959. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11960. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11961. let act = r.action || 'accept';
  11962. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11963. }
  11964. }
  11965. const comEl = document.getElementById('modal-rf-comment');
  11966. if (comEl) comEl.value = r.comment || '';
  11967. const disEl = document.getElementById('modal-rf-disabled');
  11968. if (disEl) disEl.checked = !!r.disabled;
  11969. const modal = document.getElementById('modal-routing-filter');
  11970. if (modal) modal.classList.remove('hidden');
  11971. }
  11972. function closeRoutingFilterModal() {
  11973. const modal = document.getElementById('modal-routing-filter');
  11974. if (modal) modal.classList.add('hidden');
  11975. }
  11976. async function submitRoutingFilter(e) {
  11977. if (e) e.preventDefault();
  11978. const payload = {
  11979. id: document.getElementById('modal-rf-id').value,
  11980. chain: document.getElementById('modal-rf-chain').value.trim(),
  11981. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11982. rule: document.getElementById('modal-rf-rule').value.trim(),
  11983. comment: document.getElementById('modal-rf-comment').value.trim(),
  11984. disabled: document.getElementById('modal-rf-disabled').checked
  11985. };
  11986. try {
  11987. const res = await fetch(`${API_BASE}/routing/filters`, {
  11988. method: 'POST',
  11989. headers: { 'Content-Type': 'application/json' },
  11990. body: JSON.stringify(payload)
  11991. });
  11992. if (res.ok) {
  11993. closeRoutingFilterModal();
  11994. showToast('Success', 'Routing filter rule saved', 'success');
  11995. loadDynamicRouting();
  11996. } else {
  11997. const err = await res.json();
  11998. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11999. }
  12000. } catch (err) {
  12001. showToast('Error', err.message, 'error');
  12002. }
  12003. }
  12004. async function applyRoutingFilterForm() {
  12005. const payload = {
  12006. id: document.getElementById('modal-rf-id').value,
  12007. chain: document.getElementById('modal-rf-chain').value.trim(),
  12008. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  12009. rule: document.getElementById('modal-rf-rule').value.trim(),
  12010. comment: document.getElementById('modal-rf-comment').value.trim(),
  12011. disabled: document.getElementById('modal-rf-disabled').checked
  12012. };
  12013. try {
  12014. const res = await fetch(`${API_BASE}/routing/filters`, {
  12015. method: 'POST',
  12016. headers: { 'Content-Type': 'application/json' },
  12017. body: JSON.stringify(payload)
  12018. });
  12019. if (res.ok) {
  12020. const data = await res.json();
  12021. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  12022. showToast('Applied', 'Routing filter configuration applied', 'success');
  12023. loadDynamicRouting();
  12024. } else {
  12025. const err = await res.json();
  12026. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  12027. }
  12028. } catch (err) {
  12029. showToast('Error', err.message, 'error');
  12030. }
  12031. }
  12032. async function moveRoutingFilterOrder(id, delta) {
  12033. const list = state.routingFilters || [];
  12034. const idx = list.findIndex(r => r.id === id);
  12035. if (idx < 0) return;
  12036. const targetIdx = idx + delta;
  12037. if (targetIdx < 0 || targetIdx >= list.length) return;
  12038. const currentOrder = list[idx].rule_order || 10;
  12039. const targetOrder = list[targetIdx].rule_order || 20;
  12040. list[idx].rule_order = targetOrder;
  12041. list[targetIdx].rule_order = currentOrder;
  12042. try {
  12043. await fetch(`${API_BASE}/routing/filters`, {
  12044. method: 'POST',
  12045. headers: { 'Content-Type': 'application/json' },
  12046. body: JSON.stringify(list[idx])
  12047. });
  12048. await fetch(`${API_BASE}/routing/filters`, {
  12049. method: 'POST',
  12050. headers: { 'Content-Type': 'application/json' },
  12051. body: JSON.stringify(list[targetIdx])
  12052. });
  12053. loadDynamicRouting();
  12054. } catch (e) {
  12055. console.error('Reorder error:', e);
  12056. }
  12057. }
  12058. async function deleteRoutingFilter(id) {
  12059. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  12060. try {
  12061. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12062. if (res.ok) {
  12063. showToast('Deleted', 'Routing filter rule removed', 'info');
  12064. loadDynamicRouting();
  12065. } else {
  12066. const err = await res.json();
  12067. showToast('Error', err.error || 'Failed to delete rule', 'error');
  12068. }
  12069. } catch (err) {
  12070. showToast('Error', err.message, 'error');
  12071. }
  12072. }
  12073. async function toggleRoutingFilterState(id, disabled) {
  12074. try {
  12075. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  12076. method: 'POST',
  12077. headers: { 'Content-Type': 'application/json' },
  12078. body: JSON.stringify({ disabled })
  12079. });
  12080. if (res.ok) {
  12081. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12082. loadDynamicRouting();
  12083. } else {
  12084. const err = await res.json();
  12085. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  12086. }
  12087. } catch (err) {
  12088. showToast('Error', err.message, 'error');
  12089. }
  12090. }
  12091. // -------------------------------------------------------------
  12092. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12093. // -------------------------------------------------------------
  12094. function openAddCommunityListModal() {
  12095. document.getElementById('modal-rf-cl-id').value = '';
  12096. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12097. document.getElementById('modal-rf-cl-name').value = '';
  12098. document.getElementById('modal-rf-cl-communities').value = '';
  12099. document.getElementById('modal-rf-cl-regexp').value = '';
  12100. document.getElementById('modal-rf-cl-comment').value = '';
  12101. document.getElementById('modal-rf-cl-disabled').checked = false;
  12102. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12103. }
  12104. function openEditCommunityListModal(id) {
  12105. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12106. if (!cl) return;
  12107. document.getElementById('modal-rf-cl-id').value = cl.id;
  12108. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12109. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12110. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12111. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12112. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12113. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12114. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12115. }
  12116. function closeCommunityListModal() {
  12117. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12118. }
  12119. async function submitCommunityList(e) {
  12120. e.preventDefault();
  12121. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12122. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12123. const payload = {
  12124. id: document.getElementById('modal-rf-cl-id').value,
  12125. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12126. communities: comms,
  12127. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12128. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12129. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12130. };
  12131. try {
  12132. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12133. method: 'POST',
  12134. headers: { 'Content-Type': 'application/json' },
  12135. body: JSON.stringify(payload)
  12136. });
  12137. if (res.ok) {
  12138. closeCommunityListModal();
  12139. showToast('Success', 'Community list saved', 'success');
  12140. loadDynamicRouting();
  12141. } else {
  12142. const err = await res.json();
  12143. showToast('Error', err.error || 'Failed to save community list', 'error');
  12144. }
  12145. } catch (err) {
  12146. showToast('Error', err.message, 'error');
  12147. }
  12148. }
  12149. async function deleteCommunityList(id) {
  12150. if (!confirm('Are you sure you want to delete this community list?')) return;
  12151. try {
  12152. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12153. if (res.ok) {
  12154. showToast('Deleted', 'Community list removed', 'info');
  12155. loadDynamicRouting();
  12156. } else {
  12157. const err = await res.json();
  12158. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12159. }
  12160. } catch (err) {
  12161. showToast('Error', err.message, 'error');
  12162. }
  12163. }
  12164. async function toggleCommunityListState(id, disabled) {
  12165. try {
  12166. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12167. method: 'POST',
  12168. headers: { 'Content-Type': 'application/json' },
  12169. body: JSON.stringify({ disabled })
  12170. });
  12171. if (res.ok) {
  12172. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12173. loadDynamicRouting();
  12174. } else {
  12175. const err = await res.json();
  12176. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12177. }
  12178. } catch (err) {
  12179. showToast('Error', err.message, 'error');
  12180. }
  12181. }
  12182. // -------------------------------------------------------------
  12183. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12184. // -------------------------------------------------------------
  12185. function openAddASListModal() {
  12186. document.getElementById('modal-rf-al-id').value = '';
  12187. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12188. document.getElementById('modal-rf-al-name').value = '';
  12189. document.getElementById('modal-rf-al-range').value = '';
  12190. document.getElementById('modal-rf-al-comment').value = '';
  12191. document.getElementById('modal-rf-al-disabled').checked = false;
  12192. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12193. }
  12194. function openEditASListModal(id) {
  12195. const al = (state.routingASLists || []).find(item => item.id === id);
  12196. if (!al) return;
  12197. document.getElementById('modal-rf-al-id').value = al.id;
  12198. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12199. document.getElementById('modal-rf-al-name').value = al.name || '';
  12200. document.getElementById('modal-rf-al-range').value = al.range || '';
  12201. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12202. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12203. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12204. }
  12205. function closeASListModal() {
  12206. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12207. }
  12208. async function submitASList(e) {
  12209. e.preventDefault();
  12210. const payload = {
  12211. id: document.getElementById('modal-rf-al-id').value,
  12212. name: document.getElementById('modal-rf-al-name').value.trim(),
  12213. range: document.getElementById('modal-rf-al-range').value.trim(),
  12214. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12215. disabled: document.getElementById('modal-rf-al-disabled').checked
  12216. };
  12217. try {
  12218. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12219. method: 'POST',
  12220. headers: { 'Content-Type': 'application/json' },
  12221. body: JSON.stringify(payload)
  12222. });
  12223. if (res.ok) {
  12224. closeASListModal();
  12225. showToast('Success', 'AS number list saved', 'success');
  12226. loadDynamicRouting();
  12227. } else {
  12228. const err = await res.json();
  12229. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12230. }
  12231. } catch (err) {
  12232. showToast('Error', err.message, 'error');
  12233. }
  12234. }
  12235. async function deleteASList(id) {
  12236. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12237. try {
  12238. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12239. if (res.ok) {
  12240. showToast('Deleted', 'AS list removed', 'info');
  12241. loadDynamicRouting();
  12242. } else {
  12243. const err = await res.json();
  12244. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12245. }
  12246. } catch (err) {
  12247. showToast('Error', err.message, 'error');
  12248. }
  12249. }
  12250. async function toggleASListState(id, disabled) {
  12251. try {
  12252. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12253. method: 'POST',
  12254. headers: { 'Content-Type': 'application/json' },
  12255. body: JSON.stringify({ disabled })
  12256. });
  12257. if (res.ok) {
  12258. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12259. loadDynamicRouting();
  12260. } else {
  12261. const err = await res.json();
  12262. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12263. }
  12264. } catch (err) {
  12265. showToast('Error', err.message, 'error');
  12266. }
  12267. }
  12268. // ==========================================
  12269. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12270. // ==========================================
  12271. function loadToolsView() {
  12272. populateToolsInterfaces();
  12273. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12274. }
  12275. function populateToolsInterfaces() {
  12276. const pingSel = document.getElementById('tools-ping-iface');
  12277. const traceSel = document.getElementById('tools-tr-iface');
  12278. let opts = '<option value="">Auto (Default Route)</option>';
  12279. if (Array.isArray(state.interfaces)) {
  12280. state.interfaces.forEach(iface => {
  12281. if (iface.name) {
  12282. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12283. }
  12284. });
  12285. }
  12286. if (pingSel) {
  12287. const cur = pingSel.value;
  12288. pingSel.innerHTML = opts;
  12289. if (cur) pingSel.value = cur;
  12290. }
  12291. if (traceSel) {
  12292. const cur = traceSel.value;
  12293. traceSel.innerHTML = opts;
  12294. if (cur) traceSel.value = cur;
  12295. }
  12296. }
  12297. function switchToolsSubTab(subTab) {
  12298. state.activeToolsSubTab = subTab;
  12299. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12300. tabs.forEach(t => {
  12301. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12302. const view = document.getElementById(`tools-view-${t}`);
  12303. if (btn) {
  12304. if (t === subTab) {
  12305. 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';
  12306. } else {
  12307. 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';
  12308. }
  12309. }
  12310. if (view) {
  12311. if (t === subTab) {
  12312. view.classList.remove('hidden');
  12313. } else {
  12314. view.classList.add('hidden');
  12315. }
  12316. }
  12317. });
  12318. }
  12319. function setPortPreset(port) {
  12320. const input = document.getElementById('tools-port-num');
  12321. if (input) input.value = port;
  12322. }
  12323. let pingAbortController = null;
  12324. let tracerouteAbortController = null;
  12325. function clearPingTable() {
  12326. const tbody = document.getElementById('tools-ping-tbody');
  12327. if (tbody) tbody.innerHTML = '';
  12328. const rawEl = document.getElementById('tools-ping-raw');
  12329. if (rawEl) rawEl.innerText = '';
  12330. const sentEl = document.getElementById('tools-ping-stat-sent');
  12331. if (sentEl) sentEl.innerText = '0';
  12332. const recvEl = document.getElementById('tools-ping-stat-recv');
  12333. if (recvEl) recvEl.innerText = '0';
  12334. const lossEl = document.getElementById('tools-ping-stat-loss');
  12335. if (lossEl) lossEl.innerText = '0%';
  12336. const avgEl = document.getElementById('tools-ping-stat-avg');
  12337. if (avgEl) avgEl.innerText = '0 ms';
  12338. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12339. if (minMaxEl) minMaxEl.innerText = '-';
  12340. const badge = document.getElementById('tools-ping-status-badge');
  12341. if (badge) {
  12342. badge.className = '';
  12343. badge.innerText = '';
  12344. }
  12345. }
  12346. function clearTracerouteTable() {
  12347. const tbody = document.getElementById('tools-tr-tbody');
  12348. if (tbody) tbody.innerHTML = '';
  12349. const rawEl = document.getElementById('tools-tr-raw');
  12350. if (rawEl) rawEl.innerText = '';
  12351. const statHops = document.getElementById('tools-tr-hops-count');
  12352. if (statHops) statHops.innerText = '0 Hops';
  12353. }
  12354. function resetPingButton() {
  12355. const btn = document.getElementById('tools-ping-btn');
  12356. const btnText = document.getElementById('tools-ping-btn-text');
  12357. const spinner = document.getElementById('tools-ping-spinner');
  12358. if (btn) {
  12359. btn.disabled = false;
  12360. 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';
  12361. }
  12362. if (btnText) btnText.innerText = 'Start Ping';
  12363. if (spinner) spinner.classList.add('hidden');
  12364. }
  12365. function setPingRunningButton() {
  12366. const btn = document.getElementById('tools-ping-btn');
  12367. const btnText = document.getElementById('tools-ping-btn-text');
  12368. const spinner = document.getElementById('tools-ping-spinner');
  12369. if (btn) {
  12370. btn.disabled = false;
  12371. 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';
  12372. }
  12373. if (btnText) btnText.innerText = 'Stop Ping';
  12374. if (spinner) spinner.classList.remove('hidden');
  12375. }
  12376. function resetTracerouteButton() {
  12377. const btn = document.getElementById('tools-tr-btn');
  12378. const btnText = document.getElementById('tools-tr-btn-text');
  12379. const spinner = document.getElementById('tools-tr-spinner');
  12380. if (btn) {
  12381. btn.disabled = false;
  12382. 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';
  12383. }
  12384. if (btnText) btnText.innerText = 'Start Traceroute';
  12385. if (spinner) spinner.classList.add('hidden');
  12386. }
  12387. function setTracerouteRunningButton() {
  12388. const btn = document.getElementById('tools-tr-btn');
  12389. const btnText = document.getElementById('tools-tr-btn-text');
  12390. const spinner = document.getElementById('tools-tr-spinner');
  12391. if (btn) {
  12392. btn.disabled = false;
  12393. 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';
  12394. }
  12395. if (btnText) btnText.innerText = 'Stop Traceroute';
  12396. if (spinner) spinner.classList.remove('hidden');
  12397. }
  12398. async function executePing(e) {
  12399. if (e) e.preventDefault();
  12400. // If already running, clicking the button stops the stream!
  12401. if (pingAbortController) {
  12402. pingAbortController.abort();
  12403. pingAbortController = null;
  12404. resetPingButton();
  12405. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12406. return;
  12407. }
  12408. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12409. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12410. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12411. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12412. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12413. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12414. if (!target) {
  12415. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12416. return;
  12417. }
  12418. clearPingTable();
  12419. const resCard = document.getElementById('tools-ping-results');
  12420. if (resCard) resCard.classList.remove('hidden');
  12421. pingAbortController = new AbortController();
  12422. setPingRunningButton();
  12423. try {
  12424. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12425. method: 'POST',
  12426. headers: { 'Content-Type': 'application/json' },
  12427. body: JSON.stringify({
  12428. target,
  12429. count,
  12430. size,
  12431. timeout,
  12432. interface: iface,
  12433. dont_frag: dontFrag
  12434. }),
  12435. signal: pingAbortController.signal
  12436. });
  12437. if (!res.ok) {
  12438. const errText = await res.text();
  12439. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12440. resetPingButton();
  12441. pingAbortController = null;
  12442. return;
  12443. }
  12444. const reader = res.body.getReader();
  12445. const decoder = new TextDecoder('utf-8');
  12446. let buffer = '';
  12447. while (true) {
  12448. const { done, value } = await reader.read();
  12449. if (done) break;
  12450. buffer += decoder.decode(value, { stream: true });
  12451. const blocks = buffer.split('\n\n');
  12452. buffer = blocks.pop() || '';
  12453. for (const block of blocks) {
  12454. const trimmed = block.trim();
  12455. if (!trimmed) continue;
  12456. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12457. try {
  12458. const evt = JSON.parse(line);
  12459. handleLivePingEvent(evt);
  12460. } catch (parseErr) {
  12461. console.warn('Ping SSE parse error:', parseErr, line);
  12462. }
  12463. }
  12464. }
  12465. } catch (err) {
  12466. if (err.name === 'AbortError') {
  12467. // User aborted normally
  12468. } else {
  12469. showToast('Ping Error', err.message, 'error');
  12470. }
  12471. } finally {
  12472. pingAbortController = null;
  12473. resetPingButton();
  12474. }
  12475. }
  12476. function handleLivePingEvent(evt) {
  12477. const sentEl = document.getElementById('tools-ping-stat-sent');
  12478. const recvEl = document.getElementById('tools-ping-stat-recv');
  12479. const lossEl = document.getElementById('tools-ping-stat-loss');
  12480. const avgEl = document.getElementById('tools-ping-stat-avg');
  12481. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12482. const badge = document.getElementById('tools-ping-status-badge');
  12483. const tbody = document.getElementById('tools-ping-tbody');
  12484. const rawEl = document.getElementById('tools-ping-raw');
  12485. if (evt.raw && rawEl) {
  12486. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12487. rawEl.scrollTop = rawEl.scrollHeight;
  12488. }
  12489. if (evt.type === 'reply') {
  12490. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12491. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12492. if (lossEl && evt.packet_loss_pct !== undefined) {
  12493. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12494. lossEl.className = evt.packet_loss_pct === 0
  12495. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12496. : (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');
  12497. }
  12498. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12499. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12500. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12501. }
  12502. if (badge) {
  12503. if (evt.packet_loss_pct === 0) {
  12504. 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';
  12505. badge.innerText = '100% OK';
  12506. } else {
  12507. 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';
  12508. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12509. }
  12510. }
  12511. if (tbody) {
  12512. const tr = document.createElement('tr');
  12513. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12514. tr.innerHTML = `
  12515. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12516. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12517. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12518. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12519. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12520. <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>
  12521. `;
  12522. tbody.appendChild(tr);
  12523. }
  12524. } else if (evt.type === 'timeout') {
  12525. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12526. if (lossEl && evt.packet_loss_pct !== undefined) {
  12527. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12528. 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';
  12529. }
  12530. if (badge) {
  12531. 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';
  12532. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12533. }
  12534. if (tbody) {
  12535. const tr = document.createElement('tr');
  12536. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12537. tr.innerHTML = `
  12538. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12539. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12540. <td class="py-2 px-3 text-slate-600">--</td>
  12541. <td class="py-2 px-3 text-slate-600">--</td>
  12542. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12543. <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>
  12544. `;
  12545. tbody.appendChild(tr);
  12546. }
  12547. } else if (evt.type === 'unreach') {
  12548. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12549. if (lossEl && evt.packet_loss_pct !== undefined) {
  12550. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12551. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12552. }
  12553. if (badge) {
  12554. 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';
  12555. badge.innerText = 'UNREACHABLE';
  12556. }
  12557. if (tbody) {
  12558. const tr = document.createElement('tr');
  12559. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12560. tr.innerHTML = `
  12561. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12562. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12563. <td class="py-2 px-3 text-slate-600">--</td>
  12564. <td class="py-2 px-3 text-slate-600">--</td>
  12565. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12566. <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>
  12567. `;
  12568. tbody.appendChild(tr);
  12569. }
  12570. } else if (evt.type === 'stats') {
  12571. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12572. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12573. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12574. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12575. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12576. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12577. }
  12578. } else if (evt.type === 'done') {
  12579. 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');
  12580. }
  12581. }
  12582. async function executeTraceroute(e) {
  12583. if (e) e.preventDefault();
  12584. if (tracerouteAbortController) {
  12585. tracerouteAbortController.abort();
  12586. tracerouteAbortController = null;
  12587. resetTracerouteButton();
  12588. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12589. return;
  12590. }
  12591. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12592. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12593. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12594. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12595. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12596. if (!target) {
  12597. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12598. return;
  12599. }
  12600. clearTracerouteTable();
  12601. const resCard = document.getElementById('tools-tr-results');
  12602. if (resCard) resCard.classList.remove('hidden');
  12603. tracerouteAbortController = new AbortController();
  12604. setTracerouteRunningButton();
  12605. try {
  12606. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12607. method: 'POST',
  12608. headers: { 'Content-Type': 'application/json' },
  12609. body: JSON.stringify({
  12610. target,
  12611. max_hops: maxHops,
  12612. protocol,
  12613. interface: iface,
  12614. resolve
  12615. }),
  12616. signal: tracerouteAbortController.signal
  12617. });
  12618. if (!res.ok) {
  12619. const errText = await res.text();
  12620. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12621. resetTracerouteButton();
  12622. tracerouteAbortController = null;
  12623. return;
  12624. }
  12625. const reader = res.body.getReader();
  12626. const decoder = new TextDecoder('utf-8');
  12627. let buffer = '';
  12628. while (true) {
  12629. const { done, value } = await reader.read();
  12630. if (done) break;
  12631. buffer += decoder.decode(value, { stream: true });
  12632. const blocks = buffer.split('\n\n');
  12633. buffer = blocks.pop() || '';
  12634. for (const block of blocks) {
  12635. const trimmed = block.trim();
  12636. if (!trimmed) continue;
  12637. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12638. try {
  12639. const evt = JSON.parse(line);
  12640. handleLiveTracerouteEvent(evt);
  12641. } catch (parseErr) {
  12642. console.warn('Traceroute SSE parse error:', parseErr, line);
  12643. }
  12644. }
  12645. }
  12646. } catch (err) {
  12647. if (err.name === 'AbortError') {
  12648. // User aborted normally
  12649. } else {
  12650. showToast('Traceroute Error', err.message, 'error');
  12651. }
  12652. } finally {
  12653. tracerouteAbortController = null;
  12654. resetTracerouteButton();
  12655. }
  12656. }
  12657. function handleLiveTracerouteEvent(evt) {
  12658. const statHops = document.getElementById('tools-tr-hops-count');
  12659. const tbody = document.getElementById('tools-tr-tbody');
  12660. const rawEl = document.getElementById('tools-tr-raw');
  12661. if (evt.raw && rawEl) {
  12662. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12663. rawEl.scrollTop = rawEl.scrollHeight;
  12664. }
  12665. if (evt.hops_count !== undefined && statHops) {
  12666. statHops.innerText = `${evt.hops_count} Hops`;
  12667. }
  12668. if (evt.type === 'hop' && evt.hop && tbody) {
  12669. const h = evt.hop;
  12670. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12671. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12672. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12673. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12674. const tr = document.createElement('tr');
  12675. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12676. tr.innerHTML = `
  12677. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12678. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12679. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12680. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12681. <td class="py-2.5 px-3 text-right">
  12682. ${isTimeout
  12683. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12684. : '<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>'}
  12685. </td>
  12686. `;
  12687. tbody.appendChild(tr);
  12688. } else if (evt.type === 'done') {
  12689. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12690. }
  12691. }
  12692. async function executeMTR(e) {
  12693. if (e) e.preventDefault();
  12694. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12695. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12696. if (!target) {
  12697. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12698. return;
  12699. }
  12700. const btn = document.getElementById('tools-mtr-btn');
  12701. const spinner = document.getElementById('tools-mtr-spinner');
  12702. if (btn) btn.disabled = true;
  12703. if (spinner) spinner.classList.remove('hidden');
  12704. try {
  12705. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12706. method: 'POST',
  12707. headers: { 'Content-Type': 'application/json' },
  12708. body: JSON.stringify({ target, count: cycles })
  12709. });
  12710. const data = await res.json();
  12711. if (!res.ok) {
  12712. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12713. return;
  12714. }
  12715. const resCard = document.getElementById('tools-mtr-results');
  12716. if (resCard) resCard.classList.remove('hidden');
  12717. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12718. const statHops = document.getElementById('tools-mtr-hops-count');
  12719. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12720. const tbody = document.getElementById('tools-mtr-tbody');
  12721. if (tbody) {
  12722. if (hopsCount > 0) {
  12723. tbody.innerHTML = data.hops.map(h => {
  12724. 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');
  12725. return `
  12726. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12727. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12728. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12729. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12730. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12731. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12732. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12733. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12734. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12735. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12736. </tr>
  12737. `;
  12738. }).join('');
  12739. } else {
  12740. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12741. }
  12742. }
  12743. const rawEl = document.getElementById('tools-mtr-raw');
  12744. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12745. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12746. } catch (err) {
  12747. showToast('MTR Error', err.message, 'error');
  12748. } finally {
  12749. if (btn) btn.disabled = false;
  12750. if (spinner) spinner.classList.add('hidden');
  12751. }
  12752. }
  12753. async function executeDNS(e) {
  12754. if (e) e.preventDefault();
  12755. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12756. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12757. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12758. if (!domain) {
  12759. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12760. return;
  12761. }
  12762. const btn = document.getElementById('tools-dns-btn');
  12763. const spinner = document.getElementById('tools-dns-spinner');
  12764. if (btn) btn.disabled = true;
  12765. if (spinner) spinner.classList.remove('hidden');
  12766. try {
  12767. const res = await fetch(`${API_BASE}/tools/dns`, {
  12768. method: 'POST',
  12769. headers: { 'Content-Type': 'application/json' },
  12770. body: JSON.stringify({ domain, type, server })
  12771. });
  12772. const data = await res.json();
  12773. if (!res.ok) {
  12774. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12775. return;
  12776. }
  12777. const resCard = document.getElementById('tools-dns-results');
  12778. if (resCard) resCard.classList.remove('hidden');
  12779. const metaEl = document.getElementById('tools-dns-meta');
  12780. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12781. const tbody = document.getElementById('tools-dns-tbody');
  12782. if (tbody) {
  12783. if (Array.isArray(data.records) && data.records.length > 0) {
  12784. tbody.innerHTML = data.records.map(r => `
  12785. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12786. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12787. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12788. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12789. <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>
  12790. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12791. </tr>
  12792. `).join('');
  12793. } else {
  12794. 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>`;
  12795. }
  12796. }
  12797. const rawEl = document.getElementById('tools-dns-raw');
  12798. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12799. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12800. } catch (err) {
  12801. showToast('DNS Error', err.message, 'error');
  12802. } finally {
  12803. if (btn) btn.disabled = false;
  12804. if (spinner) spinner.classList.add('hidden');
  12805. }
  12806. }
  12807. async function executePortProbe(e) {
  12808. if (e) e.preventDefault();
  12809. const target = document.getElementById('tools-port-target')?.value?.trim();
  12810. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12811. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12812. if (!target || !port) {
  12813. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12814. return;
  12815. }
  12816. const btn = document.getElementById('tools-port-btn');
  12817. const spinner = document.getElementById('tools-port-spinner');
  12818. if (btn) btn.disabled = true;
  12819. if (spinner) spinner.classList.remove('hidden');
  12820. try {
  12821. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12822. method: 'POST',
  12823. headers: { 'Content-Type': 'application/json' },
  12824. body: JSON.stringify({ target, port, timeout })
  12825. });
  12826. const data = await res.json();
  12827. if (!res.ok) {
  12828. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12829. return;
  12830. }
  12831. const resCard = document.getElementById('tools-port-results');
  12832. if (resCard) resCard.classList.remove('hidden');
  12833. const banner = document.getElementById('tools-port-banner');
  12834. const icon = document.getElementById('tools-port-icon');
  12835. const title = document.getElementById('tools-port-title');
  12836. const sub = document.getElementById('tools-port-sub');
  12837. const latency = document.getElementById('tools-port-latency');
  12838. if (data.open) {
  12839. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12840. if (icon) {
  12841. 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';
  12842. icon.innerText = '✓';
  12843. }
  12844. if (title) {
  12845. title.className = 'text-sm font-bold text-emerald-300';
  12846. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12847. }
  12848. if (sub) {
  12849. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12850. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12851. }
  12852. if (latency) {
  12853. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12854. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12855. }
  12856. } else {
  12857. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12858. if (icon) {
  12859. 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';
  12860. icon.innerText = '✕';
  12861. }
  12862. if (title) {
  12863. title.className = 'text-sm font-bold text-rose-300';
  12864. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12865. }
  12866. if (sub) {
  12867. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12868. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12869. }
  12870. if (latency) {
  12871. latency.className = 'text-base font-bold font-mono text-slate-500';
  12872. latency.innerText = '--';
  12873. }
  12874. }
  12875. const rawEl = document.getElementById('tools-port-raw');
  12876. 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'}`);
  12877. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12878. } catch (err) {
  12879. showToast('Probe Error', err.message, 'error');
  12880. } finally {
  12881. if (btn) btn.disabled = false;
  12882. if (spinner) spinner.classList.add('hidden');
  12883. }
  12884. }
  12885. // ==========================================
  12886. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12887. // ==========================================
  12888. async function loadDHCPClients(showToastMsg = false) {
  12889. try {
  12890. const [clientsRes, sumRes] = await Promise.all([
  12891. fetch(`${API_BASE}/dhcp/clients`),
  12892. fetch(`${API_BASE}/dhcp/clients/summary`)
  12893. ]);
  12894. if (clientsRes.ok) {
  12895. state.dhcpClients = await clientsRes.json();
  12896. }
  12897. if (sumRes.ok) {
  12898. state.dhcpSummary = await sumRes.json();
  12899. }
  12900. renderDHCPClients();
  12901. updateDHCPSummaryCards();
  12902. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12903. if (bDhcp && state.dhcpSummary) {
  12904. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12905. }
  12906. if (showToastMsg) {
  12907. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12908. }
  12909. } catch (err) {
  12910. console.error('Failed to load DHCP clients:', err);
  12911. if (showToastMsg) {
  12912. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12913. }
  12914. }
  12915. }
  12916. function updateDHCPSummaryCards() {
  12917. const sum = state.dhcpSummary || {
  12918. total_clients: (state.dhcpClients || []).length,
  12919. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12920. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12921. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12922. };
  12923. const totalEl = document.getElementById('dhcp-stat-total');
  12924. const boundEl = document.getElementById('dhcp-stat-bound');
  12925. const searchEl = document.getElementById('dhcp-stat-searching');
  12926. const disEl = document.getElementById('dhcp-stat-disabled');
  12927. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12928. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12929. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12930. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12931. }
  12932. function renderDHCPClients() {
  12933. const tbody = document.getElementById('dhcp-clients-tbody');
  12934. const emptyState = document.getElementById('dhcp-clients-empty');
  12935. if (!tbody) return;
  12936. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12937. if (clients.length === 0) {
  12938. tbody.innerHTML = '';
  12939. if (emptyState) emptyState.classList.remove('hidden');
  12940. return;
  12941. }
  12942. if (emptyState) emptyState.classList.add('hidden');
  12943. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12944. if (tbody.dataset.sig === sig) return;
  12945. tbody.dataset.sig = sig;
  12946. tbody.innerHTML = clients.map(c => {
  12947. let statusBadge = '';
  12948. if (!c.enabled) {
  12949. 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>';
  12950. } else if (c.status === 'bound') {
  12951. 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>';
  12952. } else if (c.status === 'searching') {
  12953. 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>';
  12954. } else if (c.status === 'stopped') {
  12955. 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>';
  12956. } else {
  12957. 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>`;
  12958. }
  12959. 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>';
  12960. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12961. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12962. 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>';
  12963. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12964. // Option flags
  12965. const flags = [];
  12966. 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>');
  12967. 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>');
  12968. 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>');
  12969. 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>`);
  12970. return `
  12971. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12972. <td class="py-3 px-4">
  12973. <div class="flex items-center gap-2">
  12974. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12975. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12976. </div>
  12977. </td>
  12978. <td class="py-3 px-4">${statusBadge}</td>
  12979. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12980. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12981. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12982. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12983. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12984. <td class="py-3 px-4">
  12985. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12986. </td>
  12987. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12988. ${c.enabled ? `
  12989. <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>
  12990. <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>
  12991. <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>
  12992. ` : `
  12993. <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>
  12994. `}
  12995. <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>
  12996. <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>
  12997. </td>
  12998. </tr>
  12999. `;
  13000. }).join('');
  13001. }
  13002. function openDHCPClientModal(clientId = null) {
  13003. const modal = document.getElementById('modal-dhcp-client');
  13004. if (!modal) return;
  13005. const title = document.getElementById('modal-dhcp-title');
  13006. const idInput = document.getElementById('modal-dhcp-id');
  13007. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13008. const distInput = document.getElementById('modal-dhcp-distance');
  13009. const commentInput = document.getElementById('modal-dhcp-comment');
  13010. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  13011. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  13012. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  13013. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  13014. // Populate interfaces
  13015. if (ifaceSelect) {
  13016. let opts = '<option value="">Select interface...</option>';
  13017. const allIfaces = state.interfaces || [];
  13018. const allVlans = state.vlans || [];
  13019. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  13020. // Group 1: Physical & Bridge Interfaces
  13021. opts += '<optgroup label="Physical & Bridge Interfaces">';
  13022. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  13023. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  13024. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  13025. });
  13026. opts += '</optgroup>';
  13027. // Group 2: VLAN Interfaces
  13028. if (allVlans.length > 0) {
  13029. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  13030. allVlans.forEach(v => {
  13031. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  13032. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  13033. });
  13034. opts += '</optgroup>';
  13035. }
  13036. ifaceSelect.innerHTML = opts;
  13037. }
  13038. if (clientId) {
  13039. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  13040. if (client) {
  13041. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  13042. if (idInput) idInput.value = client.id;
  13043. if (ifaceSelect) {
  13044. ifaceSelect.value = client.interface;
  13045. ifaceSelect.disabled = true; // interface cannot be changed on edit
  13046. }
  13047. if (distInput) distInput.value = client.default_route_distance || 1;
  13048. if (commentInput) commentInput.value = client.comment || '';
  13049. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  13050. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  13051. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  13052. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  13053. }
  13054. } else {
  13055. if (title) title.innerText = 'Add DHCP Client';
  13056. if (idInput) idInput.value = '';
  13057. if (ifaceSelect) {
  13058. ifaceSelect.value = '';
  13059. ifaceSelect.disabled = false;
  13060. }
  13061. if (distInput) distInput.value = 1;
  13062. if (commentInput) commentInput.value = '';
  13063. if (defRouteCheck) defRouteCheck.checked = true;
  13064. if (peerDnsCheck) peerDnsCheck.checked = true;
  13065. if (peerNtpCheck) peerNtpCheck.checked = true;
  13066. if (enabledCheck) enabledCheck.checked = true;
  13067. }
  13068. modal.classList.remove('hidden');
  13069. }
  13070. function openDHCPClientModalForIface(ifaceName) {
  13071. openDHCPClientModal();
  13072. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13073. if (ifaceSelect && ifaceName) {
  13074. ifaceSelect.value = ifaceName;
  13075. }
  13076. }
  13077. function closeDHCPClientModal() {
  13078. const modal = document.getElementById('modal-dhcp-client');
  13079. if (modal) modal.classList.add('hidden');
  13080. }
  13081. async function submitSaveDHCPClient(e) {
  13082. if (e) e.preventDefault();
  13083. const id = document.getElementById('modal-dhcp-id')?.value;
  13084. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  13085. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  13086. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13087. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13088. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13089. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13090. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13091. if (!id && !iface) {
  13092. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13093. return;
  13094. }
  13095. try {
  13096. let res;
  13097. if (id) {
  13098. // PUT update
  13099. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13100. method: 'PUT',
  13101. headers: { 'Content-Type': 'application/json' },
  13102. body: JSON.stringify({
  13103. enabled,
  13104. add_default_route: defRoute,
  13105. default_route_distance: distance,
  13106. use_peer_dns: peerDns,
  13107. use_peer_ntp: peerNtp,
  13108. comment
  13109. })
  13110. });
  13111. } else {
  13112. // POST create
  13113. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13114. method: 'POST',
  13115. headers: { 'Content-Type': 'application/json' },
  13116. body: JSON.stringify({
  13117. interface: iface,
  13118. enabled,
  13119. add_default_route: defRoute,
  13120. default_route_distance: distance,
  13121. use_peer_dns: peerDns,
  13122. use_peer_ntp: peerNtp,
  13123. comment
  13124. })
  13125. });
  13126. }
  13127. const data = await res.json();
  13128. if (!res.ok) {
  13129. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13130. return;
  13131. }
  13132. closeDHCPClientModal();
  13133. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13134. await loadDHCPClients();
  13135. fetchData(); // refresh interfaces list with new lease/status
  13136. } catch (err) {
  13137. showToast('Error', err.message, 'error');
  13138. }
  13139. }
  13140. async function toggleDHCPClientState(id, enabled) {
  13141. try {
  13142. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13143. method: 'POST',
  13144. headers: { 'Content-Type': 'application/json' },
  13145. body: JSON.stringify({ enabled })
  13146. });
  13147. const data = await res.json();
  13148. if (!res.ok) {
  13149. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13150. return;
  13151. }
  13152. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13153. await loadDHCPClients();
  13154. fetchData();
  13155. } catch (err) {
  13156. showToast('Error', err.message, 'error');
  13157. }
  13158. }
  13159. async function renewDHCPClient(id) {
  13160. try {
  13161. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13162. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13163. method: 'POST'
  13164. });
  13165. const data = await res.json();
  13166. if (!res.ok) {
  13167. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13168. return;
  13169. }
  13170. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13171. setTimeout(() => {
  13172. loadDHCPClients();
  13173. fetchData();
  13174. }, 1500);
  13175. } catch (err) {
  13176. showToast('Error', err.message, 'error');
  13177. }
  13178. }
  13179. async function releaseDHCPClient(id) {
  13180. try {
  13181. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13182. method: 'POST'
  13183. });
  13184. const data = await res.json();
  13185. if (!res.ok) {
  13186. showToast('Error', data.error || 'Failed to release lease', 'error');
  13187. return;
  13188. }
  13189. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13190. await loadDHCPClients();
  13191. fetchData();
  13192. } catch (err) {
  13193. showToast('Error', err.message, 'error');
  13194. }
  13195. }
  13196. async function deleteDHCPClient(id, ifaceName) {
  13197. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13198. return;
  13199. }
  13200. try {
  13201. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13202. method: 'DELETE'
  13203. });
  13204. const data = await res.json();
  13205. if (!res.ok) {
  13206. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13207. return;
  13208. }
  13209. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13210. await loadDHCPClients();
  13211. fetchData();
  13212. } catch (err) {
  13213. showToast('Error', err.message, 'error');
  13214. }
  13215. }
  13216. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13217. async function loadDHCPServer(populate = true) {
  13218. try {
  13219. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13220. fetch(`${API_BASE}/dhcp-server/summary`),
  13221. fetch(`${API_BASE}/dhcp-server/servers`),
  13222. fetch(`${API_BASE}/dhcp-server/networks`),
  13223. fetch(`${API_BASE}/dhcp-server/leases`),
  13224. fetch(`${API_BASE}/dhcp-server/options`)
  13225. ]);
  13226. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13227. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13228. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13229. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13230. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13231. const sum = state.dhcpServerSummary || {};
  13232. const srvs = state.dhcpServers || [];
  13233. const nets = state.dhcpNetworks || [];
  13234. const leases = state.dhcpLeases || [];
  13235. const opts = state.dhcpOptions || [];
  13236. // KPI Cards
  13237. const statActive = document.getElementById('dhcp-server-stat-active');
  13238. if (statActive) {
  13239. const activeCount = srvs.filter(s => s.running).length;
  13240. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13241. }
  13242. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13243. if (statLeases) {
  13244. statLeases.innerText = leases.length;
  13245. }
  13246. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13247. if (statLeasesSub) {
  13248. const dyn = leases.filter(l => l.dynamic).length;
  13249. const st = leases.filter(l => !l.dynamic).length;
  13250. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13251. }
  13252. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13253. if (statNetworks) {
  13254. statNetworks.innerText = nets.length;
  13255. }
  13256. // Subtab Badges
  13257. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13258. if (bSrv) bSrv.innerText = srvs.length;
  13259. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13260. if (bNet) bNet.innerText = nets.length;
  13261. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13262. if (bLease) bLease.innerText = leases.length;
  13263. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13264. if (bOpt) bOpt.innerText = opts.length;
  13265. // Sidebar Badge
  13266. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13267. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13268. renderCurrentDHCPServerTab();
  13269. } catch (err) {
  13270. console.error('Failed to load DHCP Server:', err);
  13271. }
  13272. }
  13273. function switchDHCPServerTab(tab) {
  13274. state.dhcpServerTab = tab;
  13275. const tabs = ['servers', 'networks', 'leases', 'options'];
  13276. tabs.forEach(t => {
  13277. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13278. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13279. if (panel) {
  13280. if (t === tab) panel.classList.remove('hidden');
  13281. else panel.classList.add('hidden');
  13282. }
  13283. if (btn) {
  13284. if (t === tab) {
  13285. 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';
  13286. } else {
  13287. 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';
  13288. }
  13289. }
  13290. });
  13291. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13292. if (addBtn) {
  13293. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13294. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13295. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13296. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13297. }
  13298. renderCurrentDHCPServerTab();
  13299. }
  13300. function handleDHCPServerPrimaryAdd() {
  13301. const tab = state.dhcpServerTab || 'servers';
  13302. if (tab === 'servers') openAddDHCPServerModal();
  13303. else if (tab === 'networks') openAddDHCPNetworkModal();
  13304. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13305. else if (tab === 'options') openAddDHCPOptionModal();
  13306. }
  13307. function renderCurrentDHCPServerTab() {
  13308. const tab = state.dhcpServerTab || 'servers';
  13309. if (tab === 'servers') renderDHCPServers();
  13310. else if (tab === 'networks') renderDHCPNetworks();
  13311. else if (tab === 'leases') renderDHCPLeases();
  13312. else if (tab === 'options') renderDHCPOptions();
  13313. }
  13314. function renderDHCPServers() {
  13315. const tbody = document.getElementById('dhcp-server-tbody');
  13316. const empty = document.getElementById('dhcp-server-empty');
  13317. if (!tbody) return;
  13318. const servers = state.dhcpServers || [];
  13319. if (servers.length === 0) {
  13320. tbody.innerHTML = '';
  13321. empty?.classList.remove('hidden');
  13322. return;
  13323. }
  13324. empty?.classList.add('hidden');
  13325. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13326. if (tbody.dataset.sig === sig) return;
  13327. tbody.dataset.sig = sig;
  13328. tbody.innerHTML = '';
  13329. servers.forEach(s => {
  13330. const tr = document.createElement('tr');
  13331. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13332. tr.innerHTML = `
  13333. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13334. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13335. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13336. <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>
  13337. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13338. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13339. <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>
  13340. <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>
  13341. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13342. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13343. <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>
  13344. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13345. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13346. </td>
  13347. `;
  13348. tbody.appendChild(tr);
  13349. });
  13350. }
  13351. function renderDHCPNetworks() {
  13352. const tbody = document.getElementById('dhcp-networks-tbody');
  13353. const empty = document.getElementById('dhcp-networks-empty');
  13354. if (!tbody) return;
  13355. tbody.innerHTML = '';
  13356. const networks = state.dhcpNetworks || [];
  13357. if (networks.length === 0) {
  13358. empty?.classList.remove('hidden');
  13359. return;
  13360. }
  13361. empty?.classList.add('hidden');
  13362. networks.forEach(n => {
  13363. const tr = document.createElement('tr');
  13364. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13365. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13366. const optionsChips = (n.dhcp_options || []).map(optId => {
  13367. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13368. if (!opt) return '';
  13369. return `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-slate-700 inline-block mr-1 mb-0.5" title="${escapeHtml(opt.name)}: ${escapeHtml(opt.value)}">#${opt.code} ${escapeHtml(opt.name)}</span>`;
  13370. }).filter(Boolean).join('');
  13371. tr.innerHTML = `
  13372. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13373. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13374. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13375. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13376. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13377. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13378. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13379. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13380. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13381. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13382. </td>
  13383. `;
  13384. tbody.appendChild(tr);
  13385. });
  13386. }
  13387. function renderDHCPLeases() {
  13388. const tbody = document.getElementById('dhcp-leases-tbody');
  13389. const empty = document.getElementById('dhcp-leases-empty');
  13390. if (!tbody) return;
  13391. tbody.innerHTML = '';
  13392. const leases = state.dhcpLeases || [];
  13393. if (leases.length === 0) {
  13394. empty?.classList.remove('hidden');
  13395. return;
  13396. }
  13397. empty?.classList.add('hidden');
  13398. leases.forEach(l => {
  13399. const tr = document.createElement('tr');
  13400. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13401. 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>';
  13402. const statusBadge = l.status === 'bound'
  13403. ? '<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>'
  13404. : l.status === 'static'
  13405. ? '<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>'
  13406. : '<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>';
  13407. const makeStaticBtn = l.dynamic
  13408. ? `<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>`
  13409. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13410. tr.innerHTML = `
  13411. <td class="py-2.5 px-3 text-center">${flag}</td>
  13412. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13413. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13414. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13415. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13416. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13417. <td class="py-2.5 px-3">${statusBadge}</td>
  13418. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13419. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13420. ${makeStaticBtn}
  13421. </td>
  13422. `;
  13423. tbody.appendChild(tr);
  13424. });
  13425. }
  13426. function renderDHCPOptions() {
  13427. const tbody = document.getElementById('dhcp-options-tbody');
  13428. const empty = document.getElementById('dhcp-options-empty');
  13429. if (!tbody) return;
  13430. tbody.innerHTML = '';
  13431. const options = state.dhcpOptions || [];
  13432. if (options.length === 0) {
  13433. empty?.classList.remove('hidden');
  13434. return;
  13435. }
  13436. empty?.classList.add('hidden');
  13437. options.forEach(o => {
  13438. const tr = document.createElement('tr');
  13439. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13440. tr.innerHTML = `
  13441. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13442. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13443. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13444. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13445. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13446. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13447. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13448. </td>
  13449. `;
  13450. tbody.appendChild(tr);
  13451. });
  13452. }
  13453. // ==================== MODALS & ACTIONS: SERVER ====================
  13454. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13455. const sel = document.getElementById(elemId);
  13456. if (!sel) return;
  13457. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13458. const networks = state.dhcpNetworks || [];
  13459. networks.forEach(n => {
  13460. const opt = document.createElement('option');
  13461. opt.value = n.address;
  13462. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13463. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13464. opt.selected = true;
  13465. }
  13466. sel.appendChild(opt);
  13467. });
  13468. }
  13469. function onDHCPServerNetworkChange() {
  13470. const netSel = document.getElementById('dhcp-server-modal-network');
  13471. if (!netSel) return;
  13472. const netVal = netSel.value;
  13473. if (!netVal) return;
  13474. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13475. if (!poolInput) return;
  13476. // Auto-calculate suggested address pool based on subnet CIDR
  13477. const parts = netVal.split('/');
  13478. const ip = parts[0];
  13479. const cidr = parseInt(parts[1] || '24', 10);
  13480. if (cidr === 24) {
  13481. const octets = ip.split('.');
  13482. if (octets.length === 4) {
  13483. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13484. poolInput.value = `${base}.10-${base}.254`;
  13485. }
  13486. }
  13487. }
  13488. function openAddDHCPServerModal() {
  13489. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13490. document.getElementById('dhcp-server-modal-id').value = '';
  13491. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13492. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13493. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13494. document.getElementById('dhcp-server-modal-comment').value = '';
  13495. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13496. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13497. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13498. const networks = state.dhcpNetworks || [];
  13499. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13500. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13501. if (defaultNet) {
  13502. onDHCPServerNetworkChange();
  13503. }
  13504. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13505. }
  13506. function openEditDHCPServerModal(id) {
  13507. const s = (state.dhcpServers || []).find(item => item.id === id);
  13508. if (!s) return;
  13509. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13510. document.getElementById('dhcp-server-modal-id').value = s.id;
  13511. document.getElementById('dhcp-server-modal-name').value = s.name;
  13512. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13513. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13514. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13515. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13516. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13517. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13518. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13519. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13520. }
  13521. function closeDHCPServerModal() {
  13522. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13523. }
  13524. async function submitSaveDHCPServer(e) {
  13525. e.preventDefault();
  13526. const id = document.getElementById('dhcp-server-modal-id').value;
  13527. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13528. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13529. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13530. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13531. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13532. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13533. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13534. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13535. try {
  13536. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13537. method: 'POST',
  13538. headers: { 'Content-Type': 'application/json' },
  13539. body: JSON.stringify({
  13540. id,
  13541. name,
  13542. interface: iface,
  13543. network,
  13544. address_pool: pool,
  13545. lease_time: leaseTime,
  13546. authoritative,
  13547. disabled,
  13548. comment
  13549. })
  13550. });
  13551. if (res.ok) {
  13552. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13553. closeDHCPServerModal();
  13554. loadDHCPServer(false);
  13555. fetchData(false);
  13556. } else {
  13557. const err = await res.text();
  13558. showToast('Error', err, 'error');
  13559. }
  13560. } catch (err) {
  13561. showToast('Error', err.message, 'error');
  13562. }
  13563. }
  13564. async function toggleDHCPServerState(id, disabled) {
  13565. try {
  13566. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13567. method: 'POST',
  13568. headers: { 'Content-Type': 'application/json' },
  13569. body: JSON.stringify({ disabled })
  13570. });
  13571. if (res.ok) {
  13572. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13573. loadDHCPServer(false);
  13574. fetchData(false);
  13575. }
  13576. } catch (err) {
  13577. showToast('Error', err.message, 'error');
  13578. }
  13579. }
  13580. async function deleteDHCPServer(id, name) {
  13581. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13582. try {
  13583. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13584. if (res.ok) {
  13585. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13586. loadDHCPServer(false);
  13587. fetchData(false);
  13588. }
  13589. } catch (err) {
  13590. showToast('Error', err.message, 'error');
  13591. }
  13592. }
  13593. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13594. function openAddDHCPNetworkModal() {
  13595. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13596. document.getElementById('dhcp-network-modal-id').value = '';
  13597. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13598. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13599. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13600. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13601. document.getElementById('dhcp-network-modal-netmask').value = '';
  13602. document.getElementById('dhcp-network-modal-comment').value = '';
  13603. renderDHCPNetworkOptionsCheckboxes([]);
  13604. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13605. }
  13606. function openEditDHCPNetworkModal(id) {
  13607. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13608. if (!n) return;
  13609. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13610. document.getElementById('dhcp-network-modal-id').value = n.id;
  13611. document.getElementById('dhcp-network-modal-address').value = n.address;
  13612. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13613. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13614. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13615. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13616. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13617. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13618. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13619. }
  13620. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13621. const container = document.getElementById('dhcp-network-modal-options-list');
  13622. if (!container) return;
  13623. container.innerHTML = '';
  13624. const opts = state.dhcpOptions || [];
  13625. if (opts.length === 0) {
  13626. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13627. return;
  13628. }
  13629. opts.forEach(o => {
  13630. const isChecked = selectedIds.includes(o.id);
  13631. const label = document.createElement('label');
  13632. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13633. label.innerHTML = `
  13634. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13635. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13636. `;
  13637. container.appendChild(label);
  13638. });
  13639. }
  13640. function closeDHCPNetworkModal() {
  13641. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13642. }
  13643. async function submitSaveDHCPNetwork(e) {
  13644. e.preventDefault();
  13645. const id = document.getElementById('dhcp-network-modal-id').value;
  13646. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13647. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13648. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13649. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13650. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13651. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13652. const selectedOpts = [];
  13653. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13654. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13655. try {
  13656. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13657. method: 'POST',
  13658. headers: { 'Content-Type': 'application/json' },
  13659. body: JSON.stringify({
  13660. id,
  13661. address,
  13662. gateway,
  13663. netmask,
  13664. dns_servers: dnsServers,
  13665. domain,
  13666. dhcp_options: selectedOpts,
  13667. comment
  13668. })
  13669. });
  13670. if (res.ok) {
  13671. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13672. closeDHCPNetworkModal();
  13673. loadDHCPServer(false);
  13674. fetchData(false);
  13675. } else {
  13676. const err = await res.text();
  13677. showToast('Error', err, 'error');
  13678. }
  13679. } catch (err) {
  13680. showToast('Error', err.message, 'error');
  13681. }
  13682. }
  13683. async function deleteDHCPNetwork(id, addr) {
  13684. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13685. try {
  13686. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13687. if (res.ok) {
  13688. showToast('Deleted', `Network ${addr} removed`, 'success');
  13689. loadDHCPServer(false);
  13690. fetchData(false);
  13691. }
  13692. } catch (err) {
  13693. showToast('Error', err.message, 'error');
  13694. }
  13695. }
  13696. // ==================== MODALS & ACTIONS: LEASES ====================
  13697. function openAddDHCPStaticLeaseModal() {
  13698. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13699. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13700. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13701. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13702. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13703. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13704. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13705. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13706. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13707. }
  13708. function closeDHCPStaticLeaseModal() {
  13709. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13710. }
  13711. async function submitSaveDHCPStaticLease(e) {
  13712. e.preventDefault();
  13713. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13714. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13715. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13716. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13717. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13718. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13719. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13720. try {
  13721. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13722. method: 'POST',
  13723. headers: { 'Content-Type': 'application/json' },
  13724. body: JSON.stringify({
  13725. id,
  13726. mac_address: mac,
  13727. address: ip,
  13728. hostname,
  13729. server,
  13730. comment,
  13731. disabled
  13732. })
  13733. });
  13734. if (res.ok) {
  13735. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13736. closeDHCPStaticLeaseModal();
  13737. loadDHCPServer(false);
  13738. fetchData(false);
  13739. } else {
  13740. const err = await res.text();
  13741. showToast('Error', err, 'error');
  13742. }
  13743. } catch (err) {
  13744. showToast('Error', err.message, 'error');
  13745. }
  13746. }
  13747. async function deleteDHCPStaticLease(id) {
  13748. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13749. try {
  13750. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13751. if (res.ok) {
  13752. showToast('Deleted', 'Static lease removed', 'success');
  13753. loadDHCPServer(false);
  13754. fetchData(false);
  13755. }
  13756. } catch (err) {
  13757. showToast('Error', err.message, 'error');
  13758. }
  13759. }
  13760. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13761. try {
  13762. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13763. method: 'POST',
  13764. headers: { 'Content-Type': 'application/json' },
  13765. body: JSON.stringify({
  13766. mac_address: mac,
  13767. address: ip,
  13768. hostname,
  13769. comment: comment || 'Converted to static'
  13770. })
  13771. });
  13772. if (res.ok) {
  13773. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13774. loadDHCPServer(false);
  13775. fetchData(false);
  13776. } else {
  13777. const err = await res.text();
  13778. showToast('Error', err, 'error');
  13779. }
  13780. } catch (err) {
  13781. showToast('Error', err.message, 'error');
  13782. }
  13783. }
  13784. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13785. function openAddDHCPOptionModal() {
  13786. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13787. document.getElementById('dhcp-option-modal-id').value = '';
  13788. document.getElementById('dhcp-option-modal-name').value = '';
  13789. document.getElementById('dhcp-option-modal-code').value = '';
  13790. document.getElementById('dhcp-option-modal-value').value = '';
  13791. document.getElementById('dhcp-option-modal-comment').value = '';
  13792. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13793. }
  13794. function openEditDHCPOptionModal(id) {
  13795. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13796. if (!o) return;
  13797. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13798. document.getElementById('dhcp-option-modal-id').value = o.id;
  13799. document.getElementById('dhcp-option-modal-name').value = o.name;
  13800. document.getElementById('dhcp-option-modal-code').value = o.code;
  13801. document.getElementById('dhcp-option-modal-value').value = o.value;
  13802. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13803. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13804. }
  13805. function closeDHCPOptionModal() {
  13806. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13807. }
  13808. async function submitSaveDHCPOption(e) {
  13809. e.preventDefault();
  13810. const id = document.getElementById('dhcp-option-modal-id').value;
  13811. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13812. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13813. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13814. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13815. try {
  13816. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13817. method: 'POST',
  13818. headers: { 'Content-Type': 'application/json' },
  13819. body: JSON.stringify({ id, name, code, value, comment })
  13820. });
  13821. if (res.ok) {
  13822. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13823. closeDHCPOptionModal();
  13824. loadDHCPServer(false);
  13825. fetchData(false);
  13826. } else {
  13827. const err = await res.text();
  13828. showToast('Error', err, 'error');
  13829. }
  13830. } catch (err) {
  13831. showToast('Error', err.message, 'error');
  13832. }
  13833. }
  13834. async function deleteDHCPOption(id, name) {
  13835. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13836. try {
  13837. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13838. if (res.ok) {
  13839. showToast('Deleted', `Option ${name} removed`, 'success');
  13840. loadDHCPServer(false);
  13841. fetchData(false);
  13842. }
  13843. } catch (err) {
  13844. showToast('Error', err.message, 'error');
  13845. }
  13846. }
  13847. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13848. function openDHCPServerSetupModal() {
  13849. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13850. onDHCPWizardIfaceChange();
  13851. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13852. }
  13853. function closeDHCPServerSetupModal() {
  13854. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13855. }
  13856. function onDHCPWizardIfaceChange() {
  13857. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13858. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13859. let ip = '192.168.88.1';
  13860. let prefix = '24';
  13861. if (iface && iface.ip_address) {
  13862. const parts = iface.ip_address.split('/');
  13863. ip = parts[0];
  13864. if (parts.length > 1) prefix = parts[1];
  13865. }
  13866. // Calculate subnet base (e.g. 192.168.88.0/24)
  13867. const ipParts = ip.split('.');
  13868. if (ipParts.length === 4) {
  13869. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13870. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13871. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13872. document.getElementById('dhcp-wizard-gateway').value = ip;
  13873. document.getElementById('dhcp-wizard-pool').value = pool;
  13874. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13875. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13876. }
  13877. }
  13878. async function submitDHCPServerSetupWizard(e) {
  13879. e.preventDefault();
  13880. const iface = document.getElementById('dhcp-wizard-iface').value;
  13881. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13882. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13883. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13884. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13885. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13886. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13887. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13888. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13889. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13890. try {
  13891. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13892. method: 'POST',
  13893. headers: { 'Content-Type': 'application/json' },
  13894. body: JSON.stringify({
  13895. interface: iface,
  13896. address_space: space,
  13897. gateway: gw,
  13898. address_pool: pool,
  13899. dns_servers: dnsServers,
  13900. lease_time: leaseTime,
  13901. ntp_servers: ntpServers,
  13902. next_server: tftp
  13903. })
  13904. });
  13905. if (res.ok) {
  13906. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13907. closeDHCPServerSetupModal();
  13908. loadDHCPServer(false);
  13909. fetchData(false);
  13910. } else {
  13911. const err = await res.text();
  13912. showToast('Error', err, 'error');
  13913. }
  13914. } catch (err) {
  13915. showToast('Error', err.message, 'error');
  13916. }
  13917. }
  13918. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13919. const sel = document.getElementById(elemId);
  13920. if (!sel) return;
  13921. sel.innerHTML = '<option value="">Select interface...</option>';
  13922. const ifaces = state.interfaces || [];
  13923. ifaces.forEach(i => {
  13924. if (i.name === 'lo') return;
  13925. const opt = document.createElement('option');
  13926. opt.value = i.name;
  13927. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13928. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13929. if (i.name === selectedVal) opt.selected = true;
  13930. sel.appendChild(opt);
  13931. });
  13932. }
  13933. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13934. function initTableSorting() {
  13935. document.querySelectorAll('table').forEach(setupSortableTable);
  13936. }
  13937. function setupSortableTable(table) {
  13938. const thead = table.querySelector('thead');
  13939. const tbody = table.querySelector('tbody');
  13940. if (!thead || !tbody) return;
  13941. const headerRows = thead.querySelectorAll('tr');
  13942. if (headerRows.length === 0) return;
  13943. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13944. ths.forEach((th, colIdx) => {
  13945. if (th._sortBound) return;
  13946. th._sortBound = true;
  13947. const rawText = th.innerText.trim().toLowerCase();
  13948. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13949. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13950. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13951. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13952. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13953. return;
  13954. }
  13955. th.classList.add('table-sortable', 'group');
  13956. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13957. let icon = th.querySelector('.table-sort-icon');
  13958. if (!icon) {
  13959. icon = document.createElement('span');
  13960. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13961. icon.innerHTML = '⇅';
  13962. th.appendChild(icon);
  13963. }
  13964. th.addEventListener('click', (e) => {
  13965. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13966. handleHeaderClick(table, th, colIdx);
  13967. });
  13968. });
  13969. if (!tbody._sortObserved) {
  13970. tbody._sortObserved = true;
  13971. let sortDebounceTimer = null;
  13972. const observer = new MutationObserver((mutations) => {
  13973. if (tbody._isSorting) return;
  13974. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13975. if (!hasChildChanges) return;
  13976. clearTimeout(sortDebounceTimer);
  13977. sortDebounceTimer = setTimeout(() => {
  13978. if (tbody._isSorting) return;
  13979. if (table._activeSort && table._activeSort.dir !== 'none') {
  13980. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13981. } else {
  13982. tagOriginalRowOrder(tbody);
  13983. }
  13984. }, 50);
  13985. });
  13986. tbody._sortObserver = observer;
  13987. observer.observe(tbody, { childList: true });
  13988. }
  13989. tagOriginalRowOrder(tbody);
  13990. }
  13991. function tagOriginalRowOrder(tbody) {
  13992. let idx = 0;
  13993. Array.from(tbody.children).forEach(tr => {
  13994. if (!tr.querySelector('td[colspan]')) {
  13995. if (!tr.hasAttribute('data-orig-idx')) {
  13996. tr.setAttribute('data-orig-idx', idx++);
  13997. }
  13998. }
  13999. });
  14000. }
  14001. function handleHeaderClick(table, th, colIdx) {
  14002. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  14003. let newDir = 'asc';
  14004. if (currentSort.colIdx === colIdx) {
  14005. if (currentSort.dir === 'asc') newDir = 'desc';
  14006. else if (currentSort.dir === 'desc') newDir = 'none';
  14007. else newDir = 'asc';
  14008. } else {
  14009. newDir = 'asc';
  14010. }
  14011. table._activeSort = { colIdx, dir: newDir };
  14012. updateHeaderIcons(table, colIdx, newDir);
  14013. applyTableSort(table, colIdx, newDir, true);
  14014. }
  14015. function updateHeaderIcons(table, activeColIdx, dir) {
  14016. const thead = table.querySelector('thead');
  14017. if (!thead) return;
  14018. const ths = thead.querySelectorAll('th');
  14019. ths.forEach((th, idx) => {
  14020. const icon = th.querySelector('.table-sort-icon');
  14021. if (!icon) return;
  14022. if (idx === activeColIdx && dir !== 'none') {
  14023. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  14024. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  14025. th.classList.add('table-sorted-active');
  14026. } else {
  14027. icon.innerHTML = '⇅';
  14028. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  14029. th.classList.remove('table-sorted-active');
  14030. }
  14031. });
  14032. }
  14033. function applyTableSort(table, colIdx, dir, userInitiated) {
  14034. const tbody = table.querySelector('tbody');
  14035. if (!tbody || tbody.children.length <= 1) return;
  14036. tbody._isSorting = true;
  14037. tagOriginalRowOrder(tbody);
  14038. // Group parent rows and any attached drawer/sub-rows
  14039. const groups = [];
  14040. let currentGroup = null;
  14041. Array.from(tbody.children).forEach(tr => {
  14042. if (tr.querySelector('td[colspan]')) {
  14043. if (currentGroup) {
  14044. currentGroup.subRows.push(tr);
  14045. } else {
  14046. groups.push({ mainRow: tr, subRows: [] });
  14047. }
  14048. } else {
  14049. currentGroup = { mainRow: tr, subRows: [] };
  14050. groups.push(currentGroup);
  14051. }
  14052. });
  14053. if (dir === 'none') {
  14054. groups.sort((a, b) => {
  14055. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14056. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14057. return idxA - idxB;
  14058. });
  14059. } else {
  14060. groups.sort((a, b) => {
  14061. const cellA = a.mainRow.children[colIdx];
  14062. const cellB = b.mainRow.children[colIdx];
  14063. const res = compareTableCells(cellA, cellB);
  14064. return dir === 'asc' ? res : -res;
  14065. });
  14066. }
  14067. // Check if rows are already in correct order to avoid modifying DOM
  14068. let alreadyOrdered = true;
  14069. let childIdx = 0;
  14070. for (const g of groups) {
  14071. if (tbody.children[childIdx] !== g.mainRow) {
  14072. alreadyOrdered = false;
  14073. break;
  14074. }
  14075. childIdx++;
  14076. for (const sub of g.subRows) {
  14077. if (tbody.children[childIdx] !== sub) {
  14078. alreadyOrdered = false;
  14079. break;
  14080. }
  14081. childIdx++;
  14082. }
  14083. }
  14084. if (alreadyOrdered) {
  14085. tbody._isSorting = false;
  14086. return;
  14087. }
  14088. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14089. if (tbody._sortObserver) {
  14090. tbody._sortObserver.disconnect();
  14091. }
  14092. // Re-append rows in sorted order
  14093. groups.forEach(g => {
  14094. tbody.appendChild(g.mainRow);
  14095. g.subRows.forEach(sub => tbody.appendChild(sub));
  14096. });
  14097. // Drain any queued mutations and re-connect observer
  14098. if (tbody._sortObserver) {
  14099. tbody._sortObserver.takeRecords();
  14100. tbody._sortObserver.observe(tbody, { childList: true });
  14101. }
  14102. tbody._isSorting = false;
  14103. }
  14104. function getCellRawText(cell) {
  14105. if (!cell) return '';
  14106. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14107. const input = cell.querySelector('input, select');
  14108. if (input) {
  14109. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14110. return input.value;
  14111. }
  14112. return cell.innerText.trim();
  14113. }
  14114. function parseTrafficToNumber(str) {
  14115. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14116. if (!m) return null;
  14117. const num = parseFloat(m[1].replace(/,/g, ''));
  14118. if (isNaN(num)) return null;
  14119. const unit = m[2].toUpperCase();
  14120. let mult = 1;
  14121. if (unit.startsWith('K')) mult = 1024;
  14122. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14123. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14124. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14125. return num * mult;
  14126. }
  14127. function parseIpToNumber(str) {
  14128. const clean = str.replace(/^[!~]/, '').trim();
  14129. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14130. if (!m) return null;
  14131. const o1 = parseInt(m[1], 10);
  14132. const o2 = parseInt(m[2], 10);
  14133. const o3 = parseInt(m[3], 10);
  14134. const o4 = parseInt(m[4], 10);
  14135. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14136. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14137. }
  14138. function parseCompoundPackets(str) {
  14139. const m = str.match(/^([\d,]+)p/);
  14140. if (!m) return null;
  14141. return parseInt(m[1].replace(/,/g, ''), 10);
  14142. }
  14143. function compareTableCells(cellA, cellB) {
  14144. const a = getCellRawText(cellA);
  14145. const b = getCellRawText(cellB);
  14146. if (a === '' && b !== '') return 1;
  14147. if (b === '' && a !== '') return -1;
  14148. if (a === b) return 0;
  14149. // 1. IP Addresses / CIDR
  14150. const ipA = parseIpToNumber(a);
  14151. const ipB = parseIpToNumber(b);
  14152. if (ipA !== null && ipB !== null) return ipA - ipB;
  14153. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14154. const pktA = parseCompoundPackets(a);
  14155. const pktB = parseCompoundPackets(b);
  14156. if (pktA !== null && pktB !== null) return pktA - pktB;
  14157. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14158. const trafA = parseTrafficToNumber(a);
  14159. const trafB = parseTrafficToNumber(b);
  14160. if (trafA !== null && trafB !== null) return trafA - trafB;
  14161. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14162. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14163. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14164. const numA = Number(cleanNumA);
  14165. const numB = Number(cleanNumB);
  14166. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14167. return numA - numB;
  14168. }
  14169. // 5. Natural case-insensitive string compare
  14170. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14171. }
  14172. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14173. async function loadVRRP(showToastNotification = false) {
  14174. try {
  14175. const [instRes, sumRes] = await Promise.all([
  14176. fetch(`${API_BASE}/vrrp/instances`),
  14177. fetch(`${API_BASE}/vrrp/summary`)
  14178. ]);
  14179. if (instRes.ok) {
  14180. state.vrrpInstances = await instRes.json();
  14181. renderVRRP();
  14182. }
  14183. if (sumRes.ok) {
  14184. state.vrrpSummary = await sumRes.json();
  14185. renderVRRPSummary();
  14186. }
  14187. if (showToastNotification) {
  14188. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14189. }
  14190. } catch (err) {
  14191. console.error('Failed to load VRRP:', err);
  14192. }
  14193. }
  14194. function renderVRRPSummary() {
  14195. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14196. const elTotal = document.getElementById('vrrp-stat-total');
  14197. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14198. const elMaster = document.getElementById('vrrp-stat-master');
  14199. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14200. const elBackup = document.getElementById('vrrp-stat-backup');
  14201. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14202. const bCount = document.getElementById('badge-vrrp-count');
  14203. if (bCount) bCount.innerText = s.total_instances || 0;
  14204. const dot = document.getElementById('badge-vrrp-dot');
  14205. if (dot) {
  14206. if (s.master_instances > 0) {
  14207. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14208. } else if (s.backup_instances > 0) {
  14209. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14210. } else {
  14211. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14212. }
  14213. }
  14214. }
  14215. function renderVRRP() {
  14216. const tbody = document.getElementById('vrrp-table-tbody');
  14217. const empty = document.getElementById('vrrp-table-empty');
  14218. if (!tbody) return;
  14219. tbody.innerHTML = '';
  14220. const instances = state.vrrpInstances || [];
  14221. if (instances.length === 0) {
  14222. empty?.classList.remove('hidden');
  14223. return;
  14224. }
  14225. empty?.classList.add('hidden');
  14226. instances.forEach(inst => {
  14227. const tr = document.createElement('tr');
  14228. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14229. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14230. 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>`;
  14231. if (inst.disabled) {
  14232. 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>`;
  14233. } else if (inst.state === 'MASTER') {
  14234. 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>`;
  14235. } else if (inst.state === 'BACKUP') {
  14236. 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>`;
  14237. } else if (inst.state === 'FAULT') {
  14238. 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>`;
  14239. }
  14240. // Render State Badge
  14241. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14242. if (!inst.disabled) {
  14243. if (inst.state === 'MASTER') {
  14244. 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>`;
  14245. } else if (inst.state === 'BACKUP') {
  14246. 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>`;
  14247. } else if (inst.state === 'FAULT') {
  14248. 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>`;
  14249. }
  14250. }
  14251. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14252. tr.innerHTML = `
  14253. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14254. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14255. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14256. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14257. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14258. <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>
  14259. <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>
  14260. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14261. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14262. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14263. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14264. <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>
  14265. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14266. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14267. </td>
  14268. `;
  14269. tbody.appendChild(tr);
  14270. });
  14271. }
  14272. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14273. const sel = document.getElementById(elemId);
  14274. if (!sel) return;
  14275. sel.innerHTML = '<option value="">Select interface...</option>';
  14276. const ifaces = state.interfaces || [];
  14277. ifaces.forEach(i => {
  14278. const opt = document.createElement('option');
  14279. opt.value = i.name;
  14280. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14281. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14282. sel.appendChild(opt);
  14283. });
  14284. }
  14285. function openAddVRRPModal() {
  14286. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14287. document.getElementById('modal-vrrp-id').value = '';
  14288. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14289. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14290. document.getElementById('modal-vrrp-priority').value = 100;
  14291. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14292. document.getElementById('modal-vrrp-version').value = '3';
  14293. document.getElementById('modal-vrrp-interval').value = 1;
  14294. document.getElementById('modal-vrrp-authtype').value = 'none';
  14295. document.getElementById('modal-vrrp-authpass').value = '';
  14296. document.getElementById('modal-vrrp-comment').value = '';
  14297. document.getElementById('modal-vrrp-preempt').checked = true;
  14298. document.getElementById('modal-vrrp-disabled').checked = false;
  14299. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14300. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14301. }
  14302. function openEditVRRPModal(id) {
  14303. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14304. if (!inst) return;
  14305. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14306. document.getElementById('modal-vrrp-id').value = inst.id;
  14307. document.getElementById('modal-vrrp-name').value = inst.name;
  14308. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14309. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14310. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14311. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14312. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14313. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14314. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14315. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14316. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14317. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14318. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14319. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14320. }
  14321. function closeVRRPModal() {
  14322. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14323. }
  14324. async function submitSaveVRRP(e) {
  14325. e.preventDefault();
  14326. const id = document.getElementById('modal-vrrp-id').value;
  14327. const name = document.getElementById('modal-vrrp-name').value.trim();
  14328. const iface = document.getElementById('modal-vrrp-iface').value;
  14329. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14330. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14331. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14332. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14333. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14334. const authType = document.getElementById('modal-vrrp-authtype').value;
  14335. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14336. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14337. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14338. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14339. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14340. try {
  14341. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14342. method: 'POST',
  14343. headers: { 'Content-Type': 'application/json' },
  14344. body: JSON.stringify({
  14345. id,
  14346. name,
  14347. interface: iface,
  14348. vrid,
  14349. priority,
  14350. virtual_ips: vips,
  14351. version,
  14352. interval,
  14353. auth_type: authType,
  14354. auth_password: authPass,
  14355. comment,
  14356. preempt,
  14357. disabled
  14358. })
  14359. });
  14360. if (res.ok) {
  14361. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14362. closeVRRPModal();
  14363. loadVRRP(false);
  14364. fetchData(false);
  14365. } else {
  14366. const err = await res.text();
  14367. showToast('Error', err, 'error');
  14368. }
  14369. } catch (err) {
  14370. showToast('Error', err.message, 'error');
  14371. }
  14372. }
  14373. async function deleteVRRP(id, name) {
  14374. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14375. try {
  14376. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14377. if (res.ok) {
  14378. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14379. loadVRRP(false);
  14380. fetchData(false);
  14381. } else {
  14382. const err = await res.text();
  14383. showToast('Error', err, 'error');
  14384. }
  14385. } catch (err) {
  14386. showToast('Error', err.message, 'error');
  14387. }
  14388. }
  14389. async function toggleVRRPState(id, disabled) {
  14390. try {
  14391. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14392. method: 'POST',
  14393. headers: { 'Content-Type': 'application/json' },
  14394. body: JSON.stringify({ disabled })
  14395. });
  14396. if (res.ok) {
  14397. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14398. loadVRRP(false);
  14399. fetchData(false);
  14400. } else {
  14401. const err = await res.text();
  14402. showToast('Error', err, 'error');
  14403. }
  14404. } catch (err) {
  14405. showToast('Error', err.message, 'error');
  14406. }
  14407. }
  14408. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14409. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14410. let docSortDebounce = null;
  14411. const docTableObserver = new MutationObserver((mutations) => {
  14412. let needsInit = false;
  14413. for (const m of mutations) {
  14414. for (const node of m.addedNodes) {
  14415. if (node.nodeType === 1) {
  14416. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14417. needsInit = true;
  14418. break;
  14419. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14420. needsInit = true;
  14421. break;
  14422. }
  14423. }
  14424. }
  14425. if (needsInit) break;
  14426. }
  14427. if (needsInit) {
  14428. clearTimeout(docSortDebounce);
  14429. docSortDebounce = setTimeout(initTableSorting, 100);
  14430. }
  14431. });
  14432. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14433. }
  14434. // =========================================================================
  14435. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14436. // =========================================================================
  14437. const bwtestState = {
  14438. running: false,
  14439. pollTimer: null,
  14440. eventSource: null,
  14441. chartPoints: [],
  14442. maxChartPoints: 60,
  14443. serverConfig: null,
  14444. peakTx: 0,
  14445. peakRx: 0,
  14446. targetDuration: 10,
  14447. lastSampleElapsed: -1,
  14448. sessionID: null
  14449. };
  14450. async function loadBwTestView() {
  14451. resizeBwTestCanvas();
  14452. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14453. }
  14454. async function fetchBwTestServerStatus() {
  14455. try {
  14456. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14457. if (!res.ok) return;
  14458. const s = await res.json();
  14459. bwtestState.serverConfig = s;
  14460. // Update indicator and badges
  14461. const indicator = document.getElementById('bwtest-server-indicator');
  14462. const badge = document.getElementById('bwtest-server-badge');
  14463. const sideBadge = document.getElementById('badge-bwtest-server');
  14464. if (s.enabled && s.running) {
  14465. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14466. if (badge) {
  14467. badge.innerText = `Port ${s.port} (Active)`;
  14468. badge.className = 'text-emerald-400 font-bold';
  14469. }
  14470. if (sideBadge) {
  14471. sideBadge.innerText = s.port;
  14472. 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';
  14473. }
  14474. } else {
  14475. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14476. if (badge) {
  14477. badge.innerText = `Disabled`;
  14478. badge.className = 'text-slate-500 font-bold';
  14479. }
  14480. if (sideBadge) {
  14481. sideBadge.innerText = 'Off';
  14482. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14483. }
  14484. }
  14485. // Modal fields
  14486. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14487. const serverModal = document.getElementById('modal-bwtest-server');
  14488. const editing = serverModal && !serverModal.classList.contains('hidden');
  14489. if (toggle && !editing) toggle.checked = !!s.enabled;
  14490. const portInp = document.getElementById('bwtest-server-port-input');
  14491. if (portInp && !editing) portInp.value = s.port || 2000;
  14492. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14493. if (actSess) actSess.innerText = s.active_sessions || 0;
  14494. const totServ = document.getElementById('bwtest-modal-total-served');
  14495. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14496. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14497. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14498. } catch (err) {
  14499. console.error('Failed to fetch BwTest server status:', err);
  14500. }
  14501. }
  14502. function openBwTestServerModal() {
  14503. const cfg = bwtestState.serverConfig;
  14504. if (cfg) {
  14505. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14506. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14507. }
  14508. fetchBwTestServerStatus();
  14509. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14510. }
  14511. function closeBwTestServerModal() {
  14512. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14513. }
  14514. async function submitBwTestServerSettings(e) {
  14515. e.preventDefault();
  14516. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14517. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14518. try {
  14519. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14520. method: 'POST',
  14521. headers: { 'Content-Type': 'application/json' },
  14522. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14523. });
  14524. if (!res.ok) {
  14525. const err = await res.json();
  14526. throw new Error(err.error || 'Failed to update server configuration');
  14527. }
  14528. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14529. closeBwTestServerModal();
  14530. fetchBwTestServerStatus();
  14531. } catch (err) {
  14532. showToast('Server Configuration Error', err.message, 'error');
  14533. }
  14534. }
  14535. function setBwTestTarget(target) {
  14536. const inp = document.getElementById('bwtest-input-target');
  14537. if (inp) inp.value = target;
  14538. }
  14539. function setBwTestProtocol(proto) {
  14540. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14541. if (hiddenInp) hiddenInp.value = proto;
  14542. const btnUdp = document.getElementById('bwtest-proto-udp');
  14543. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14544. const badge = document.getElementById('bwtest-proto-badge');
  14545. const pktField = document.getElementById('bwtest-field-pktsize');
  14546. 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';
  14547. 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';
  14548. 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';
  14549. if (proto === 'udp') {
  14550. if (btnUdp) {
  14551. btnUdp.className = activeUdpCls;
  14552. const dot = btnUdp.querySelector('span');
  14553. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14554. }
  14555. if (btnTcp) {
  14556. btnTcp.className = inactiveCls;
  14557. const dot = btnTcp.querySelector('span');
  14558. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14559. }
  14560. if (badge) {
  14561. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14562. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14563. }
  14564. if (pktField) pktField.classList.remove('opacity-40');
  14565. } else {
  14566. if (btnUdp) {
  14567. btnUdp.className = inactiveCls;
  14568. const dot = btnUdp.querySelector('span');
  14569. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14570. }
  14571. if (btnTcp) {
  14572. btnTcp.className = activeTcpCls;
  14573. const dot = btnTcp.querySelector('span');
  14574. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14575. }
  14576. if (badge) {
  14577. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14578. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14579. }
  14580. if (pktField) pktField.classList.add('opacity-40');
  14581. }
  14582. }
  14583. function setBwTestDirection(dir) {
  14584. const hiddenInp = document.getElementById('bwtest-input-direction');
  14585. if (hiddenInp) hiddenInp.value = dir;
  14586. const btnBoth = document.getElementById('bwtest-dir-both');
  14587. const btnTx = document.getElementById('bwtest-dir-tx');
  14588. const btnRx = document.getElementById('bwtest-dir-rx');
  14589. 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';
  14590. 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';
  14591. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14592. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14593. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14594. }
  14595. function setBwTestLimit(bps) {
  14596. const sel = document.getElementById('bwtest-input-limit');
  14597. if (sel) sel.value = String(bps);
  14598. }
  14599. async function checkActiveBwTest() {
  14600. try {
  14601. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14602. if (!res.ok) return;
  14603. const st = await res.json();
  14604. if (st.running) {
  14605. setBwTestRunningUI(true);
  14606. processBwTestStatus(st);
  14607. startBwTestTelemetry();
  14608. }
  14609. } catch (err) {
  14610. console.error('Failed to check active BwTest:', err);
  14611. }
  14612. }
  14613. async function startBwTest(e) {
  14614. if (e && e.preventDefault) e.preventDefault();
  14615. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14616. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14617. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14618. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14619. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14620. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14621. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14622. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14623. bwtestState.targetDuration = duration;
  14624. bwtestState.chartPoints = [];
  14625. bwtestState.peakTx = 0;
  14626. bwtestState.peakRx = 0;
  14627. bwtestState.lastSampleElapsed = -1;
  14628. bwtestState.sessionID = null;
  14629. // Clear UI elements
  14630. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14631. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14632. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14633. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14634. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14635. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14636. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14637. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14638. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14639. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14640. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14641. const tbody = document.getElementById('bwtest-samples-tbody');
  14642. if (tbody) tbody.innerHTML = '';
  14643. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14644. setBwTestRunningUI(true);
  14645. try {
  14646. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14647. method: 'POST',
  14648. headers: { 'Content-Type': 'application/json' },
  14649. body: JSON.stringify({
  14650. target,
  14651. port,
  14652. direction,
  14653. protocol,
  14654. bandwidth_limit,
  14655. packet_size,
  14656. streams,
  14657. duration
  14658. })
  14659. });
  14660. if (!res.ok) {
  14661. const err = await res.json();
  14662. throw new Error(err.error || 'Failed to start bandwidth test');
  14663. }
  14664. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14665. startBwTestTelemetry();
  14666. } catch (err) {
  14667. setBwTestRunningUI(false);
  14668. showToast('Start Failed', err.message, 'error');
  14669. }
  14670. }
  14671. function setBwTestRunningUI(running) {
  14672. bwtestState.running = running;
  14673. const startBtn = document.getElementById('bwtest-btn-start');
  14674. const stopBtn = document.getElementById('bwtest-btn-stop');
  14675. const badge = document.getElementById('bwtest-run-status-badge');
  14676. const ph = document.getElementById('bwtest-chart-placeholder');
  14677. if (running) {
  14678. if (startBtn) {
  14679. startBtn.disabled = true;
  14680. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14681. }
  14682. if (stopBtn) {
  14683. stopBtn.disabled = false;
  14684. stopBtn.classList.remove('opacity-40');
  14685. }
  14686. if (badge) {
  14687. badge.innerText = 'TESTING...';
  14688. 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';
  14689. }
  14690. if (ph) ph.style.display = 'none';
  14691. } else {
  14692. if (startBtn) {
  14693. startBtn.disabled = false;
  14694. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14695. }
  14696. if (stopBtn) {
  14697. stopBtn.disabled = true;
  14698. stopBtn.classList.add('opacity-40');
  14699. }
  14700. if (badge) {
  14701. badge.innerText = 'IDLE';
  14702. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14703. }
  14704. }
  14705. }
  14706. async function stopBwTest() {
  14707. try {
  14708. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14709. if (!res.ok) throw new Error(await responseError(res));
  14710. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14711. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14712. } catch (err) {
  14713. showToast('Stop Failed', err.message, 'error');
  14714. }
  14715. }
  14716. async function responseError(res) {
  14717. const text = await res.text();
  14718. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14719. catch { return text || `HTTP ${res.status}`; }
  14720. }
  14721. function processBwTestStatus(st) {
  14722. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14723. bwtestState.sessionID = st.session_id;
  14724. bwtestState.lastSampleElapsed = -1;
  14725. }
  14726. for (const sample of st.recent_samples || []) {
  14727. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14728. handleBwTestSample(sample);
  14729. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14730. }
  14731. }
  14732. if (!st.running) {
  14733. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14734. bwtestState.pollTimer = null;
  14735. setBwTestRunningUI(false);
  14736. handleBwTestFinish(st.summary, st.error);
  14737. }
  14738. }
  14739. function startBwTestTelemetry() {
  14740. if (!state.currentUser) return;
  14741. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14742. let busy = false;
  14743. const poll = async () => {
  14744. if (busy || !state.currentUser || document.hidden) return;
  14745. busy = true;
  14746. try {
  14747. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14748. if (!res.ok) throw new Error(await responseError(res));
  14749. processBwTestStatus(await res.json());
  14750. } catch (err) {
  14751. console.error('BwTest polling error:', err);
  14752. } finally { busy = false; }
  14753. };
  14754. bwtestState.pollTimer = setInterval(poll, 400);
  14755. poll();
  14756. }
  14757. function handleBwTestSample(s) {
  14758. if (!s) return;
  14759. const payloadHint = document.getElementById('bwtest-effective-payload');
  14760. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14761. const txMbps = s.tx_mbps || 0;
  14762. const rxMbps = s.rx_mbps || 0;
  14763. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14764. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14765. // KPI updates
  14766. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14767. if (elTx) {
  14768. elTx.innerText = txMbps.toFixed(2);
  14769. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14770. }
  14771. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14772. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14773. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14774. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14775. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14776. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14777. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14778. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14779. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14780. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14781. const elLoss = document.getElementById('bwtest-stat-loss');
  14782. if (elLoss) {
  14783. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14784. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14785. }
  14786. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14787. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14788. const elJitter = document.getElementById('bwtest-stat-jitter');
  14789. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14790. const elTime = document.getElementById('bwtest-stat-time');
  14791. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14792. const elData = document.getElementById('bwtest-stat-data');
  14793. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14794. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14795. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14796. // Append point to chart buffer
  14797. bwtestState.chartPoints.push({
  14798. elapsed: s.elapsed_sec || 0,
  14799. tx: txMbps,
  14800. rx: rxMbps
  14801. });
  14802. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14803. bwtestState.chartPoints.shift();
  14804. }
  14805. drawBwTestChart();
  14806. // Add row to breakdown table
  14807. const tbody = document.getElementById('bwtest-samples-tbody');
  14808. if (tbody) {
  14809. const tr = document.createElement('tr');
  14810. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14811. tr.innerHTML = `
  14812. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14813. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14814. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14815. <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>
  14816. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14817. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14818. `;
  14819. tbody.insertBefore(tr, tbody.firstChild);
  14820. const countEl = document.getElementById('bwtest-sample-count');
  14821. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14822. }
  14823. }
  14824. function handleBwTestFinish(summary, error) {
  14825. const badge = document.getElementById('bwtest-run-status-badge');
  14826. if (error) {
  14827. showToast('Benchmark Error', error, 'error');
  14828. if (badge) {
  14829. badge.innerText = 'ERROR';
  14830. 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';
  14831. }
  14832. } else if (summary) {
  14833. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14834. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14835. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14836. if (badge) {
  14837. badge.innerText = 'COMPLETED';
  14838. 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';
  14839. }
  14840. }
  14841. loadBwTestHistory();
  14842. fetchBwTestServerStatus();
  14843. }
  14844. function resizeBwTestCanvas() {
  14845. const canvas = document.getElementById('bwtest-chart');
  14846. if (!canvas || !canvas.parentElement) return;
  14847. const rect = canvas.parentElement.getBoundingClientRect();
  14848. const dpr = window.devicePixelRatio || 1;
  14849. canvas.width = rect.width * dpr;
  14850. canvas.height = rect.height * dpr;
  14851. const ctx = canvas.getContext('2d');
  14852. ctx.scale(dpr, dpr);
  14853. drawBwTestChart();
  14854. }
  14855. window.addEventListener('resize', () => {
  14856. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14857. });
  14858. function drawBwTestChart() {
  14859. const canvas = document.getElementById('bwtest-chart');
  14860. if (!canvas) return;
  14861. const ctx = canvas.getContext('2d');
  14862. const dpr = window.devicePixelRatio || 1;
  14863. const width = canvas.width / dpr;
  14864. const height = canvas.height / dpr;
  14865. ctx.clearRect(0, 0, width, height);
  14866. const points = bwtestState.chartPoints;
  14867. if (!points || points.length === 0) return;
  14868. // Determine scale ceiling
  14869. let maxRate = 10;
  14870. for (const p of points) {
  14871. if (p.tx > maxRate) maxRate = p.tx;
  14872. if (p.rx > maxRate) maxRate = p.rx;
  14873. }
  14874. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14875. const paddingLeft = 55;
  14876. const paddingBottom = 24;
  14877. const paddingTop = 12;
  14878. const paddingRight = 16;
  14879. const chartW = width - paddingLeft - paddingRight;
  14880. const chartH = height - paddingTop - paddingBottom;
  14881. // Grid Lines and Y-Axis labels
  14882. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14883. ctx.lineWidth = 1;
  14884. ctx.fillStyle = '#94a3b8';
  14885. ctx.font = '10px monospace';
  14886. ctx.textAlign = 'right';
  14887. const gridSteps = 4;
  14888. for (let i = 0; i <= gridSteps; i++) {
  14889. const val = (maxRate / gridSteps) * i;
  14890. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14891. ctx.beginPath();
  14892. ctx.moveTo(paddingLeft, y);
  14893. ctx.lineTo(width - paddingRight, y);
  14894. ctx.stroke();
  14895. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14896. }
  14897. // Draw TX Line (Cyan #22d3ee)
  14898. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14899. // Draw RX Line (Purple #a855f7)
  14900. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14901. }
  14902. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14903. if (points.length < 2) return;
  14904. const stepX = w / Math.max(points.length - 1, 1);
  14905. // Gradient area fill
  14906. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14907. grad.addColorStop(0, fillColor);
  14908. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14909. ctx.beginPath();
  14910. points.forEach((p, idx) => {
  14911. const x = left + idx * stepX;
  14912. const val = valFn(p);
  14913. const y = top + h - (val / maxVal) * h;
  14914. if (idx === 0) {
  14915. ctx.moveTo(x, y);
  14916. } else {
  14917. ctx.lineTo(x, y);
  14918. }
  14919. });
  14920. // Complete path for fill
  14921. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14922. ctx.lineTo(left, top + h);
  14923. ctx.closePath();
  14924. ctx.fillStyle = grad;
  14925. ctx.fill();
  14926. // Draw line stroke
  14927. ctx.beginPath();
  14928. ctx.lineWidth = 2.5;
  14929. ctx.strokeStyle = strokeColor;
  14930. points.forEach((p, idx) => {
  14931. const x = left + idx * stepX;
  14932. const val = valFn(p);
  14933. const y = top + h - (val / maxVal) * h;
  14934. if (idx === 0) {
  14935. ctx.moveTo(x, y);
  14936. } else {
  14937. ctx.lineTo(x, y);
  14938. }
  14939. });
  14940. ctx.stroke();
  14941. // Draw end point halo
  14942. const lastP = points[points.length - 1];
  14943. const lastX = left + (points.length - 1) * stepX;
  14944. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14945. ctx.fillStyle = strokeColor;
  14946. ctx.beginPath();
  14947. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14948. ctx.fill();
  14949. }
  14950. async function loadBwTestHistory() {
  14951. try {
  14952. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14953. if (!res.ok) return;
  14954. const list = await res.json();
  14955. renderBwTestHistory(Array.isArray(list) ? list : []);
  14956. } catch (err) {
  14957. console.error('Failed to load BwTest history:', err);
  14958. }
  14959. }
  14960. function renderBwTestHistory(list) {
  14961. const tbody = document.getElementById('bwtest-history-tbody');
  14962. if (!tbody) return;
  14963. if (list.length === 0) {
  14964. 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>`;
  14965. return;
  14966. }
  14967. tbody.innerHTML = '';
  14968. list.forEach(item => {
  14969. const s = item.summary || {};
  14970. const tr = document.createElement('tr');
  14971. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14972. const dirBadge = item.direction === 'both'
  14973. ? `<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>`
  14974. : item.direction === 'tx'
  14975. ? `<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>`
  14976. : `<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>`;
  14977. const protoBadge = item.protocol === 'tcp'
  14978. ? `<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>`
  14979. : `<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>`;
  14980. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14981. tr.innerHTML = `
  14982. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14983. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14984. <td class="py-2.5 px-4">${protoBadge}</td>
  14985. <td class="py-2.5 px-4">${dirBadge}</td>
  14986. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14987. <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>
  14988. <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>
  14989. <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>
  14990. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14991. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14992. `;
  14993. tbody.appendChild(tr);
  14994. });
  14995. }
  14996. // ======================== SETTINGS & ROUTER DNS ========================
  14997. state.settingsSubTab = 'dns';
  14998. state.dnsSettings = null;
  14999. state.dnsStaticRecords = [];
  15000. state.dnsStatus = null;
  15001. function switchSettingsSubTab(sub) {
  15002. state.settingsSubTab = sub;
  15003. const btnDns = document.getElementById('btn-settings-subtab-dns');
  15004. const btnSys = document.getElementById('btn-settings-subtab-system');
  15005. const btnBak = document.getElementById('btn-settings-subtab-backup');
  15006. const tabDns = document.getElementById('settings-subtab-dns');
  15007. const tabSys = document.getElementById('settings-subtab-system');
  15008. const tabBak = document.getElementById('settings-subtab-backup');
  15009. const activeClass = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5 cursor-pointer';
  15010. const inactiveClass = '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 cursor-pointer';
  15011. if (btnDns) btnDns.className = inactiveClass;
  15012. if (btnSys) btnSys.className = inactiveClass;
  15013. if (btnBak) btnBak.className = inactiveClass;
  15014. tabDns?.classList.add('hidden');
  15015. tabSys?.classList.add('hidden');
  15016. tabBak?.classList.add('hidden');
  15017. if (sub === 'dns') {
  15018. if (btnDns) btnDns.className = activeClass;
  15019. tabDns?.classList.remove('hidden');
  15020. loadDNSSettings();
  15021. } else if (sub === 'system') {
  15022. if (btnSys) btnSys.className = activeClass;
  15023. tabSys?.classList.remove('hidden');
  15024. loadSystemSettings();
  15025. } else if (sub === 'backup') {
  15026. if (btnBak) btnBak.className = activeClass;
  15027. tabBak?.classList.remove('hidden');
  15028. loadBackupList();
  15029. }
  15030. }
  15031. async function loadSettingsData(showLoading = false) {
  15032. if (state.settingsSubTab === 'system') {
  15033. await loadSystemSettings();
  15034. } else if (state.settingsSubTab === 'backup') {
  15035. await loadBackupList();
  15036. } else {
  15037. await loadDNSSettings();
  15038. }
  15039. }
  15040. async function loadDNSSettings() {
  15041. try {
  15042. const [settingsRes, staticRes, statusRes] = await Promise.all([
  15043. fetch(`${API_BASE}/dns/settings`),
  15044. fetch(`${API_BASE}/dns/static`),
  15045. fetch(`${API_BASE}/dns/status`)
  15046. ]);
  15047. if (settingsRes.ok) {
  15048. state.dnsSettings = await settingsRes.json();
  15049. populateDNSSettingsForm(state.dnsSettings);
  15050. }
  15051. if (staticRes.ok) {
  15052. state.dnsStaticRecords = await staticRes.json();
  15053. renderStaticDNSList();
  15054. }
  15055. if (statusRes.ok) {
  15056. state.dnsStatus = await statusRes.json();
  15057. updateDNSStatusView(state.dnsStatus);
  15058. }
  15059. } catch (err) {
  15060. console.error('Failed to load DNS settings:', err);
  15061. }
  15062. }
  15063. function populateDNSSettingsForm(s) {
  15064. if (!s) return;
  15065. const dnsForm = document.getElementById('form-dns-settings');
  15066. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  15067. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  15068. if (dynamicEl) {
  15069. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  15070. 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(' ');
  15071. } else {
  15072. dynamicEl.innerText = 'None';
  15073. }
  15074. }
  15075. // If user is actively typing or editing in the form, do not overwrite their inputs!
  15076. if (isEditing) return;
  15077. const serversInput = document.getElementById('dns-servers-input');
  15078. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  15079. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  15080. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  15081. const domainInput = document.getElementById('dns-domain-input');
  15082. if (domainInput) domainInput.value = s.domain || '';
  15083. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  15084. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  15085. }
  15086. function updateDNSStatusView(st) {
  15087. if (!st) return;
  15088. const preview = document.getElementById('dns-resolv-preview');
  15089. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15090. const pillText = document.getElementById('dns-live-status-text');
  15091. const pill = document.getElementById('dns-live-status-pill');
  15092. if (pill && pillText) {
  15093. if (st.service_running) {
  15094. 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';
  15095. pillText.innerText = 'DNS Service Active';
  15096. } else {
  15097. 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';
  15098. pillText.innerText = 'DNS Service Inactive';
  15099. }
  15100. }
  15101. }
  15102. function appendDNSPreset(preset) {
  15103. const input = document.getElementById('dns-servers-input');
  15104. if (!input) return;
  15105. const dnsForm = document.getElementById('form-dns-settings');
  15106. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15107. const current = input.value.trim();
  15108. if (!current) {
  15109. input.value = preset;
  15110. } else {
  15111. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15112. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15113. toAdd.forEach(ip => {
  15114. if (!existing.includes(ip)) existing.push(ip);
  15115. });
  15116. input.value = existing.join(', ');
  15117. }
  15118. }
  15119. async function saveDNSSettings(e) {
  15120. e.preventDefault();
  15121. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15122. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15123. if (servers.length === 0) {
  15124. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15125. return;
  15126. }
  15127. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15128. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15129. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15130. try {
  15131. const res = await fetch(`${API_BASE}/dns/settings`, {
  15132. method: 'POST',
  15133. headers: { 'Content-Type': 'application/json' },
  15134. body: JSON.stringify({
  15135. servers: servers,
  15136. cache_size: cacheSize,
  15137. domain: domain,
  15138. allow_remote_requests: allowRemote
  15139. })
  15140. });
  15141. const data = await res.json();
  15142. if (res.ok) {
  15143. const dnsForm = document.getElementById('form-dns-settings');
  15144. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15145. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15146. loadDNSSettings();
  15147. } else {
  15148. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15149. }
  15150. } catch (err) {
  15151. showToast('Error', err.message, 'error');
  15152. }
  15153. }
  15154. async function flushDNSCache() {
  15155. try {
  15156. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15157. if (res.ok) {
  15158. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15159. loadDNSSettings();
  15160. } else {
  15161. const err = await res.json();
  15162. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15163. }
  15164. } catch (err) {
  15165. showToast('Error', err.message, 'error');
  15166. }
  15167. }
  15168. function renderStaticDNSList() {
  15169. const tbody = document.getElementById('dns-static-tbody');
  15170. const empty = document.getElementById('dns-static-empty');
  15171. const badge = document.getElementById('dns-static-count-badge');
  15172. if (!tbody) return;
  15173. tbody.innerHTML = '';
  15174. const records = state.dnsStaticRecords || [];
  15175. if (badge) badge.innerText = `${records.length} Records`;
  15176. if (records.length === 0) {
  15177. empty?.classList.remove('hidden');
  15178. return;
  15179. }
  15180. empty?.classList.add('hidden');
  15181. records.forEach(rec => {
  15182. const tr = document.createElement('tr');
  15183. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15184. tr.innerHTML = `
  15185. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15186. <td class="py-2.5 px-4">
  15187. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15188. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15189. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15190. }">
  15191. ${rec.type || 'A'}
  15192. </span>
  15193. </td>
  15194. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15195. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15196. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15197. <td class="py-2.5 px-4">
  15198. <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'}">
  15199. ${rec.disabled ? 'Disabled' : 'Active'}
  15200. </span>
  15201. </td>
  15202. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15203. <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>
  15204. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15205. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15206. </td>
  15207. `;
  15208. tbody.appendChild(tr);
  15209. });
  15210. }
  15211. function openStaticDNSModal(id = null) {
  15212. const modal = document.getElementById('modal-static-dns');
  15213. const title = document.getElementById('modal-static-dns-title');
  15214. const form = document.getElementById('form-static-dns');
  15215. if (!modal || !form) return;
  15216. form.reset();
  15217. document.getElementById('modal-static-dns-id').value = '';
  15218. if (id) {
  15219. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15220. if (rec) {
  15221. if (title) title.innerText = 'Edit Static DNS Record';
  15222. document.getElementById('modal-static-dns-id').value = rec.id;
  15223. document.getElementById('modal-static-dns-name').value = rec.name;
  15224. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15225. document.getElementById('modal-static-dns-addr').value = rec.address;
  15226. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15227. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15228. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15229. }
  15230. } else {
  15231. if (title) title.innerText = 'Add Static DNS Record';
  15232. }
  15233. modal.classList.remove('hidden');
  15234. }
  15235. function closeStaticDNSModal() {
  15236. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15237. }
  15238. async function submitSaveStaticDNS(e) {
  15239. e.preventDefault();
  15240. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15241. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15242. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15243. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15244. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15245. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15246. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15247. if (!name || !address) {
  15248. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15249. return;
  15250. }
  15251. try {
  15252. const res = await fetch(`${API_BASE}/dns/static`, {
  15253. method: 'POST',
  15254. headers: { 'Content-Type': 'application/json' },
  15255. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15256. });
  15257. const data = await res.json();
  15258. if (res.ok) {
  15259. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15260. closeStaticDNSModal();
  15261. loadDNSSettings();
  15262. } else {
  15263. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15264. }
  15265. } catch (err) {
  15266. showToast('Error', err.message, 'error');
  15267. }
  15268. }
  15269. async function deleteStaticDNS(id) {
  15270. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15271. try {
  15272. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15273. if (res.ok) {
  15274. showToast('Deleted', 'Static DNS record deleted', 'success');
  15275. loadDNSSettings();
  15276. }
  15277. } catch (err) {
  15278. showToast('Error', err.message, 'error');
  15279. }
  15280. }
  15281. async function toggleStaticDNS(id, disabled) {
  15282. try {
  15283. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15284. method: 'POST',
  15285. headers: { 'Content-Type': 'application/json' },
  15286. body: JSON.stringify({ disabled })
  15287. });
  15288. if (res.ok) {
  15289. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15290. loadDNSSettings();
  15291. }
  15292. } catch (err) {
  15293. showToast('Error', err.message, 'error');
  15294. }
  15295. }
  15296. async function loadSystemSettings() {
  15297. try {
  15298. const sysForm = document.getElementById('form-system-settings');
  15299. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15300. const res = await fetch(`${API_BASE}/system/settings`);
  15301. if (res.ok) {
  15302. const data = await res.json();
  15303. if (!isEditing) {
  15304. const hostInput = document.getElementById('system-hostname-input');
  15305. if (hostInput) hostInput.value = data.hostname || '';
  15306. const tzInput = document.getElementById('system-timezone-input');
  15307. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15308. }
  15309. }
  15310. } catch (err) {
  15311. console.error('Failed to load system settings:', err);
  15312. }
  15313. }
  15314. async function saveSystemSettings(e) {
  15315. e.preventDefault();
  15316. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15317. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15318. try {
  15319. const res = await fetch(`${API_BASE}/system/settings`, {
  15320. method: 'POST',
  15321. headers: { 'Content-Type': 'application/json' },
  15322. body: JSON.stringify({ hostname, timezone })
  15323. });
  15324. const data = await res.json();
  15325. if (res.ok) {
  15326. const sysForm = document.getElementById('form-system-settings');
  15327. if (sysForm) sysForm.dataset.dirty = 'false';
  15328. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15329. const sideH = document.getElementById('side-hostname');
  15330. if (sideH) sideH.innerText = data.hostname;
  15331. } else {
  15332. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15333. }
  15334. } catch (err) {
  15335. showToast('Error', err.message, 'error');
  15336. }
  15337. }
  15338. // =============================================================================
  15339. // BACKUP & RESTORE MANAGER
  15340. // =============================================================================
  15341. state.selectedBackupFile = null;
  15342. state.inspectedBackupManifest = null;
  15343. state.pendingRestoreTarget = null;
  15344. state.backupsList = [];
  15345. async function exportBackupDownload() {
  15346. const btn = document.getElementById('btn-export-backup');
  15347. const commentInput = document.getElementById('backup-export-comment');
  15348. const comment = (commentInput?.value || '').trim();
  15349. const originalHtml = btn ? btn.innerHTML : '';
  15350. if (btn) {
  15351. btn.disabled = true;
  15352. btn.innerHTML = `<span class="w-3.5 h-3.5 rounded-full border-2 border-white border-t-transparent animate-spin inline-block"></span> Generating Backup...`;
  15353. }
  15354. try {
  15355. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15356. if (!res.ok) {
  15357. const err = await res.json().catch(() => ({}));
  15358. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15359. return;
  15360. }
  15361. const blob = await res.blob();
  15362. const disposition = res.headers.get('Content-Disposition') || '';
  15363. let filename = 'debtik-backup.zip';
  15364. const match = disposition.match(/filename="?([^";]+)"?/);
  15365. if (match && match[1]) {
  15366. filename = match[1];
  15367. }
  15368. const blobUrl = window.URL.createObjectURL(blob);
  15369. const a = document.createElement('a');
  15370. a.href = blobUrl;
  15371. a.download = filename;
  15372. document.body.appendChild(a);
  15373. a.click();
  15374. setTimeout(() => {
  15375. window.URL.revokeObjectURL(blobUrl);
  15376. a.remove();
  15377. }, 1000);
  15378. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15379. } catch (err) {
  15380. showToast('Export Error', err.message || 'Network error during download', 'error');
  15381. } finally {
  15382. if (btn) {
  15383. btn.disabled = false;
  15384. btn.innerHTML = originalHtml;
  15385. }
  15386. }
  15387. }
  15388. async function onBackupFileSelected(e) {
  15389. const file = e.target.files?.[0];
  15390. if (!file) return;
  15391. const label = document.getElementById('backup-file-label');
  15392. if (label) {
  15393. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15394. }
  15395. await inspectBackupFile(file);
  15396. }
  15397. async function inspectBackupFile(file) {
  15398. const preview = document.getElementById('backup-inspect-preview');
  15399. const restoreBtn = document.getElementById('btn-restore-backup');
  15400. const formData = new FormData();
  15401. formData.append('backup', file);
  15402. try {
  15403. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15404. method: 'POST',
  15405. body: formData
  15406. });
  15407. const data = await res.json();
  15408. if (!res.ok || !data.success || !data.manifest) {
  15409. if (preview) preview.classList.add('hidden');
  15410. if (restoreBtn) restoreBtn.disabled = true;
  15411. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15412. return;
  15413. }
  15414. const mf = data.manifest;
  15415. state.selectedBackupFile = file;
  15416. state.inspectedBackupManifest = mf;
  15417. const vEl = document.getElementById('backup-inspect-version');
  15418. const hEl = document.getElementById('backup-inspect-hostname');
  15419. const fEl = document.getElementById('backup-inspect-files');
  15420. const dEl = document.getElementById('backup-inspect-date');
  15421. const cEl = document.getElementById('backup-inspect-comment');
  15422. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15423. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15424. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15425. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15426. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15427. if (preview) preview.classList.remove('hidden');
  15428. if (restoreBtn) restoreBtn.disabled = false;
  15429. } catch (err) {
  15430. if (preview) preview.classList.add('hidden');
  15431. if (restoreBtn) restoreBtn.disabled = true;
  15432. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15433. }
  15434. }
  15435. function confirmRestoreBackup(localFilename = null) {
  15436. const modal = document.getElementById('modal-restore-confirm');
  15437. const details = document.getElementById('modal-restore-details');
  15438. const progress = document.getElementById('modal-restore-progress');
  15439. const cancelBtn = document.getElementById('btn-cancel-restore');
  15440. const execBtn = document.getElementById('btn-execute-restore');
  15441. if (progress) progress.classList.add('hidden');
  15442. if (cancelBtn) cancelBtn.disabled = false;
  15443. if (execBtn) {
  15444. execBtn.disabled = false;
  15445. execBtn.innerText = 'Yes, Restore & Reload';
  15446. }
  15447. if (localFilename) {
  15448. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15449. if (details) {
  15450. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15451. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15452. }
  15453. } else {
  15454. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15455. showToast('Error', 'Please select a valid backup archive first', 'error');
  15456. return;
  15457. }
  15458. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15459. const mf = state.inspectedBackupManifest;
  15460. if (details) {
  15461. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15462. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15463. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15464. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15465. }
  15466. }
  15467. if (modal) modal.classList.remove('hidden');
  15468. }
  15469. function closeRestoreModal() {
  15470. const modal = document.getElementById('modal-restore-confirm');
  15471. if (modal) modal.classList.add('hidden');
  15472. }
  15473. async function executeRestoreBackup() {
  15474. const target = state.pendingRestoreTarget;
  15475. if (!target) return;
  15476. const progress = document.getElementById('modal-restore-progress');
  15477. const progressText = document.getElementById('modal-restore-progress-text');
  15478. const cancelBtn = document.getElementById('btn-cancel-restore');
  15479. const execBtn = document.getElementById('btn-execute-restore');
  15480. if (cancelBtn) cancelBtn.disabled = true;
  15481. if (execBtn) execBtn.disabled = true;
  15482. if (progress) progress.classList.remove('hidden');
  15483. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15484. try {
  15485. let res;
  15486. if (target.type === 'file') {
  15487. const formData = new FormData();
  15488. formData.append('backup', target.file);
  15489. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15490. method: 'POST',
  15491. body: formData
  15492. });
  15493. } else {
  15494. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15495. method: 'POST'
  15496. });
  15497. }
  15498. const data = await res.json();
  15499. if (!res.ok || !data.success) {
  15500. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15501. if (cancelBtn) cancelBtn.disabled = false;
  15502. if (execBtn) execBtn.disabled = false;
  15503. if (progress) progress.classList.add('hidden');
  15504. return;
  15505. }
  15506. if (progressText) {
  15507. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15508. }
  15509. pollAfterRestoreReconnect();
  15510. } catch (err) {
  15511. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15512. if (cancelBtn) cancelBtn.disabled = false;
  15513. if (execBtn) execBtn.disabled = false;
  15514. if (progress) progress.classList.add('hidden');
  15515. }
  15516. }
  15517. function pollAfterRestoreReconnect() {
  15518. let attempts = 0;
  15519. const maxAttempts = 25;
  15520. const timer = setInterval(async () => {
  15521. attempts++;
  15522. try {
  15523. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15524. if (res.ok) {
  15525. clearInterval(timer);
  15526. closeRestoreModal();
  15527. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15528. setTimeout(() => {
  15529. window.location.reload();
  15530. }, 1200);
  15531. }
  15532. } catch (_) {
  15533. // Still restarting, retry
  15534. }
  15535. if (attempts >= maxAttempts) {
  15536. clearInterval(timer);
  15537. closeRestoreModal();
  15538. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15539. }
  15540. }, 1500);
  15541. }
  15542. async function loadBackupList() {
  15543. const tbody = document.getElementById('backups-table-tbody');
  15544. const empty = document.getElementById('backups-empty-state');
  15545. if (!tbody) return;
  15546. try {
  15547. const res = await fetch(`${API_BASE}/system/backups`);
  15548. if (!res.ok) return;
  15549. const list = await res.json();
  15550. state.backupsList = list || [];
  15551. renderBackupsTable(state.backupsList);
  15552. } catch (err) {
  15553. console.error('Failed to load backup list:', err);
  15554. }
  15555. }
  15556. function renderBackupsTable(backups) {
  15557. const tbody = document.getElementById('backups-table-tbody');
  15558. const empty = document.getElementById('backups-empty-state');
  15559. if (!tbody) return;
  15560. if (!backups || backups.length === 0) {
  15561. tbody.innerHTML = '';
  15562. if (empty) empty.classList.remove('hidden');
  15563. return;
  15564. }
  15565. if (empty) empty.classList.add('hidden');
  15566. tbody.innerHTML = backups.map(bk => {
  15567. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15568. const badge = isAuto
  15569. ? `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-amber-500/10 text-amber-300 border border-amber-500/20">PRE-RESTORE</span>`
  15570. : `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-cyan-500/10 text-cyan-300 border border-cyan-500/20">MANUAL</span>`;
  15571. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15572. return `<tr class="hover:bg-slate-800/40 transition">
  15573. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15574. ${badge}
  15575. <span>${escapeHtml(bk.filename)}</span>
  15576. </td>
  15577. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15578. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15579. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15580. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15581. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15582. <td class="py-3 px-4 text-right space-x-2">
  15583. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15584. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-800 hover:bg-slate-700 text-cyan-400 border border-slate-700 transition cursor-pointer">
  15585. Download
  15586. </button>
  15587. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15588. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-amber-600/20 hover:bg-amber-600/30 text-amber-300 border border-amber-500/30 transition cursor-pointer">
  15589. Restore
  15590. </button>
  15591. </td>
  15592. </tr>`;
  15593. }).join('');
  15594. }
  15595. async function downloadLocalBackup(filename) {
  15596. try {
  15597. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15598. if (!res.ok) {
  15599. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15600. return;
  15601. }
  15602. const blob = await res.blob();
  15603. const blobUrl = window.URL.createObjectURL(blob);
  15604. const a = document.createElement('a');
  15605. a.href = blobUrl;
  15606. a.download = filename;
  15607. document.body.appendChild(a);
  15608. a.click();
  15609. setTimeout(() => {
  15610. window.URL.revokeObjectURL(blobUrl);
  15611. a.remove();
  15612. }, 1000);
  15613. } catch (err) {
  15614. showToast('Download Error', err.message, 'error');
  15615. }
  15616. }
  15617. // =============================================================================
  15618. // AUTHENTICATION & USER MANAGER
  15619. // =============================================================================
  15620. async function checkAuthStatus() {
  15621. try {
  15622. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15623. headers: {
  15624. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15625. }
  15626. });
  15627. if (res.ok) {
  15628. const user = await res.json();
  15629. state.currentUser = user;
  15630. updateUserProfileHeader(user);
  15631. hideLoginScreen();
  15632. state.isPolling = true;
  15633. fetchData();
  15634. initLiveTrafficStream();
  15635. return true;
  15636. } else {
  15637. showLoginScreen(false);
  15638. return false;
  15639. }
  15640. } catch (err) {
  15641. showLoginScreen(false);
  15642. return false;
  15643. }
  15644. }
  15645. function showLoginScreen(isExpired = false) {
  15646. const el = document.getElementById('login-screen');
  15647. if (el) el.classList.remove('hidden');
  15648. const errEl = document.getElementById('login-error');
  15649. const errTxt = document.getElementById('login-error-text');
  15650. if (isExpired && errEl && errTxt) {
  15651. errTxt.innerText = 'Session expired. Please sign in again.';
  15652. errEl.classList.remove('hidden');
  15653. } else if (errEl) {
  15654. errEl.classList.add('hidden');
  15655. }
  15656. const pwInput = document.getElementById('login-password');
  15657. if (pwInput) pwInput.value = '';
  15658. const userInput = document.getElementById('login-username');
  15659. if (userInput && !userInput.value) userInput.focus();
  15660. else if (pwInput) pwInput.focus();
  15661. }
  15662. function hideLoginScreen() {
  15663. const el = document.getElementById('login-screen');
  15664. if (el) el.classList.add('hidden');
  15665. const errEl = document.getElementById('login-error');
  15666. if (errEl) errEl.classList.add('hidden');
  15667. }
  15668. async function handleLoginSubmit(event) {
  15669. event.preventDefault();
  15670. const username = (document.getElementById('login-username')?.value || '').trim();
  15671. const password = document.getElementById('login-password')?.value || '';
  15672. const errEl = document.getElementById('login-error');
  15673. const errTxt = document.getElementById('login-error-text');
  15674. const btn = document.getElementById('login-submit-btn');
  15675. const btnText = document.getElementById('login-btn-text');
  15676. const spinner = document.getElementById('login-btn-spinner');
  15677. if (!username || !password) {
  15678. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15679. if (errEl) errEl.classList.remove('hidden');
  15680. return;
  15681. }
  15682. if (errEl) errEl.classList.add('hidden');
  15683. if (btn) btn.disabled = true;
  15684. if (btnText) btnText.innerText = 'Authenticating...';
  15685. if (spinner) spinner.classList.remove('hidden');
  15686. try {
  15687. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15688. method: 'POST',
  15689. headers: { 'Content-Type': 'application/json' },
  15690. body: JSON.stringify({ username, password })
  15691. });
  15692. const data = await res.json();
  15693. if (res.ok && data.success) {
  15694. localStorage.setItem('debtik_token', data.token);
  15695. state.currentUser = data.user;
  15696. updateUserProfileHeader(data.user);
  15697. hideLoginScreen();
  15698. state.isPolling = true;
  15699. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15700. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15701. navigate(hash);
  15702. fetchData();
  15703. initLiveTrafficStream();
  15704. // Ensure background telemetry polling is active
  15705. if (!window._telemetryInterval) {
  15706. window._telemetryInterval = setInterval(() => {
  15707. if (state.isPolling && state.currentUser && !document.hidden) {
  15708. fetchData(false);
  15709. }
  15710. }, 5000);
  15711. }
  15712. } else {
  15713. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15714. if (errEl) errEl.classList.remove('hidden');
  15715. }
  15716. } catch (err) {
  15717. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15718. if (errEl) errEl.classList.remove('hidden');
  15719. } finally {
  15720. if (btn) btn.disabled = false;
  15721. if (btnText) btnText.innerText = 'Sign In to Controller';
  15722. if (spinner) spinner.classList.add('hidden');
  15723. }
  15724. }
  15725. async function handleLogoutClick() {
  15726. try {
  15727. await originalFetch(`${API_BASE}/auth/logout`, {
  15728. method: 'POST',
  15729. headers: {
  15730. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15731. }
  15732. });
  15733. } catch (e) {}
  15734. stopSessionPolling();
  15735. localStorage.removeItem('debtik_token');
  15736. state.currentUser = null;
  15737. state.isPolling = false;
  15738. if (window._telemetryInterval) {
  15739. clearInterval(window._telemetryInterval);
  15740. window._telemetryInterval = null;
  15741. }
  15742. if (trafficEventSource) {
  15743. trafficEventSource.close();
  15744. trafficEventSource = null;
  15745. }
  15746. if (trafficPollFallback) {
  15747. clearInterval(trafficPollFallback);
  15748. trafficPollFallback = null;
  15749. }
  15750. showLoginScreen(false);
  15751. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15752. }
  15753. function togglePasswordVisibility(id) {
  15754. const input = document.getElementById(id);
  15755. if (!input) return;
  15756. input.type = input.type === 'password' ? 'text' : 'password';
  15757. }
  15758. function toggleUserMenu() {
  15759. const menu = document.getElementById('user-menu-dropdown');
  15760. if (menu) menu.classList.toggle('hidden');
  15761. }
  15762. function closeUserMenu() {
  15763. const menu = document.getElementById('user-menu-dropdown');
  15764. if (menu) menu.classList.add('hidden');
  15765. }
  15766. // Close user menu on outside click
  15767. document.addEventListener('click', (e) => {
  15768. const menu = document.getElementById('user-menu-dropdown');
  15769. if (!menu || menu.classList.contains('hidden')) return;
  15770. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15771. menu.classList.add('hidden');
  15772. }
  15773. });
  15774. function updateUserProfileHeader(user) {
  15775. if (!user) return;
  15776. const navName = document.getElementById('nav-user-name');
  15777. if (navName) navName.innerText = user.username;
  15778. const dropName = document.getElementById('dropdown-user-name');
  15779. if (dropName) dropName.innerText = user.username;
  15780. const navRole = document.getElementById('nav-user-role');
  15781. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15782. const navAvatar = document.getElementById('nav-user-avatar');
  15783. if (navAvatar) {
  15784. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15785. navAvatar.innerText = initials;
  15786. }
  15787. const statCurUser = document.getElementById('stat-current-user');
  15788. if (statCurUser) statCurUser.innerText = user.username;
  15789. const statCurRole = document.getElementById('stat-current-role');
  15790. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15791. // Role permissions UI visibility: hide user management for non-admins
  15792. const isFullAdmin = user.role === 'full';
  15793. const navUsers = document.getElementById('nav-users');
  15794. if (navUsers) {
  15795. if (isFullAdmin) navUsers.classList.remove('hidden');
  15796. else navUsers.classList.add('hidden');
  15797. }
  15798. const dropdownUsers = document.getElementById('dropdown-item-users');
  15799. if (dropdownUsers) {
  15800. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15801. else dropdownUsers.classList.add('hidden');
  15802. }
  15803. }
  15804. // ================= User Management CRUD =================
  15805. async function loadUsers(isManual = false) {
  15806. try {
  15807. const res = await fetch(`${API_BASE}/users`);
  15808. if (res.status === 403) {
  15809. const tbody = document.getElementById('users-table-tbody');
  15810. if (tbody) {
  15811. tbody.innerHTML = `
  15812. <tr>
  15813. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15814. <div class="inline-flex items-center gap-2">
  15815. <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
  15816. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15817. </div>
  15818. </td>
  15819. </tr>
  15820. `;
  15821. }
  15822. return;
  15823. }
  15824. if (res.ok) {
  15825. state.users = await res.json();
  15826. renderUsersTable();
  15827. const totalUsers = document.getElementById('stat-total-users');
  15828. if (totalUsers) totalUsers.innerText = state.users.length;
  15829. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15830. const adminUsers = document.getElementById('stat-admin-users');
  15831. if (adminUsers) adminUsers.innerText = adminCount;
  15832. const badgeCount = document.getElementById('badge-users-count');
  15833. if (badgeCount) badgeCount.innerText = state.users.length;
  15834. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15835. }
  15836. } catch (err) {
  15837. console.error('Failed to load users:', err);
  15838. }
  15839. }
  15840. function renderUsersTable() {
  15841. const tbody = document.getElementById('users-table-tbody');
  15842. const emptyState = document.getElementById('users-empty-state');
  15843. if (!tbody) return;
  15844. tbody.innerHTML = '';
  15845. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15846. const filtered = (state.users || []).filter(u => {
  15847. if (!query) return true;
  15848. return u.username.toLowerCase().includes(query) ||
  15849. (u.role || '').toLowerCase().includes(query) ||
  15850. (u.comment || '').toLowerCase().includes(query);
  15851. });
  15852. if (filtered.length === 0) {
  15853. if (emptyState) emptyState.classList.remove('hidden');
  15854. return;
  15855. }
  15856. if (emptyState) emptyState.classList.add('hidden');
  15857. const currentAuthUser = state.currentUser?.username || '';
  15858. filtered.forEach(u => {
  15859. const isSelf = u.username === currentAuthUser;
  15860. const isFull = u.role === 'full';
  15861. const isWrite = u.role === 'write';
  15862. let roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-300 border border-slate-700">READ (OBSERVER)</span>`;
  15863. if (isFull) {
  15864. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-purple-500/15 text-purple-300 border border-purple-500/30">FULL (SUPER ADMIN)</span>`;
  15865. } else if (isWrite) {
  15866. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-sky-500/15 text-sky-300 border border-sky-500/30">WRITE (OPERATOR)</span>`;
  15867. }
  15868. const statusBadge = u.disabled
  15869. ? `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-rose-500/15 text-rose-300 border border-rose-500/30"><span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>Disabled</span>`
  15870. : `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-500/15 text-emerald-300 border border-emerald-500/30"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>Active</span>`;
  15871. let lastLoginText = 'Never';
  15872. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15873. const dt = new Date(u.last_login_at);
  15874. lastLoginText = dt.toLocaleString();
  15875. }
  15876. const initials = u.username.slice(0, 2).toUpperCase();
  15877. const tr = document.createElement('tr');
  15878. tr.className = 'hover:bg-slate-800/40 transition group';
  15879. tr.innerHTML = `
  15880. <td class="py-3 px-4">
  15881. <div class="flex items-center gap-3">
  15882. <div class="w-8 h-8 rounded-xl bg-slate-800 border border-slate-700/80 flex items-center justify-center font-bold text-xs text-white">
  15883. ${initials}
  15884. </div>
  15885. <div>
  15886. <div class="font-bold text-white text-xs flex items-center gap-2">
  15887. <span>${escapeHtml(u.username)}</span>
  15888. ${isSelf ? '<span class="text-[9px] bg-brand-500/20 text-brand-300 border border-brand-500/30 px-1.5 py-0.2 rounded font-mono">YOU</span>' : ''}
  15889. </div>
  15890. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15891. </div>
  15892. </div>
  15893. </td>
  15894. <td class="py-3 px-4 font-sans">
  15895. ${roleBadge}
  15896. </td>
  15897. <td class="py-3 px-4 font-sans">
  15898. ${statusBadge}
  15899. </td>
  15900. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15901. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15902. </td>
  15903. <td class="py-3 px-4 text-slate-400 text-xs">
  15904. ${lastLoginText}
  15905. </td>
  15906. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15907. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15908. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15909. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/></svg>
  15910. </button>
  15911. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15912. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15913. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  15914. </button>
  15915. ${!isSelf ? `
  15916. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15917. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15918. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  15919. </button>
  15920. ` : ''}
  15921. </td>
  15922. `;
  15923. tbody.appendChild(tr);
  15924. });
  15925. }
  15926. function openAddUserModal() {
  15927. document.getElementById('user-add-username').value = '';
  15928. document.getElementById('user-add-password').value = '';
  15929. document.getElementById('user-add-confirm').value = '';
  15930. document.getElementById('user-add-role').value = 'full';
  15931. document.getElementById('user-add-comment').value = '';
  15932. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15933. document.getElementById('user-add-username')?.focus();
  15934. }
  15935. function closeAddUserModal() {
  15936. document.getElementById('modal-add-user')?.classList.add('hidden');
  15937. }
  15938. async function submitAddUser(event) {
  15939. event.preventDefault();
  15940. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15941. const password = document.getElementById('user-add-password')?.value || '';
  15942. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15943. const role = document.getElementById('user-add-role')?.value || 'full';
  15944. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15945. if (password !== confirm) {
  15946. showToast('Validation Error', 'Passwords do not match', 'warning');
  15947. return;
  15948. }
  15949. if (password.length < 4) {
  15950. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15951. return;
  15952. }
  15953. try {
  15954. const res = await fetch(`${API_BASE}/users`, {
  15955. method: 'POST',
  15956. headers: { 'Content-Type': 'application/json' },
  15957. body: JSON.stringify({ username, password, role, comment })
  15958. });
  15959. const data = await res.json();
  15960. if (res.ok) {
  15961. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15962. closeAddUserModal();
  15963. loadUsers(false);
  15964. } else {
  15965. showToast('Error', data.message || 'Failed to create user', 'error');
  15966. }
  15967. } catch (err) {
  15968. showToast('Error', err.message, 'error');
  15969. }
  15970. }
  15971. function openEditUserModal(username) {
  15972. const user = (state.users || []).find(u => u.username === username);
  15973. if (!user) return;
  15974. document.getElementById('user-edit-username').value = user.username;
  15975. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15976. document.getElementById('user-edit-role').value = user.role || 'read';
  15977. document.getElementById('user-edit-comment').value = user.comment || '';
  15978. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15979. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15980. }
  15981. function closeEditUserModal() {
  15982. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15983. }
  15984. async function submitEditUser(event) {
  15985. event.preventDefault();
  15986. const username = document.getElementById('user-edit-username')?.value;
  15987. const role = document.getElementById('user-edit-role')?.value || 'read';
  15988. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15989. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15990. try {
  15991. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15992. method: 'PUT',
  15993. headers: { 'Content-Type': 'application/json' },
  15994. body: JSON.stringify({ role, comment, disabled })
  15995. });
  15996. const data = await res.json();
  15997. if (res.ok) {
  15998. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15999. closeEditUserModal();
  16000. loadUsers(false);
  16001. // If updated own role/disabled status, refresh self profile
  16002. if (username === state.currentUser?.username) {
  16003. checkAuthStatus();
  16004. }
  16005. } else {
  16006. showToast('Error', data.message || 'Failed to update user', 'error');
  16007. }
  16008. } catch (err) {
  16009. showToast('Error', err.message, 'error');
  16010. }
  16011. }
  16012. function openAdminResetPasswordModal(username) {
  16013. document.getElementById('admin-reset-username').value = username;
  16014. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  16015. document.getElementById('admin-reset-new-pw').value = '';
  16016. document.getElementById('admin-reset-confirm-pw').value = '';
  16017. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  16018. document.getElementById('admin-reset-new-pw')?.focus();
  16019. }
  16020. function closeAdminResetPasswordModal() {
  16021. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  16022. }
  16023. async function submitAdminResetPassword(event) {
  16024. event.preventDefault();
  16025. const username = document.getElementById('admin-reset-username')?.value;
  16026. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  16027. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  16028. if (newPassword !== confirm) {
  16029. showToast('Validation Error', 'Passwords do not match', 'warning');
  16030. return;
  16031. }
  16032. if (newPassword.length < 4) {
  16033. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16034. return;
  16035. }
  16036. try {
  16037. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  16038. method: 'POST',
  16039. headers: { 'Content-Type': 'application/json' },
  16040. body: JSON.stringify({ new_password: newPassword })
  16041. });
  16042. const data = await res.json();
  16043. if (res.ok) {
  16044. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  16045. closeAdminResetPasswordModal();
  16046. } else {
  16047. showToast('Error', data.message || 'Failed to reset password', 'error');
  16048. }
  16049. } catch (err) {
  16050. showToast('Error', err.message, 'error');
  16051. }
  16052. }
  16053. async function deleteUser(username) {
  16054. if (username === state.currentUser?.username) {
  16055. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  16056. return;
  16057. }
  16058. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  16059. return;
  16060. }
  16061. try {
  16062. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16063. method: 'DELETE'
  16064. });
  16065. const data = await res.json();
  16066. if (res.ok) {
  16067. showToast('User Deleted', `User ${username} has been removed`, 'success');
  16068. loadUsers(false);
  16069. } else {
  16070. showToast('Error', data.message || 'Failed to delete user', 'error');
  16071. }
  16072. } catch (err) {
  16073. showToast('Error', err.message, 'error');
  16074. }
  16075. }
  16076. function openSelfPasswordModal() {
  16077. document.getElementById('self-current-password').value = '';
  16078. document.getElementById('self-new-password').value = '';
  16079. document.getElementById('self-confirm-password').value = '';
  16080. document.getElementById('modal-self-password')?.classList.remove('hidden');
  16081. document.getElementById('self-current-password')?.focus();
  16082. }
  16083. function closeSelfPasswordModal() {
  16084. document.getElementById('modal-self-password')?.classList.add('hidden');
  16085. }
  16086. async function submitSelfPassword(event) {
  16087. event.preventDefault();
  16088. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16089. const newPassword = document.getElementById('self-new-password')?.value || '';
  16090. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16091. if (newPassword !== confirm) {
  16092. showToast('Validation Error', 'New passwords do not match', 'warning');
  16093. return;
  16094. }
  16095. if (newPassword.length < 4) {
  16096. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16097. return;
  16098. }
  16099. try {
  16100. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16101. method: 'POST',
  16102. headers: { 'Content-Type': 'application/json' },
  16103. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16104. });
  16105. const data = await res.json();
  16106. if (res.ok) {
  16107. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16108. closeSelfPasswordModal();
  16109. } else {
  16110. showToast('Error', data.message || 'Failed to change password', 'error');
  16111. }
  16112. } catch (err) {
  16113. showToast('Error', err.message, 'error');
  16114. }
  16115. }
  16116. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16117. state.services = [];
  16118. async function loadServices(manual = false) {
  16119. try {
  16120. const res = await fetch(`${API_BASE}/system/services`);
  16121. if (!res.ok) throw new Error('Failed to load services');
  16122. const data = await res.json();
  16123. state.services = data || [];
  16124. renderServicesTable();
  16125. updateCertificatesBadges();
  16126. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16127. } catch (err) {
  16128. if (manual) showToast('Error', err.message, 'error');
  16129. }
  16130. }
  16131. function renderServicesTable() {
  16132. const tbody = document.getElementById('services-table-body');
  16133. if (!tbody) return;
  16134. if (!state.services || state.services.length === 0) {
  16135. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16136. return;
  16137. }
  16138. tbody.innerHTML = state.services.map(s => {
  16139. const isOff = s.disabled;
  16140. const statusBadge = isOff
  16141. ? '<span class="px-2 py-0.5 rounded text-[10px] bg-rose-500/20 text-rose-300 border border-rose-500/30 font-bold uppercase">Disabled</span>'
  16142. : '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">Active</span>';
  16143. const toggleBtn = isOff
  16144. ? `<button onclick="toggleServiceState('${s.name}', false)" class="px-2.5 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30 border border-emerald-500/40 text-[11px] font-bold transition">Enable</button>`
  16145. : `<button onclick="toggleServiceState('${s.name}', true)" class="px-2.5 py-1 rounded-lg bg-rose-500/20 text-rose-300 hover:bg-rose-500/30 border border-rose-500/40 text-[11px] font-bold transition">Disable</button>`;
  16146. let certBadge = '';
  16147. if (s.name === 'www-ssl') {
  16148. if (s.certificate) {
  16149. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-amber-300 border border-slate-700 font-mono">🔒 ${escapeHtml(s.certificate)}</span>`;
  16150. } else {
  16151. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-rose-500/10 text-rose-400 border border-rose-500/20 font-mono">⚠️ No Cert Selected</span>`;
  16152. }
  16153. }
  16154. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16155. return `
  16156. <tr class="hover:bg-slate-800/40 transition">
  16157. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16158. <td class="py-3 px-4">
  16159. <div class="flex items-center gap-2">
  16160. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16161. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" title="Edit Service" class="text-slate-500 hover:text-cyan-400 p-1 rounded hover:bg-slate-800/80 transition">
  16162. <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>
  16163. </button>
  16164. </div>
  16165. </td>
  16166. <td class="py-3 px-4">${statusBadge}</td>
  16167. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16168. <td class="py-3 px-4 text-right">
  16169. <div class="flex items-center justify-end gap-2">
  16170. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
  16171. <svg class="w-3.5 h-3.5 text-slate-400" 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>
  16172. <span>Edit</span>
  16173. </button>
  16174. ${toggleBtn}
  16175. </div>
  16176. </td>
  16177. </tr>
  16178. `;
  16179. }).join('');
  16180. }
  16181. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16182. document.getElementById('modal-service-name').value = serviceName;
  16183. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16184. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16185. document.getElementById('modal-service-port').value = currentPort;
  16186. const hintEl = document.getElementById('modal-service-port-hint');
  16187. const warnEl = document.getElementById('modal-service-warning');
  16188. const certGroup = document.getElementById('modal-service-cert-group');
  16189. const certSelect = document.getElementById('modal-service-cert-select');
  16190. if (serviceName === 'www') {
  16191. hintEl.textContent = 'Default HTTP web port: 80';
  16192. warnEl.classList.remove('hidden');
  16193. certGroup.classList.add('hidden');
  16194. } else if (serviceName === 'www-ssl') {
  16195. hintEl.textContent = 'Default HTTPS web port: 443';
  16196. warnEl.classList.remove('hidden');
  16197. certGroup.classList.remove('hidden');
  16198. const populateCertOptions = (certs) => {
  16199. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16200. (certs || []).forEach(c => {
  16201. const opt = document.createElement('option');
  16202. opt.value = c.name;
  16203. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16204. if (c.name === currentCert) opt.selected = true;
  16205. certSelect.appendChild(opt);
  16206. });
  16207. };
  16208. if (state.certificates && state.certificates.length > 0) {
  16209. populateCertOptions(state.certificates);
  16210. } else {
  16211. loadCertificates(false).then(() => {
  16212. populateCertOptions(state.certificates);
  16213. });
  16214. }
  16215. } else if (serviceName === 'telnet') {
  16216. hintEl.textContent = 'Default Telnet console port: 8282';
  16217. warnEl.classList.add('hidden');
  16218. certGroup.classList.add('hidden');
  16219. } else if (serviceName === 'ssh') {
  16220. hintEl.textContent = 'Default SSH port: 2222';
  16221. warnEl.classList.add('hidden');
  16222. certGroup.classList.add('hidden');
  16223. } else {
  16224. hintEl.textContent = '';
  16225. warnEl.classList.add('hidden');
  16226. certGroup.classList.add('hidden');
  16227. }
  16228. const modal = document.getElementById('modal-service-edit');
  16229. modal.classList.remove('hidden');
  16230. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16231. }
  16232. function closeEditServiceModal() {
  16233. const modal = document.getElementById('modal-service-edit');
  16234. if (modal) modal.classList.add('hidden');
  16235. }
  16236. async function submitSaveServicePort(event) {
  16237. event.preventDefault();
  16238. const name = document.getElementById('modal-service-name').value;
  16239. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16240. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16241. if (isNaN(port) || port < 1 || port > 65535) {
  16242. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16243. return;
  16244. }
  16245. const certSelect = document.getElementById('modal-service-cert-select');
  16246. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16247. try {
  16248. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16249. method: 'POST',
  16250. headers: { 'Content-Type': 'application/json' },
  16251. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16252. });
  16253. if (!res.ok) {
  16254. const errData = await res.json();
  16255. throw new Error(errData.message || 'Failed to update service settings');
  16256. }
  16257. closeEditServiceModal();
  16258. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16259. await loadServices();
  16260. } catch (err) {
  16261. showToast('Error', err.message, 'error');
  16262. }
  16263. }
  16264. async function toggleServiceState(serviceName, newDisabled) {
  16265. if (serviceName === 'www' && newDisabled) {
  16266. if (!confirm("WARNING: Disabling the Web service ('www') will turn off this Web UI and REST API. You will only be able to re-enable it via SSH (port 2222) or Telnet (port 8282) using 'ip service enable www'. Continue?")) {
  16267. return;
  16268. }
  16269. }
  16270. if (serviceName === 'www-ssl' && !newDisabled) {
  16271. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16272. if (!sslSvc || !sslSvc.certificate) {
  16273. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16274. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16275. return;
  16276. }
  16277. }
  16278. try {
  16279. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16280. method: 'POST',
  16281. headers: { 'Content-Type': 'application/json' },
  16282. body: JSON.stringify({ disabled: newDisabled })
  16283. });
  16284. if (!res.ok) {
  16285. const errData = await res.json();
  16286. throw new Error(errData.message || 'Failed to update service');
  16287. }
  16288. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16289. await loadServices();
  16290. } catch (err) {
  16291. showToast('Error', err.message, 'error');
  16292. }
  16293. }
  16294. // ==================== SYSTEM LOGS (/log) ====================
  16295. state.logs = [];
  16296. let logsTimer = null;
  16297. async function loadLogs(manual = false) {
  16298. const limitEl = document.getElementById('logs-limit-select');
  16299. const limit = limitEl ? limitEl.value : '100';
  16300. try {
  16301. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16302. if (!res.ok) throw new Error('Failed to load logs');
  16303. const data = await res.json();
  16304. state.logs = data.logs || [];
  16305. renderLogsTable();
  16306. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16307. } catch (err) {
  16308. if (manual) showToast('Error', err.message, 'error');
  16309. }
  16310. // Setup auto-refresh if enabled and on logs tab
  16311. if (!logsTimer && state.currentUser) {
  16312. logsTimer = setInterval(() => {
  16313. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16314. const auto = document.getElementById('logs-auto-refresh');
  16315. if (auto && auto.checked) {
  16316. loadLogs(false);
  16317. }
  16318. }
  16319. }, 3000);
  16320. }
  16321. }
  16322. function renderLogsTable() {
  16323. const tbody = document.getElementById('logs-table-body');
  16324. if (!tbody) return;
  16325. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16326. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16327. const filtered = state.logs.filter(entry => {
  16328. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16329. return false;
  16330. }
  16331. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16332. return false;
  16333. }
  16334. return true;
  16335. });
  16336. if (filtered.length === 0) {
  16337. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16338. return;
  16339. }
  16340. tbody.innerHTML = filtered.map(l => {
  16341. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16342. const topLower = l.topics.toLowerCase();
  16343. if (topLower.includes('auth')) {
  16344. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16345. } else if (topLower.includes('dhcp')) {
  16346. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16347. } else if (topLower.includes('route')) {
  16348. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16349. } else if (topLower.includes('firewall')) {
  16350. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16351. } else if (topLower.includes('error')) {
  16352. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16353. } else if (topLower.includes('system')) {
  16354. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16355. }
  16356. const d = new Date(l.time);
  16357. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16358. return `
  16359. <tr class="hover:bg-slate-800/40 transition">
  16360. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16361. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16362. <td class="py-2 px-3 whitespace-nowrap">
  16363. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16364. </td>
  16365. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16366. </tr>
  16367. `;
  16368. }).join('');
  16369. }
  16370. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16371. state.certificates = [];
  16372. async function loadCertificates(manual = false) {
  16373. try {
  16374. const res = await fetch(`${API_BASE}/certificates`);
  16375. if (!res.ok) throw new Error('Failed to load certificates');
  16376. state.certificates = await res.json() || [];
  16377. updateCertificatesBadges();
  16378. renderCertificatesTable();
  16379. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16380. } catch (err) {
  16381. if (manual) showToast('Error', err.message, 'error');
  16382. }
  16383. }
  16384. function updateCertificatesBadges() {
  16385. const total = (state.certificates || []).length;
  16386. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16387. const bCount = document.getElementById('badge-certs-count');
  16388. if (bCount) bCount.innerText = total;
  16389. const kpiTotal = document.getElementById('kpi-certs-total');
  16390. if (kpiTotal) kpiTotal.innerText = total;
  16391. const kpiCA = document.getElementById('kpi-certs-ca');
  16392. if (kpiCA) kpiCA.innerText = caCount;
  16393. const kpiHttps = document.getElementById('kpi-https-status');
  16394. if (kpiHttps) {
  16395. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16396. if (sslSvc) {
  16397. if (!sslSvc.disabled) {
  16398. kpiHttps.innerHTML = `<span class="text-emerald-400 font-bold">Enabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-400 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
  16399. } else {
  16400. kpiHttps.innerHTML = `<span class="text-rose-400 font-bold">Disabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-500 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
  16401. }
  16402. }
  16403. }
  16404. }
  16405. function renderCertificatesTable() {
  16406. const tbody = document.getElementById('certs-table-body');
  16407. if (!tbody) return;
  16408. if (!state.certificates || state.certificates.length === 0) {
  16409. tbody.innerHTML = '<tr><td colspan="6" class="py-8 text-center text-slate-500 text-xs">No certificates configured yet. Click "Create CA" or "Issue Cert" to begin.</td></tr>';
  16410. return;
  16411. }
  16412. tbody.innerHTML = state.certificates.map(c => {
  16413. let typeBadge = '';
  16414. if (c.is_ca) {
  16415. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-bold uppercase">🏛 CA</span>';
  16416. } else if (c.type === 'acme') {
  16417. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">🔒 Let\'s Encrypt</span>';
  16418. } else if (c.issuer && c.issuer !== c.common_name) {
  16419. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-bold uppercase">📜 Signed</span>';
  16420. } else {
  16421. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-700/60 text-slate-300 border border-slate-600 font-bold uppercase">📜 Self-Signed</span>';
  16422. }
  16423. const sansHtml = (c.sans && c.sans.length > 0)
  16424. ? c.sans.map(s => `<span class="inline-block px-1.5 py-0.2 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700 mr-1 mb-0.5">${escapeHtml(s)}</span>`).join('')
  16425. : '<span class="text-slate-500">-</span>';
  16426. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16427. let validStr = '-';
  16428. let validBadge = '';
  16429. if (validTo && !isNaN(validTo.getTime())) {
  16430. const now = new Date();
  16431. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16432. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16433. if (daysLeft < 0) {
  16434. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16435. } else if (daysLeft < 30) {
  16436. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16437. } else {
  16438. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16439. }
  16440. }
  16441. return `
  16442. <tr class="hover:bg-slate-800/40 transition">
  16443. <td class="py-3 px-4">${typeBadge}</td>
  16444. <td class="py-3 px-4">
  16445. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16446. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16447. </td>
  16448. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16449. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16450. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16451. <span>${validStr}</span> ${validBadge}
  16452. ${c.type === 'acme' ? `<div class="text-[10px] ${c.renewal_error ? 'text-rose-400' : 'text-slate-400'}">${c.renewal_error ? 'Renewal failed: ' + escapeHtml(c.renewal_error) : 'Automatic renewal enabled'}</div>` : ''}
  16453. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16454. </td>
  16455. <td class="py-3 px-4 text-right whitespace-nowrap">
  16456. <div class="flex items-center justify-end gap-1.5">
  16457. <button onclick="openViewCertModal('${c.name}')" title="View & Export PEM" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
  16458. <svg class="w-3.5 h-3.5 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
  16459. <span>View</span>
  16460. </button>
  16461. <button onclick="deleteCertificate('${c.name}')" title="Delete Certificate" class="px-2 py-1 rounded-lg bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[11px] transition">
  16462. <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  16463. </button>
  16464. </div>
  16465. </td>
  16466. </tr>
  16467. `;
  16468. }).join('');
  16469. }
  16470. // Create CA
  16471. function openCreateCAModal() {
  16472. document.getElementById('form-create-ca').reset();
  16473. document.getElementById('ca-days').value = '3650';
  16474. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16475. document.getElementById('ca-country').value = 'GR';
  16476. document.getElementById('ca-key-type').value = 'RSA-2048';
  16477. document.getElementById('modal-create-ca').classList.remove('hidden');
  16478. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16479. }
  16480. function closeCreateCAModal() {
  16481. document.getElementById('modal-create-ca').classList.add('hidden');
  16482. }
  16483. async function submitCreateCA(event) {
  16484. event.preventDefault();
  16485. const payload = {
  16486. name: document.getElementById('ca-name').value.trim(),
  16487. common_name: document.getElementById('ca-cn').value.trim(),
  16488. organization: document.getElementById('ca-org').value.trim(),
  16489. country: document.getElementById('ca-country').value.trim(),
  16490. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16491. key_type: document.getElementById('ca-key-type').value
  16492. };
  16493. try {
  16494. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16495. method: 'POST',
  16496. headers: { 'Content-Type': 'application/json' },
  16497. body: JSON.stringify(payload)
  16498. });
  16499. if (!res.ok) {
  16500. const errData = await res.json();
  16501. throw new Error(errData.message || 'Failed to create CA');
  16502. }
  16503. closeCreateCAModal();
  16504. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16505. await loadCertificates();
  16506. } catch (err) {
  16507. showToast('Error', err.message, 'error');
  16508. }
  16509. }
  16510. // Create Cert
  16511. function openCreateCertModal() {
  16512. document.getElementById('form-create-cert').reset();
  16513. document.getElementById('cert-days').value = '730';
  16514. document.getElementById('cert-key-type').value = 'RSA-2048';
  16515. const caSelect = document.getElementById('cert-ca-select');
  16516. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16517. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16518. const opt = document.createElement('option');
  16519. opt.value = ca.name;
  16520. opt.textContent = `${ca.name} (${ca.common_name})`;
  16521. caSelect.appendChild(opt);
  16522. });
  16523. document.getElementById('modal-create-cert').classList.remove('hidden');
  16524. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16525. }
  16526. function closeCreateCertModal() {
  16527. document.getElementById('modal-create-cert').classList.add('hidden');
  16528. }
  16529. async function submitCreateCert(event) {
  16530. event.preventDefault();
  16531. const rawSans = document.getElementById('cert-sans').value;
  16532. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16533. const caName = document.getElementById('cert-ca-select').value;
  16534. const payload = {
  16535. name: document.getElementById('cert-name').value.trim(),
  16536. common_name: document.getElementById('cert-cn').value.trim(),
  16537. ca_name: caName,
  16538. sans: sansList,
  16539. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16540. key_type: document.getElementById('cert-key-type').value,
  16541. is_server: true
  16542. };
  16543. try {
  16544. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16545. method: 'POST',
  16546. headers: { 'Content-Type': 'application/json' },
  16547. body: JSON.stringify(payload)
  16548. });
  16549. if (!res.ok) {
  16550. const errData = await res.json();
  16551. throw new Error(errData.message || 'Failed to issue certificate');
  16552. }
  16553. closeCreateCertModal();
  16554. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16555. await loadCertificates();
  16556. } catch (err) {
  16557. showToast('Error', err.message, 'error');
  16558. }
  16559. }
  16560. // Let's Encrypt
  16561. function openLetsEncryptModal() {
  16562. document.getElementById('form-letsencrypt').reset();
  16563. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16564. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16565. }
  16566. function closeLetsEncryptModal() {
  16567. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16568. }
  16569. async function submitLetsEncrypt(event) {
  16570. event.preventDefault();
  16571. const domain = document.getElementById('le-domain').value.trim();
  16572. const email = document.getElementById('le-email').value.trim();
  16573. let name = document.getElementById('le-name').value.trim();
  16574. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16575. const staging = document.getElementById('le-staging').checked;
  16576. const btn = document.getElementById('btn-submit-letsencrypt');
  16577. const origBtnHtml = btn.innerHTML;
  16578. btn.disabled = true;
  16579. btn.innerHTML = `<svg class="w-4 h-4 animate-spin text-white" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg> <span>Issuing (may take up to 60s)...</span>`;
  16580. try {
  16581. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16582. method: 'POST',
  16583. headers: { 'Content-Type': 'application/json' },
  16584. body: JSON.stringify({
  16585. name: name,
  16586. domain: domain,
  16587. email: email,
  16588. staging: staging
  16589. })
  16590. });
  16591. if (!res.ok) {
  16592. const errData = await res.json();
  16593. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16594. }
  16595. closeLetsEncryptModal();
  16596. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16597. await loadCertificates();
  16598. } catch (err) {
  16599. showToast('Let\'s Encrypt Error', err.message, 'error');
  16600. } finally {
  16601. btn.disabled = false;
  16602. btn.innerHTML = origBtnHtml;
  16603. }
  16604. }
  16605. // Import Cert
  16606. function openImportCertModal() {
  16607. document.getElementById('form-import-cert').reset();
  16608. document.getElementById('modal-import-cert').classList.remove('hidden');
  16609. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16610. }
  16611. function closeImportCertModal() {
  16612. document.getElementById('modal-import-cert').classList.add('hidden');
  16613. }
  16614. async function submitImportCert(event) {
  16615. event.preventDefault();
  16616. const payload = {
  16617. name: document.getElementById('import-cert-name').value.trim(),
  16618. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16619. key_pem: document.getElementById('import-key-pem').value.trim()
  16620. };
  16621. try {
  16622. const res = await fetch(`${API_BASE}/certificates/import`, {
  16623. method: 'POST',
  16624. headers: { 'Content-Type': 'application/json' },
  16625. body: JSON.stringify(payload)
  16626. });
  16627. if (!res.ok) {
  16628. const errData = await res.json();
  16629. throw new Error(errData.message || 'Failed to import certificate');
  16630. }
  16631. closeImportCertModal();
  16632. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16633. await loadCertificates();
  16634. } catch (err) {
  16635. showToast('Error', err.message, 'error');
  16636. }
  16637. }
  16638. // View / Export Modal
  16639. async function openViewCertModal(name) {
  16640. const c = (state.certificates || []).find(x => x.name === name);
  16641. if (!c) return;
  16642. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16643. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16644. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16645. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16646. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16647. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16648. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16649. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16650. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16651. document.getElementById('modal-view-cert').classList.remove('hidden');
  16652. try {
  16653. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16654. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16655. const data = await res.json();
  16656. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16657. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16658. } catch (err) {
  16659. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16660. document.getElementById('view-key-pem-text').value = '';
  16661. }
  16662. }
  16663. function closeViewCertModal() {
  16664. document.getElementById('modal-view-cert').classList.add('hidden');
  16665. }
  16666. function copyCertPEM() {
  16667. const text = document.getElementById('view-cert-pem-text').value;
  16668. if (!text) return;
  16669. navigator.clipboard.writeText(text).then(() => {
  16670. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16671. }).catch(() => {
  16672. showToast('Error', 'Failed to copy to clipboard', 'error');
  16673. });
  16674. }
  16675. function copyKeyPEM() {
  16676. const text = document.getElementById('view-key-pem-text').value;
  16677. if (!text) return;
  16678. navigator.clipboard.writeText(text).then(() => {
  16679. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16680. }).catch(() => {
  16681. showToast('Error', 'Failed to copy to clipboard', 'error');
  16682. });
  16683. }
  16684. async function deleteCertificate(name) {
  16685. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16686. return;
  16687. }
  16688. try {
  16689. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16690. method: 'DELETE'
  16691. });
  16692. if (!res.ok) {
  16693. const errData = await res.json();
  16694. throw new Error(errData.message || 'Failed to delete certificate');
  16695. }
  16696. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16697. await loadCertificates();
  16698. } catch (err) {
  16699. showToast('Error', err.message, 'error');
  16700. }
  16701. }
  16702. // Refresh immediately when returning to a backgrounded controller tab.
  16703. document.addEventListener('visibilitychange', () => {
  16704. if (!state.currentUser) return;
  16705. if (document.hidden) {
  16706. if (trafficEventSource) trafficEventSource.close();
  16707. trafficEventSource = null;
  16708. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16709. trafficPollFallback = null;
  16710. } else {
  16711. fetchData(false);
  16712. initLiveTrafficStream();
  16713. if (state.activeTab === 'bwtest') loadBwTestView();
  16714. }
  16715. });
  16716. async function loadUpdateStatus(populate = true) {
  16717. try {
  16718. const res = await fetch(`${API_BASE}/update/status`);
  16719. if (!res.ok) throw new Error(await responseError(res));
  16720. const data = await res.json();
  16721. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16722. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16723. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16724. document.getElementById('update-state').textContent = data.state || 'idle';
  16725. document.getElementById('update-log').textContent = data.log || '';
  16726. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16727. }
  16728. async function saveUpdateConfig() {
  16729. try {
  16730. const repository = document.getElementById('update-repository').value.trim();
  16731. const branch = 'master';
  16732. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16733. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16734. if (!res.ok) throw new Error(await responseError(res));
  16735. document.getElementById('update-install-button').disabled = true;
  16736. document.getElementById('update-available').textContent = '—';
  16737. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16738. await loadUpdateStatus(false);
  16739. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16740. }
  16741. async function checkUpdate() {
  16742. try {
  16743. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16744. if (!res.ok) throw new Error(await responseError(res));
  16745. const data = await res.json();
  16746. document.getElementById('update-available').textContent = data.available_version;
  16747. document.getElementById('update-install-button').disabled = !data.update_available;
  16748. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16749. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16750. }
  16751. async function startUpdate(action) {
  16752. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16753. try {
  16754. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16755. if (!res.ok) throw new Error(await responseError(res));
  16756. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16757. await loadUpdateStatus(false);
  16758. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16759. }
  16760. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16761. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16762. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16763. function safeFirewallRow(row) {
  16764. const result = {...row};
  16765. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16766. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16767. return result;
  16768. }
  16769. function setFirewallDays(prefix, days) {
  16770. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16771. for (const d of ['sun','mon','tue','wed','thu','fri','sat']) { const el = document.getElementById(prefix+'-day-'+d); if (el) el.checked = selected.includes(d); }
  16772. }
  16773. function getFirewallDays(prefix) {
  16774. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16775. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16776. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16777. return selected.join(',');
  16778. }
  16779. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16780. const id = document.getElementById(kind+'-modal-id')?.value;
  16781. if (!id) { resetDisplay(); return; }
  16782. try {
  16783. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16784. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16785. resetDisplay(); await loadFirewall(false);
  16786. } catch(error) { showToast('Error', error.message, 'error'); }
  16787. }
  16788. function reviewLegacyFirewallSettings(kind, id) {
  16789. if (!id) return true;
  16790. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16791. const rule = (rows || []).find(r => r.id === id);
  16792. if (!rule) return true;
  16793. const unsupported = ['layer7_protocol','connection_bytes','connection_rate','pcc','in_bridge_port_list','out_bridge_port_list','tls_host','ingress_priority','priority','ipv4_options','dst_limit','psd','hotspot','route','sniff_target'];
  16794. const present = unsupported.filter(key => rule[key]);
  16795. if (!present.length) return true;
  16796. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16797. }
  16798. function refreshFirewallRejectTypes() {
  16799. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16800. const old=select.value;
  16801. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16802. const types=ipv6 ? ['icmp6-port-unreachable','icmp6-no-route','icmp6-adm-prohibited','icmp6-addr-unreachable','tcp-reset'] : ['icmp-port-unreachable','icmp-net-unreachable','icmp-host-unreachable','icmp-proto-unreachable','icmp-net-prohibited','icmp-host-prohibited','icmp-admin-prohibited','tcp-reset'];
  16803. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16804. if(types.includes(old))select.value=old;
  16805. }
  16806. function setFirewallActionSelection(kind, value) {
  16807. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16808. if(!Array.from(select.options).some(option=>option.value===value)) {
  16809. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16810. }
  16811. select.value=value;
  16812. }
  16813. // ==========================================
  16814. // REVERSE PROXY & APPLICATION GATEWAY
  16815. // ==========================================
  16816. state.proxyRules = [];
  16817. state.proxyConfig = null;
  16818. async function loadReverseProxy(manual = false) {
  16819. try {
  16820. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16821. fetch(`${API_BASE}/proxy/config`),
  16822. fetch(`${API_BASE}/proxy/rules`),
  16823. fetch(`${API_BASE}/certificates`).catch(() => null)
  16824. ]);
  16825. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16826. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16827. state.proxyConfig = await cfgRes.json();
  16828. state.proxyRules = await rulesRes.json() || [];
  16829. if (certsRes && certsRes.ok) {
  16830. state.certificates = await certsRes.json() || [];
  16831. }
  16832. renderProxyRules(state.proxyRules);
  16833. updateProxyMetrics();
  16834. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16835. } catch (err) {
  16836. console.error('loadReverseProxy error:', err);
  16837. if (manual) showToast('Error', err.message, 'error');
  16838. }
  16839. }
  16840. function updateProxyMetrics() {
  16841. const badge = document.getElementById('badge-proxy-count');
  16842. if (badge) badge.textContent = (state.proxyRules || []).length;
  16843. const metricRules = document.getElementById('proxy-metric-rules');
  16844. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16845. const cfg = state.proxyConfig;
  16846. const statusEl = document.getElementById('proxy-metric-status');
  16847. const portsEl = document.getElementById('proxy-metric-ports');
  16848. if (cfg) {
  16849. if (statusEl) {
  16850. if (cfg.enabled) {
  16851. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16852. } else {
  16853. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16854. }
  16855. }
  16856. if (portsEl) {
  16857. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16858. }
  16859. }
  16860. let totalRequests = 0;
  16861. const certSet = new Set();
  16862. (state.proxyRules || []).forEach(r => {
  16863. totalRequests += (r.stats && r.stats.requests) || 0;
  16864. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16865. });
  16866. const metricRequests = document.getElementById('proxy-metric-requests');
  16867. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16868. const metricCerts = document.getElementById('proxy-metric-certs');
  16869. if (metricCerts) metricCerts.textContent = certSet.size;
  16870. }
  16871. function renderProxyRules(rules) {
  16872. const tbody = document.getElementById('proxy-rules-table-body');
  16873. if (!tbody) return;
  16874. if (!rules || rules.length === 0) {
  16875. tbody.innerHTML = '<tr><td colspan="9" class="py-8 text-center text-slate-500 text-xs font-sans">No reverse proxy rules configured yet. Click "Add Proxy Rule" to begin.</td></tr>';
  16876. return;
  16877. }
  16878. tbody.innerHTML = rules.map(r => {
  16879. const isEnabled = r.enabled !== false;
  16880. const domainsStr = (r.domains && r.domains.length > 0) ? r.domains.map(d => `<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${escapeHtml(d)}</span>`).join(' ') : '<span class="px-1.5 py-0.5 rounded bg-violet-950/60 text-violet-300 border border-violet-800/40 font-mono text-[11px]">* (any)</span>';
  16881. const pathBadge = `<span class="px-2 py-0.5 rounded bg-cyan-950/60 text-cyan-300 border border-cyan-800/40 font-mono text-[11px] font-bold">${escapeHtml(r.path || '/')}</span>`;
  16882. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16883. if (r.protocol === 'https') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/40 text-[10px] font-mono font-bold">HTTPS</span>';
  16884. else if (r.protocol === 'http') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-sky-950 text-sky-400 border border-sky-800/40 text-[10px] font-mono">HTTP</span>';
  16885. const certBadge = r.certificate ? `<span class="ml-1 text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40 px-1 py-0.5 rounded font-mono truncate max-w-[120px] inline-block align-bottom" title="${escapeHtml(r.certificate)}">🔒 ${escapeHtml(r.certificate)}</span>` : '';
  16886. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16887. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16888. return `
  16889. <tr class="hover:bg-slate-800/40 transition">
  16890. <td class="py-3 px-4">
  16891. <button onclick="toggleProxyRuleState('${escapeHtml(r.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-emerald-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  16892. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  16893. </button>
  16894. </td>
  16895. <td class="py-3 px-4">
  16896. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16897. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16898. </td>
  16899. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16900. ${domainsStr}
  16901. </td>
  16902. <td class="py-3 px-4">
  16903. ${pathBadge}
  16904. </td>
  16905. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16906. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16907. </td>
  16908. <td class="py-3 px-4 whitespace-nowrap">
  16909. ${protoBadge}${certBadge}
  16910. </td>
  16911. <td class="py-3 px-4 font-mono">
  16912. ${stripBadge}
  16913. </td>
  16914. <td class="py-3 px-4 font-mono text-slate-300">
  16915. ${requests}
  16916. </td>
  16917. <td class="py-3 px-4 text-right whitespace-nowrap">
  16918. <button onclick="openEditProxyRuleModal('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs mr-1 transition font-sans">Edit</button>
  16919. <button onclick="deleteProxyRule('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-300 border border-rose-800/40 text-xs transition font-sans">Delete</button>
  16920. </td>
  16921. </tr>
  16922. `;
  16923. }).join('');
  16924. }
  16925. function populateProxyCertDropdown(selectedVal = '') {
  16926. const select = document.getElementById('proxy-rule-cert');
  16927. if (!select) return;
  16928. const certs = state.certificates || [];
  16929. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16930. certs.filter(c => !c.is_ca).forEach(c => {
  16931. const opt = document.createElement('option');
  16932. opt.value = c.name;
  16933. const cn = c.common_name ? ` (${c.common_name})` : '';
  16934. opt.textContent = `${c.name}${cn}`;
  16935. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16936. opt.selected = true;
  16937. }
  16938. select.appendChild(opt);
  16939. });
  16940. }
  16941. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16942. const select = document.getElementById('proxy-cfg-default-cert');
  16943. if (!select) return;
  16944. const certs = state.certificates || [];
  16945. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16946. certs.filter(c => !c.is_ca).forEach(c => {
  16947. const opt = document.createElement('option');
  16948. opt.value = c.name;
  16949. const cn = c.common_name ? ` (${c.common_name})` : '';
  16950. opt.textContent = `${c.name}${cn}`;
  16951. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16952. opt.selected = true;
  16953. }
  16954. select.appendChild(opt);
  16955. });
  16956. }
  16957. function onProxyProtoChange() {
  16958. const proto = document.getElementById('proxy-rule-proto')?.value;
  16959. const certSelect = document.getElementById('proxy-rule-cert');
  16960. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16961. if (proto === 'http') {
  16962. if (certSelect) certSelect.disabled = true;
  16963. if (redirectCheck) redirectCheck.disabled = true;
  16964. } else {
  16965. if (certSelect) certSelect.disabled = false;
  16966. if (redirectCheck) redirectCheck.disabled = false;
  16967. }
  16968. }
  16969. function openAddProxyRuleModal() {
  16970. const modal = document.getElementById('modal-proxy-rule');
  16971. if (!modal) return;
  16972. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16973. <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" /></svg>
  16974. <span>Add Reverse Proxy Rule</span>
  16975. `;
  16976. document.getElementById('proxy-rule-id').value = '';
  16977. document.getElementById('proxy-rule-name').value = '';
  16978. document.getElementById('proxy-rule-domains').value = '';
  16979. document.getElementById('proxy-rule-path').value = '/';
  16980. document.getElementById('proxy-rule-target').value = '';
  16981. document.getElementById('proxy-rule-proto').value = 'both';
  16982. document.getElementById('proxy-rule-strip-path').checked = false;
  16983. document.getElementById('proxy-rule-http-to-https').checked = false;
  16984. document.getElementById('proxy-rule-preserve-host').checked = false;
  16985. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16986. document.getElementById('proxy-rule-enabled').checked = true;
  16987. document.getElementById('proxy-rule-comment').value = '';
  16988. populateProxyCertDropdown('');
  16989. onProxyProtoChange();
  16990. modal.classList.remove('hidden');
  16991. }
  16992. function openEditProxyRuleModal(id) {
  16993. const modal = document.getElementById('modal-proxy-rule');
  16994. if (!modal) return;
  16995. const rule = (state.proxyRules || []).find(r => r.id === id);
  16996. if (!rule) {
  16997. showToast('Error', 'Rule not found', 'error');
  16998. return;
  16999. }
  17000. document.getElementById('proxy-rule-modal-title').innerHTML = `
  17001. <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
  17002. <span>Edit Reverse Proxy Rule</span>
  17003. `;
  17004. document.getElementById('proxy-rule-id').value = rule.id || '';
  17005. document.getElementById('proxy-rule-name').value = rule.name || '';
  17006. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  17007. document.getElementById('proxy-rule-path').value = rule.path || '/';
  17008. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  17009. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  17010. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  17011. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  17012. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  17013. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  17014. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  17015. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  17016. populateProxyCertDropdown(rule.certificate || '');
  17017. onProxyProtoChange();
  17018. modal.classList.remove('hidden');
  17019. }
  17020. function closeProxyRuleModal() {
  17021. const modal = document.getElementById('modal-proxy-rule');
  17022. if (modal) modal.classList.add('hidden');
  17023. }
  17024. async function saveProxyRule(event) {
  17025. event.preventDefault();
  17026. const id = document.getElementById('proxy-rule-id').value;
  17027. const name = document.getElementById('proxy-rule-name').value.trim();
  17028. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  17029. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  17030. const target = document.getElementById('proxy-rule-target').value.trim();
  17031. const proto = document.getElementById('proxy-rule-proto').value;
  17032. const cert = document.getElementById('proxy-rule-cert').value;
  17033. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  17034. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  17035. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  17036. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  17037. const enabled = document.getElementById('proxy-rule-enabled').checked;
  17038. const comment = document.getElementById('proxy-rule-comment').value.trim();
  17039. let domains = [];
  17040. if (rawDomains && rawDomains !== '*') {
  17041. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  17042. }
  17043. const payload = {
  17044. id: id || undefined,
  17045. name,
  17046. domains,
  17047. path: pathVal,
  17048. target_url: target,
  17049. protocol: proto,
  17050. certificate: cert,
  17051. strip_path: stripPath,
  17052. http_to_https: httpToHttps,
  17053. preserve_host: preserveHost,
  17054. insecure_tls: insecureTLS,
  17055. enabled,
  17056. comment
  17057. };
  17058. try {
  17059. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  17060. const method = id ? 'PUT' : 'POST';
  17061. const res = await fetch(url, {
  17062. method,
  17063. headers: { 'Content-Type': 'application/json' },
  17064. body: JSON.stringify(payload)
  17065. });
  17066. if (!res.ok) {
  17067. const errData = await res.json().catch(() => ({}));
  17068. throw new Error(errData.message || 'Failed to save proxy rule');
  17069. }
  17070. closeProxyRuleModal();
  17071. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  17072. await loadReverseProxy(false);
  17073. } catch (err) {
  17074. showToast('Error', err.message, 'error');
  17075. }
  17076. }
  17077. async function deleteProxyRule(id) {
  17078. const rule = (state.proxyRules || []).find(r => r.id === id);
  17079. const name = rule ? rule.name : id;
  17080. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  17081. return;
  17082. }
  17083. try {
  17084. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  17085. method: 'DELETE'
  17086. });
  17087. if (!res.ok) {
  17088. const errData = await res.json().catch(() => ({}));
  17089. throw new Error(errData.message || 'Failed to delete rule');
  17090. }
  17091. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17092. await loadReverseProxy(false);
  17093. } catch (err) {
  17094. showToast('Error', err.message, 'error');
  17095. }
  17096. }
  17097. async function toggleProxyRuleState(id, currentState) {
  17098. try {
  17099. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17100. method: 'POST',
  17101. headers: { 'Content-Type': 'application/json' },
  17102. body: JSON.stringify({ enabled: !currentState })
  17103. });
  17104. if (!res.ok) {
  17105. const errData = await res.json().catch(() => ({}));
  17106. throw new Error(errData.message || 'Failed to toggle rule state');
  17107. }
  17108. await loadReverseProxy(false);
  17109. } catch (err) {
  17110. showToast('Error', err.message, 'error');
  17111. }
  17112. }
  17113. function openProxyConfigModal() {
  17114. const modal = document.getElementById('modal-proxy-config');
  17115. if (!modal) return;
  17116. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17117. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17118. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17119. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17120. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17121. modal.classList.remove('hidden');
  17122. }
  17123. function closeProxyConfigModal() {
  17124. const modal = document.getElementById('modal-proxy-config');
  17125. if (modal) modal.classList.add('hidden');
  17126. }
  17127. async function saveProxyConfig(event) {
  17128. event.preventDefault();
  17129. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17130. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17131. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17132. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17133. const payload = {
  17134. enabled,
  17135. http_port: httpPort,
  17136. https_port: httpsPort,
  17137. default_cert: defaultCert
  17138. };
  17139. try {
  17140. const res = await fetch(`${API_BASE}/proxy/config`, {
  17141. method: 'POST',
  17142. headers: { 'Content-Type': 'application/json' },
  17143. body: JSON.stringify(payload)
  17144. });
  17145. if (!res.ok) {
  17146. const errData = await res.json().catch(() => ({}));
  17147. throw new Error(errData.message || 'Failed to update proxy settings');
  17148. }
  17149. closeProxyConfigModal();
  17150. showToast('Success', 'Reverse proxy settings updated', 'success');
  17151. await loadReverseProxy(false);
  17152. } catch (err) {
  17153. showToast('Error', err.message, 'error');
  17154. }
  17155. }
  17156. // ==================== SD-WAN Controller ====================
  17157. async function loadSDWAN(manual = false) {
  17158. try {
  17159. const [groupsRes, telemetryRes] = await Promise.all([
  17160. fetch(`${API_BASE}/sdwan/groups`),
  17161. fetch(`${API_BASE}/sdwan/telemetry`)
  17162. ]);
  17163. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17164. state.sdwanGroups = await groupsRes.json() || [];
  17165. if (telemetryRes.ok) {
  17166. state.sdwanTelemetry = await telemetryRes.json() || {};
  17167. }
  17168. renderSDWANGroups(state.sdwanGroups);
  17169. renderSDWANMembers(state.sdwanGroups);
  17170. updateSDWANMetrics(state.sdwanTelemetry);
  17171. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17172. } catch (err) {
  17173. console.error('loadSDWAN error:', err);
  17174. if (manual) showToast('Error', err.message, 'error');
  17175. }
  17176. }
  17177. function updateSDWANMetrics(telemetry) {
  17178. const groups = state.sdwanGroups || [];
  17179. const t = telemetry || {};
  17180. const badge = document.getElementById('badge-sdwan-count');
  17181. if (badge) badge.textContent = groups.length;
  17182. const metricGroups = document.getElementById('sdwan-metric-groups');
  17183. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17184. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17185. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17186. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17187. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17188. const metricDown = document.getElementById('sdwan-metric-down');
  17189. if (metricDown) metricDown.textContent = t.down_members || 0;
  17190. }
  17191. function renderSDWANGroups(groups) {
  17192. const tbody = document.getElementById('sdwan-groups-table-body');
  17193. if (!tbody) return;
  17194. if (!groups || groups.length === 0) {
  17195. tbody.innerHTML = '<tr><td colspan="8" class="py-8 text-center text-slate-500 text-xs font-sans">No SD-WAN groups configured yet. Click "Create SD-WAN Group" to begin.</td></tr>';
  17196. return;
  17197. }
  17198. tbody.innerHTML = groups.map(g => {
  17199. const isEnabled = g.disabled !== true;
  17200. const members = g.members || [];
  17201. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17202. // Build distribution progress bar
  17203. let distHtml = '';
  17204. if (members.length === 0) {
  17205. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17206. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17207. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17208. const segments = members.map((m, idx) => {
  17209. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17210. const col = colors[idx % colors.length];
  17211. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17212. }).join('');
  17213. const labels = members.map((m, idx) => {
  17214. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17215. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17216. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17217. }).join('');
  17218. distHtml = `
  17219. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17220. <div class="flex flex-wrap">${labels}</div>
  17221. `;
  17222. } else if (g.mode === 'lowest-latency') {
  17223. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17224. } else if (g.mode === 'lowest-loss') {
  17225. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17226. } else if (g.mode === 'failover') {
  17227. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17228. }
  17229. let modeBadge = '';
  17230. switch (g.mode) {
  17231. case 'weighted':
  17232. modeBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30 text-[10px] font-bold">Weighted LB</span>';
  17233. break;
  17234. case 'pcc':
  17235. modeBadge = '<span class="px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 text-[10px] font-bold">PCC Hashing</span>';
  17236. break;
  17237. case 'lowest-latency':
  17238. modeBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-[10px] font-bold">Lowest Latency SLA</span>';
  17239. break;
  17240. case 'lowest-loss':
  17241. modeBadge = '<span class="px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 text-[10px] font-bold">Lowest Loss SLA</span>';
  17242. break;
  17243. case 'failover':
  17244. modeBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/30 text-[10px] font-bold">Failover</span>';
  17245. break;
  17246. default:
  17247. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17248. }
  17249. const autoNatBadge = g.auto_nat
  17250. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17251. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17252. return `
  17253. <tr class="hover:bg-slate-800/40 transition">
  17254. <td class="py-3 px-4">
  17255. <button onclick="toggleSDWANGroupState('${escapeHtml(g.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  17256. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17257. </button>
  17258. </td>
  17259. <td class="py-3 px-4">
  17260. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17261. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(g.name)}</span>
  17262. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17263. </div>
  17264. </td>
  17265. <td class="py-3 px-4">${modeBadge}</td>
  17266. <td class="py-3 px-4">${distHtml}</td>
  17267. <td class="py-3 px-4">
  17268. <span class="px-2 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${members.length} links</span>
  17269. </td>
  17270. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17271. <td class="py-3 px-4">${autoNatBadge}</td>
  17272. <td class="py-3 px-4 text-right">
  17273. <div class="flex items-center justify-end gap-1.5">
  17274. <button onclick="openAddSDWANMemberModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-amber-300 transition" title="Add Member Link">
  17275. <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="M12 4v16m8-8H4"/></svg>
  17276. </button>
  17277. <button onclick="openEditSDWANGroupModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Group">
  17278. <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  17279. </button>
  17280. <button onclick="deleteSDWANGroup('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Delete Group">
  17281. <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  17282. </button>
  17283. </div>
  17284. </td>
  17285. </tr>
  17286. `;
  17287. }).join('');
  17288. }
  17289. function renderSDWANMembers(groups) {
  17290. const tbody = document.getElementById('sdwan-members-table-body');
  17291. if (!tbody) return;
  17292. const allMembers = [];
  17293. (groups || []).forEach(g => {
  17294. (g.members || []).forEach(m => {
  17295. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17296. });
  17297. });
  17298. if (allMembers.length === 0) {
  17299. tbody.innerHTML = '<tr><td colspan="11" class="py-8 text-center text-slate-500 text-xs font-sans">No member WAN links configured. Click "Add Member Link" above.</td></tr>';
  17300. return;
  17301. }
  17302. tbody.innerHTML = allMembers.map(m => {
  17303. const isEnabled = m.disabled !== true;
  17304. let statusBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 text-[10px] font-bold">HEALTHY</span>';
  17305. if (!isEnabled) {
  17306. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17307. } else if (m.status === 'DEGRADED') {
  17308. statusBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30 text-[10px] font-bold">DEGRADED</span>';
  17309. } else if (m.status === 'DOWN') {
  17310. statusBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[10px] font-bold animate-pulse">DOWN</span>';
  17311. }
  17312. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17313. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17314. return `
  17315. <tr class="hover:bg-slate-800/40 transition">
  17316. <td class="py-3 px-4">
  17317. <button onclick="toggleSDWANMemberState('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable link' : 'Click to enable link'}">
  17318. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17319. </button>
  17320. </td>
  17321. <td class="py-3 px-4">
  17322. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(m.group_name)}</span>
  17323. </td>
  17324. <td class="py-3 px-4">
  17325. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17326. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17327. </td>
  17328. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17329. <td class="py-3 px-4">
  17330. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17331. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17332. </td>
  17333. <td class="py-3 px-4">${statusBadge}</td>
  17334. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17335. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17336. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17337. </td>
  17338. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17339. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17340. </td>
  17341. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17342. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17343. </td>
  17344. <td class="py-3 px-4 text-right">
  17345. <div class="flex items-center justify-end gap-1.5">
  17346. <button onclick="openEditSDWANMemberModal('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Member">
  17347. <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  17348. </button>
  17349. <button onclick="deleteSDWANMember('${escapeHtml(m.group_id)}', '${escapeHtml(m.interface)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Remove Link">
  17350. <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  17351. </button>
  17352. </div>
  17353. </td>
  17354. </tr>
  17355. `;
  17356. }).join('');
  17357. }
  17358. // Modal handling for SD-WAN Groups
  17359. function openAddSDWANGroupModal() {
  17360. const modal = document.getElementById('modal-sdwan-group');
  17361. if (!modal) return;
  17362. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17363. document.getElementById('sdwan-group-id').value = '';
  17364. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17365. document.getElementById('sdwan-group-name').disabled = false;
  17366. document.getElementById('sdwan-group-mode').value = 'weighted';
  17367. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17368. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17369. document.getElementById('sdwan-group-probe-interval').value = 3;
  17370. document.getElementById('sdwan-group-auto-nat').checked = true;
  17371. document.getElementById('sdwan-group-comment').value = '';
  17372. modal.classList.remove('hidden');
  17373. }
  17374. function openEditSDWANGroupModal(id) {
  17375. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17376. if (!group) return;
  17377. const modal = document.getElementById('modal-sdwan-group');
  17378. if (!modal) return;
  17379. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17380. document.getElementById('sdwan-group-id').value = group.id;
  17381. document.getElementById('sdwan-group-name').value = group.name;
  17382. document.getElementById('sdwan-group-name').disabled = true;
  17383. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17384. if (group.mode === 'pcc') {
  17385. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17386. } else {
  17387. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17388. }
  17389. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17390. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17391. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17392. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17393. modal.classList.remove('hidden');
  17394. }
  17395. function closeSDWANGroupModal() {
  17396. const modal = document.getElementById('modal-sdwan-group');
  17397. if (modal) modal.classList.add('hidden');
  17398. }
  17399. function onSDWANModeChange() {
  17400. const mode = document.getElementById('sdwan-group-mode').value;
  17401. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17402. if (pccContainer) {
  17403. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17404. else pccContainer.classList.add('hidden');
  17405. }
  17406. }
  17407. async function saveSDWANGroup(event) {
  17408. event.preventDefault();
  17409. const id = document.getElementById('sdwan-group-id').value;
  17410. const name = document.getElementById('sdwan-group-name').value.trim();
  17411. const mode = document.getElementById('sdwan-group-mode').value;
  17412. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17413. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17414. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17415. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17416. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17417. const payload = {
  17418. id: id || undefined,
  17419. name,
  17420. mode,
  17421. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17422. probe_interval: probeInterval,
  17423. auto_nat: autoNAT,
  17424. comment,
  17425. members: existing ? existing.members : undefined
  17426. };
  17427. try {
  17428. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17429. method: 'POST',
  17430. headers: { 'Content-Type': 'application/json' },
  17431. body: JSON.stringify(payload)
  17432. });
  17433. if (!res.ok) {
  17434. const err = await res.json().catch(() => ({}));
  17435. throw new Error(err.message || 'Failed to save SD-WAN group');
  17436. }
  17437. closeSDWANGroupModal();
  17438. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17439. await loadSDWAN(false);
  17440. } catch (err) {
  17441. showToast('Error', err.message, 'error');
  17442. }
  17443. }
  17444. async function toggleSDWANGroupState(id, currentState) {
  17445. try {
  17446. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17447. method: 'POST',
  17448. headers: { 'Content-Type': 'application/json' },
  17449. body: JSON.stringify({ disabled: currentState })
  17450. });
  17451. if (!res.ok) throw new Error('Failed to update group state');
  17452. await loadSDWAN(false);
  17453. } catch (err) {
  17454. showToast('Error', err.message, 'error');
  17455. }
  17456. }
  17457. async function deleteSDWANGroup(id) {
  17458. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17459. const name = group ? group.name : id;
  17460. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17461. try {
  17462. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17463. method: 'DELETE'
  17464. });
  17465. if (!res.ok) {
  17466. const err = await res.json().catch(() => ({}));
  17467. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17468. }
  17469. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17470. await loadSDWAN(false);
  17471. } catch (err) {
  17472. showToast('Error', err.message, 'error');
  17473. }
  17474. }
  17475. // Modal handling for SD-WAN Members
  17476. function populateSDWANGroupsSelect(selectedId = '') {
  17477. const sel = document.getElementById('sdwan-member-group-id');
  17478. if (!sel) return;
  17479. sel.innerHTML = '';
  17480. (state.sdwanGroups || []).forEach(g => {
  17481. const opt = document.createElement('option');
  17482. opt.value = g.id;
  17483. opt.textContent = `${g.name} (${g.mode})`;
  17484. if (g.id === selectedId) opt.selected = true;
  17485. sel.appendChild(opt);
  17486. });
  17487. }
  17488. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17489. const sel = document.getElementById('sdwan-member-interface');
  17490. if (!sel) return;
  17491. sel.innerHTML = '';
  17492. (state.interfaces || []).forEach(i => {
  17493. const opt = document.createElement('option');
  17494. opt.value = i.name;
  17495. opt.textContent = `${i.name} (${i.role || i.type})`;
  17496. if (i.name === selectedVal) opt.selected = true;
  17497. sel.appendChild(opt);
  17498. });
  17499. }
  17500. function openAddSDWANMemberModal(defaultGroupId = null) {
  17501. const modal = document.getElementById('modal-sdwan-member');
  17502. if (!modal) return;
  17503. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17504. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17505. return;
  17506. }
  17507. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17508. document.getElementById('sdwan-member-id').value = '';
  17509. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17510. populateSDWANMemberInterfaceSelect();
  17511. document.getElementById('sdwan-member-gateway').value = '';
  17512. document.getElementById('sdwan-member-weight').value = 50;
  17513. document.getElementById('sdwan-member-priority').value = 1;
  17514. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17515. document.getElementById('sdwan-member-max-lat').value = 250;
  17516. document.getElementById('sdwan-member-max-loss').value = 20;
  17517. document.getElementById('sdwan-member-comment').value = '';
  17518. modal.classList.remove('hidden');
  17519. }
  17520. function openEditSDWANMemberModal(groupId, memberId) {
  17521. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17522. if (!group) return;
  17523. const member = (group.members || []).find(m => m.id === memberId);
  17524. if (!member) return;
  17525. const modal = document.getElementById('modal-sdwan-member');
  17526. if (!modal) return;
  17527. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17528. document.getElementById('sdwan-member-id').value = member.id;
  17529. populateSDWANGroupsSelect(group.id);
  17530. document.getElementById('sdwan-member-group-id').disabled = true;
  17531. populateSDWANMemberInterfaceSelect(member.interface);
  17532. document.getElementById('sdwan-member-interface').disabled = true;
  17533. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17534. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17535. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17536. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17537. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17538. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17539. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17540. modal.classList.remove('hidden');
  17541. }
  17542. function closeSDWANMemberModal() {
  17543. const modal = document.getElementById('modal-sdwan-member');
  17544. if (modal) {
  17545. document.getElementById('sdwan-member-group-id').disabled = false;
  17546. document.getElementById('sdwan-member-interface').disabled = false;
  17547. modal.classList.add('hidden');
  17548. }
  17549. }
  17550. async function saveSDWANMember(event) {
  17551. event.preventDefault();
  17552. const id = document.getElementById('sdwan-member-id').value;
  17553. let groupId = document.getElementById('sdwan-member-group-id').value;
  17554. let iface = document.getElementById('sdwan-member-interface').value;
  17555. // In edit mode with disabled selects, fallback to existing member data if needed
  17556. if (id) {
  17557. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17558. if (existingGroup) {
  17559. if (!groupId) groupId = existingGroup.id;
  17560. const mem = (existingGroup.members || []).find(m => m.id === id);
  17561. if (mem && !iface) iface = mem.interface;
  17562. }
  17563. }
  17564. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17565. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17566. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17567. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17568. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17569. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17570. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17571. const payload = {
  17572. id: id || undefined,
  17573. interface: iface,
  17574. gateway,
  17575. weight,
  17576. priority,
  17577. target_probe: targetProbe,
  17578. max_latency: maxLatency,
  17579. max_loss: maxLoss,
  17580. comment
  17581. };
  17582. try {
  17583. const method = id ? 'PUT' : 'POST';
  17584. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17585. method,
  17586. headers: { 'Content-Type': 'application/json' },
  17587. body: JSON.stringify(payload)
  17588. });
  17589. if (!res.ok) {
  17590. const err = await res.json().catch(() => ({}));
  17591. throw new Error(err.message || 'Failed to save member link');
  17592. }
  17593. closeSDWANMemberModal();
  17594. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17595. await loadSDWAN(false);
  17596. } catch (err) {
  17597. showToast('Error', err.message, 'error');
  17598. }
  17599. }
  17600. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17601. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17602. if (!group) return;
  17603. const member = (group.members || []).find(m => m.id === memberId);
  17604. if (!member) return;
  17605. const payload = {
  17606. ...member,
  17607. disabled: currentState
  17608. };
  17609. try {
  17610. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17611. method: 'PUT',
  17612. headers: { 'Content-Type': 'application/json' },
  17613. body: JSON.stringify(payload)
  17614. });
  17615. if (!res.ok) throw new Error('Failed to update member state');
  17616. await loadSDWAN(false);
  17617. } catch (err) {
  17618. showToast('Error', err.message, 'error');
  17619. }
  17620. }
  17621. async function deleteSDWANMember(groupId, iface) {
  17622. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17623. try {
  17624. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17625. method: 'DELETE'
  17626. });
  17627. if (!res.ok) {
  17628. const err = await res.json().catch(() => ({}));
  17629. throw new Error(err.message || 'Failed to remove member link');
  17630. }
  17631. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17632. await loadSDWAN(false);
  17633. } catch (err) {
  17634. showToast('Error', err.message, 'error');
  17635. }
  17636. }
  17637. // ==============================================================================
  17638. // DYNAMIC ROUTING: RIP MODULE
  17639. // ==============================================================================
  17640. state.ripInstances = [];
  17641. state.ripInterfaces = [];
  17642. state.ripNeighborsLive = [];
  17643. state.ripRoutes = [];
  17644. state.selectedRipRow = {};
  17645. state.activeRipTab = 'instances';
  17646. function switchRipTab(tab) {
  17647. state.activeRipTab = tab;
  17648. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17649. const pane = document.getElementById(`rip-pane-${t}`);
  17650. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17651. if (pane) {
  17652. if (t === tab) pane.classList.remove('hidden');
  17653. else pane.classList.add('hidden');
  17654. }
  17655. if (btn) {
  17656. if (t === tab) {
  17657. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-rose-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  17658. } else {
  17659. 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';
  17660. }
  17661. }
  17662. });
  17663. }
  17664. function selectRipRow(tab, id) {
  17665. if (!state.selectedRipRow) state.selectedRipRow = {};
  17666. state.selectedRipRow[tab] = id;
  17667. if (tab === 'instances') {
  17668. renderRipInstances();
  17669. const btnEn = document.getElementById('btn-rip-inst-enable');
  17670. const btnDis = document.getElementById('btn-rip-inst-disable');
  17671. const btnRem = document.getElementById('btn-rip-inst-remove');
  17672. if (btnEn) btnEn.disabled = false;
  17673. if (btnDis) btnDis.disabled = false;
  17674. if (btnRem) btnRem.disabled = false;
  17675. } else if (tab === 'interfaces') {
  17676. renderRipInterfaces();
  17677. const btnEn = document.getElementById('btn-rip-iface-enable');
  17678. const btnDis = document.getElementById('btn-rip-iface-disable');
  17679. const btnRem = document.getElementById('btn-rip-iface-remove');
  17680. if (btnEn) btnEn.disabled = false;
  17681. if (btnDis) btnDis.disabled = false;
  17682. if (btnRem) btnRem.disabled = false;
  17683. }
  17684. }
  17685. function renderRipInstances() {
  17686. const tbody = document.getElementById('rip-instances-table-body');
  17687. if (!tbody) return;
  17688. const countEl = document.getElementById('rip-instances-footer-count');
  17689. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17690. let list = state.ripInstances || [];
  17691. if (filter) {
  17692. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17693. }
  17694. if (countEl) countEl.innerText = list.length;
  17695. const selId = state.selectedRipRow?.instances;
  17696. tbody.innerHTML = list.map((inst, idx) => {
  17697. const isSel = inst.id === selId;
  17698. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17699. const flagD = inst.disabled
  17700. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  17701. : (inst.running
  17702. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  17703. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  17704. const redist = [];
  17705. if (inst.redistribute_connected) redist.push('conn');
  17706. if (inst.redistribute_static) redist.push('static');
  17707. if (inst.redistribute_bgp) redist.push('bgp');
  17708. if (inst.redistribute_ospf) redist.push('ospf');
  17709. if (inst.redistribute_default) redist.push('default');
  17710. const filterBadges = [];
  17711. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  17712. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  17713. return `
  17714. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17715. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17716. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17717. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17718. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17719. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17720. ${filterBadges.join(' ')}
  17721. </td>
  17722. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${inst.version == 1 || inst.version === 'ripng' ? 'RIPng' : 'RIPv2'}</td>
  17723. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17724. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17725. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17726. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17727. </tr>
  17728. `;
  17729. }).join('');
  17730. }
  17731. function renderRipInterfaces() {
  17732. const tbody = document.getElementById('rip-interfaces-table-body');
  17733. if (!tbody) return;
  17734. const countEl = document.getElementById('rip-interfaces-footer-count');
  17735. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17736. let list = state.ripInterfaces || [];
  17737. if (filter) {
  17738. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17739. }
  17740. if (countEl) countEl.innerText = list.length;
  17741. const selId = state.selectedRipRow?.interfaces;
  17742. tbody.innerHTML = list.map((iface, idx) => {
  17743. const isSel = iface.id === selId;
  17744. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17745. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17746. return `
  17747. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17748. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17749. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17750. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17751. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17752. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17753. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17754. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17755. <td class="py-1.5 px-3">${iface.use_bfd ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  17756. </tr>
  17757. `;
  17758. }).join('');
  17759. }
  17760. function renderRipNeighbors() {
  17761. const tbody = document.getElementById('rip-neighbors-table-body');
  17762. if (!tbody) return;
  17763. const countEl = document.getElementById('rip-neighbors-footer-count');
  17764. const list = state.ripNeighborsLive || [];
  17765. if (countEl) countEl.innerText = list.length;
  17766. tbody.innerHTML = list.map((nbr, idx) => `
  17767. <tr class="hover:bg-[#1a2636] text-slate-300">
  17768. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17769. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17770. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17771. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17772. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17773. </tr>
  17774. `).join('');
  17775. }
  17776. function renderRipRoutes() {
  17777. const tbody = document.getElementById('rip-routes-table-body');
  17778. if (!tbody) return;
  17779. const countEl = document.getElementById('rip-routes-footer-count');
  17780. const list = state.ripRoutes || [];
  17781. if (countEl) countEl.innerText = list.length;
  17782. tbody.innerHTML = list.map((r, idx) => `
  17783. <tr class="hover:bg-[#1a2636] text-slate-300">
  17784. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17785. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17786. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17787. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17788. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17789. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17790. </tr>
  17791. `).join('');
  17792. }
  17793. function openRipInstanceModal() {
  17794. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17795. document.getElementById('modal-rip-instance-id').value = '';
  17796. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17797. document.getElementById('modal-rip-instance-version').value = '2';
  17798. document.getElementById('modal-rip-instance-update').value = '30';
  17799. document.getElementById('modal-rip-instance-timeout').value = '180';
  17800. document.getElementById('modal-rip-instance-garbage').value = '120';
  17801. document.getElementById('modal-rip-instance-metric').value = '1';
  17802. document.getElementById('modal-rip-instance-comment').value = '';
  17803. document.getElementById('modal-rip-instance-in-filter').value = '';
  17804. document.getElementById('modal-rip-instance-out-filter').value = '';
  17805. document.getElementById('modal-rip-instance-enabled').checked = true;
  17806. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17807. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17808. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17809. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17810. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17811. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17812. }
  17813. function openEditRipInstanceModal(id) {
  17814. const inst = (state.ripInstances || []).find(i => i.id === id);
  17815. if (!inst) return;
  17816. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17817. document.getElementById('modal-rip-instance-id').value = inst.id;
  17818. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17819. document.getElementById('modal-rip-instance-version').value = (inst.version == 1 || inst.version === 'ripng') ? '1' : '2';
  17820. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17821. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17822. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17823. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17824. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17825. document.getElementById('modal-rip-instance-in-filter').value = inst.in_filter || '';
  17826. document.getElementById('modal-rip-instance-out-filter').value = inst.out_filter || '';
  17827. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17828. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17829. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17830. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17831. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17832. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17833. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17834. }
  17835. function closeRipInstanceModal() {
  17836. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17837. }
  17838. async function submitRipInstance(e) {
  17839. e.preventDefault();
  17840. const id = document.getElementById('modal-rip-instance-id').value;
  17841. const payload = {
  17842. id: id || undefined,
  17843. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17844. version: parseInt(document.getElementById('modal-rip-instance-version').value, 10) || 2,
  17845. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17846. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17847. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17848. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17849. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17850. in_filter: (document.getElementById('modal-rip-instance-in-filter')?.value || '').trim(),
  17851. out_filter: (document.getElementById('modal-rip-instance-out-filter')?.value || '').trim(),
  17852. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17853. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17854. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17855. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17856. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17857. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17858. };
  17859. try {
  17860. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17861. method: 'POST',
  17862. headers: { 'Content-Type': 'application/json' },
  17863. body: JSON.stringify(payload)
  17864. });
  17865. if (!res.ok) throw new Error(await res.text());
  17866. closeRipInstanceModal();
  17867. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17868. await loadDynamicRouting(false);
  17869. } catch (err) {
  17870. showToast('Error', err.message, 'error');
  17871. }
  17872. }
  17873. async function enableSelectedRipInstance() {
  17874. const id = state.selectedRipRow?.instances;
  17875. if (!id) return;
  17876. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17877. await loadDynamicRouting(false);
  17878. }
  17879. async function disableSelectedRipInstance() {
  17880. const id = state.selectedRipRow?.instances;
  17881. if (!id) return;
  17882. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17883. await loadDynamicRouting(false);
  17884. }
  17885. async function removeSelectedRipInstance() {
  17886. const id = state.selectedRipRow?.instances;
  17887. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  17888. await fetch(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' });
  17889. state.selectedRipRow.instances = null;
  17890. await loadDynamicRouting(false);
  17891. }
  17892. function openRipInterfaceModal() {
  17893. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  17894. document.getElementById('modal-rip-iface-id').value = '';
  17895. const dl = document.getElementById('rip-iface-datalist');
  17896. if (dl) {
  17897. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17898. }
  17899. const instSel = document.getElementById('modal-rip-iface-instance');
  17900. if (instSel && instSel.tagName === 'SELECT') {
  17901. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17902. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17903. }
  17904. document.getElementById('modal-rip-iface-pattern').value = '*';
  17905. if (instSel) instSel.value = (state.ripInstances && state.ripInstances.length > 0) ? state.ripInstances[0].name : 'default';
  17906. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  17907. document.getElementById('modal-rip-iface-metric').value = '1';
  17908. document.getElementById('modal-rip-iface-comment').value = '';
  17909. document.getElementById('modal-rip-iface-enabled').checked = true;
  17910. document.getElementById('modal-rip-iface-passive').checked = false;
  17911. document.getElementById('modal-rip-iface-bfd').checked = false;
  17912. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17913. }
  17914. function openEditRipInterfaceModal(id) {
  17915. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  17916. if (!iface) return;
  17917. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  17918. document.getElementById('modal-rip-iface-id').value = iface.id;
  17919. const dl = document.getElementById('rip-iface-datalist');
  17920. if (dl) {
  17921. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17922. }
  17923. const instSel = document.getElementById('modal-rip-iface-instance');
  17924. if (instSel && instSel.tagName === 'SELECT') {
  17925. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17926. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17927. instSel.value = iface.instance || 'default';
  17928. } else if (instSel) {
  17929. instSel.value = iface.instance || '';
  17930. }
  17931. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '*';
  17932. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  17933. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  17934. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  17935. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  17936. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  17937. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  17938. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17939. }
  17940. function closeRipInterfaceModal() {
  17941. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  17942. }
  17943. async function submitRipInterface(e) {
  17944. e.preventDefault();
  17945. const id = document.getElementById('modal-rip-iface-id').value;
  17946. const payload = {
  17947. id: id || undefined,
  17948. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  17949. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  17950. mode: document.getElementById('modal-rip-iface-mode').value,
  17951. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  17952. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  17953. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  17954. passive: document.getElementById('modal-rip-iface-passive').checked,
  17955. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  17956. };
  17957. try {
  17958. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  17959. method: 'POST',
  17960. headers: { 'Content-Type': 'application/json' },
  17961. body: JSON.stringify(payload)
  17962. });
  17963. if (!res.ok) throw new Error(await res.text());
  17964. closeRipInterfaceModal();
  17965. showToast('Saved', `RIP interface template saved`, 'success');
  17966. await loadDynamicRouting(false);
  17967. } catch (err) {
  17968. showToast('Error', err.message, 'error');
  17969. }
  17970. }
  17971. async function enableSelectedRipInterface() {
  17972. const id = state.selectedRipRow?.interfaces;
  17973. if (!id) return;
  17974. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17975. await loadDynamicRouting(false);
  17976. }
  17977. async function disableSelectedRipInterface() {
  17978. const id = state.selectedRipRow?.interfaces;
  17979. if (!id) return;
  17980. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17981. await loadDynamicRouting(false);
  17982. }
  17983. async function removeSelectedRipInterface() {
  17984. const id = state.selectedRipRow?.interfaces;
  17985. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  17986. await fetch(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' });
  17987. state.selectedRipRow.interfaces = null;
  17988. await loadDynamicRouting(false);
  17989. }
  17990. // ==============================================================================
  17991. // DYNAMIC ROUTING: BFD MODULE
  17992. // ==============================================================================
  17993. state.bfdInstance = null;
  17994. state.bfdInterfaces = [];
  17995. state.bfdNeighbors = [];
  17996. state.bfdSessions = [];
  17997. state.selectedBfdRow = {};
  17998. state.activeBfdTab = 'config';
  17999. function switchBfdTab(tab) {
  18000. state.activeBfdTab = tab;
  18001. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  18002. const pane = document.getElementById(`bfd-pane-${t}`);
  18003. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  18004. if (pane) {
  18005. if (t === tab) pane.classList.remove('hidden');
  18006. else pane.classList.add('hidden');
  18007. }
  18008. if (btn) {
  18009. if (t === tab) {
  18010. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-amber-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18011. } else {
  18012. 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';
  18013. }
  18014. }
  18015. });
  18016. }
  18017. function selectBfdRow(tab, id) {
  18018. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  18019. state.selectedBfdRow[tab] = id;
  18020. if (tab === 'interfaces') {
  18021. renderBfdInterfaces();
  18022. const btnEn = document.getElementById('btn-bfd-iface-enable');
  18023. const btnDis = document.getElementById('btn-bfd-iface-disable');
  18024. const btnRem = document.getElementById('btn-bfd-iface-remove');
  18025. if (btnEn) btnEn.disabled = false;
  18026. if (btnDis) btnDis.disabled = false;
  18027. if (btnRem) btnRem.disabled = false;
  18028. } else if (tab === 'peers') {
  18029. renderBfdPeers();
  18030. const btnEn = document.getElementById('btn-bfd-peer-enable');
  18031. const btnDis = document.getElementById('btn-bfd-peer-disable');
  18032. const btnRem = document.getElementById('btn-bfd-peer-remove');
  18033. if (btnEn) btnEn.disabled = false;
  18034. if (btnDis) btnDis.disabled = false;
  18035. if (btnRem) btnRem.disabled = false;
  18036. }
  18037. }
  18038. function renderBfdConfig() {
  18039. const inst = state.bfdInstance;
  18040. const pill = document.getElementById('bfd-live-status-pill');
  18041. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  18042. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  18043. const peerStat = document.getElementById('bfd-stat-peers');
  18044. const sessStat = document.getElementById('bfd-stat-sessions');
  18045. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  18046. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  18047. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  18048. const isEnabled = inst && (inst.enabled || inst.running || (!inst.disabled && (state.bfdInterfaces || []).length > 0));
  18049. if (!inst || inst.disabled || !isEnabled) {
  18050. if (pill) {
  18051. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  18052. pill.innerText = 'DISABLED';
  18053. }
  18054. if (toggleBtn) {
  18055. toggleBtn.innerText = 'Enable BFD';
  18056. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-amber-600 hover:bg-amber-500 text-white shadow-lg shadow-amber-500/20 transition';
  18057. }
  18058. } else {
  18059. if (pill) {
  18060. if (inst.running) {
  18061. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-emerald-950 text-emerald-300 border border-emerald-800/60 font-semibold';
  18062. pill.innerText = 'RUNNING (ACTIVE)';
  18063. } else {
  18064. 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';
  18065. pill.innerText = 'CONFIGURED';
  18066. }
  18067. }
  18068. if (toggleBtn) {
  18069. toggleBtn.innerText = 'Disable BFD';
  18070. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  18071. }
  18072. }
  18073. }
  18074. async function toggleBfdGlobalState() {
  18075. const current = state.bfdInstance;
  18076. const isCurrentlyEnabled = current && (current.enabled || current.running) && !current.disabled;
  18077. const newEnabled = !isCurrentlyEnabled;
  18078. const newDisabled = !newEnabled;
  18079. try {
  18080. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  18081. method: 'POST',
  18082. headers: { 'Content-Type': 'application/json' },
  18083. body: JSON.stringify({ enabled: newEnabled, disabled: newDisabled })
  18084. });
  18085. if (!res.ok) throw new Error(await res.text());
  18086. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  18087. await loadDynamicRouting(false);
  18088. } catch (err) {
  18089. showToast('Error', err.message, 'error');
  18090. }
  18091. }
  18092. function renderBfdInterfaces() {
  18093. const tbody = document.getElementById('bfd-interfaces-table-body');
  18094. if (!tbody) return;
  18095. const countEl = document.getElementById('bfd-interfaces-footer-count');
  18096. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  18097. let list = state.bfdInterfaces || [];
  18098. if (filter) {
  18099. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18100. }
  18101. if (countEl) countEl.innerText = list.length;
  18102. const selId = state.selectedBfdRow?.interfaces;
  18103. tbody.innerHTML = list.map((iface, idx) => {
  18104. const isSel = iface.id === selId;
  18105. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18106. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18107. return `
  18108. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  18109. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18110. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18111. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18112. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18113. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  18114. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  18115. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  18116. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  18117. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  18118. </tr>
  18119. `;
  18120. }).join('');
  18121. }
  18122. function renderBfdPeers() {
  18123. const tbody = document.getElementById('bfd-peers-table-body');
  18124. if (!tbody) return;
  18125. const countEl = document.getElementById('bfd-peers-footer-count');
  18126. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  18127. let list = state.bfdNeighbors || [];
  18128. if (filter) {
  18129. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18130. }
  18131. if (countEl) countEl.innerText = list.length;
  18132. const selId = state.selectedBfdRow?.peers;
  18133. tbody.innerHTML = list.map((p, idx) => {
  18134. const isSel = p.id === selId;
  18135. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18136. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18137. return `
  18138. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18139. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18140. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18141. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18142. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18143. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18144. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(p.local_address || 'auto')}</td>
  18145. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18146. </tr>
  18147. `;
  18148. }).join('');
  18149. }
  18150. function renderBfdSessions() {
  18151. const tbody = document.getElementById('bfd-sessions-table-body');
  18152. if (!tbody) return;
  18153. const countEl = document.getElementById('bfd-sessions-footer-count');
  18154. const list = state.bfdSessions || [];
  18155. if (countEl) countEl.innerText = list.length;
  18156. tbody.innerHTML = list.map((s, idx) => {
  18157. const isUp = (s.state || '').toLowerCase() === 'up';
  18158. const stateBadge = isUp
  18159. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">UP</span>'
  18160. : `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-500/20 text-rose-300 border border-rose-500/30">${escapeHtml(s.state || 'DOWN')}</span>`;
  18161. return `
  18162. <tr class="hover:bg-[#1a2636] text-slate-300">
  18163. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18164. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18165. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18166. <td class="py-1.5 px-3">${stateBadge}</td>
  18167. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18168. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18169. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18170. </tr>
  18171. `;
  18172. }).join('');
  18173. }
  18174. function openBfdInterfaceModal() {
  18175. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18176. document.getElementById('modal-bfd-iface-id').value = '';
  18177. const dl = document.getElementById('bfd-iface-datalist');
  18178. if (dl) {
  18179. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18180. }
  18181. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18182. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18183. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18184. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18185. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18186. document.getElementById('modal-bfd-iface-comment').value = '';
  18187. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18188. document.getElementById('modal-bfd-iface-passive').checked = false;
  18189. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18190. }
  18191. function openEditBfdInterfaceModal(id) {
  18192. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18193. if (!iface) return;
  18194. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18195. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18196. const dl = document.getElementById('bfd-iface-datalist');
  18197. if (dl) {
  18198. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18199. }
  18200. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18201. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18202. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18203. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18204. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18205. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18206. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18207. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18208. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18209. }
  18210. function closeBfdInterfaceModal() {
  18211. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18212. }
  18213. async function submitBfdInterface(e) {
  18214. e.preventDefault();
  18215. const id = document.getElementById('modal-bfd-iface-id').value;
  18216. const payload = {
  18217. id: id || undefined,
  18218. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18219. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18220. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18221. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18222. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18223. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18224. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18225. passive: document.getElementById('modal-bfd-iface-passive').checked
  18226. };
  18227. try {
  18228. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18229. method: 'POST',
  18230. headers: { 'Content-Type': 'application/json' },
  18231. body: JSON.stringify(payload)
  18232. });
  18233. if (!res.ok) throw new Error(await res.text());
  18234. closeBfdInterfaceModal();
  18235. showToast('Saved', `BFD profile saved`, 'success');
  18236. await loadDynamicRouting(false);
  18237. } catch (err) {
  18238. showToast('Error', err.message, 'error');
  18239. }
  18240. }
  18241. async function enableSelectedBfdInterface() {
  18242. const id = state.selectedBfdRow?.interfaces;
  18243. if (!id) return;
  18244. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18245. await loadDynamicRouting(false);
  18246. }
  18247. async function disableSelectedBfdInterface() {
  18248. const id = state.selectedBfdRow?.interfaces;
  18249. if (!id) return;
  18250. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18251. await loadDynamicRouting(false);
  18252. }
  18253. async function removeSelectedBfdInterface() {
  18254. const id = state.selectedBfdRow?.interfaces;
  18255. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18256. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' });
  18257. state.selectedBfdRow.interfaces = null;
  18258. await loadDynamicRouting(false);
  18259. }
  18260. function openBfdPeerModal() {
  18261. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18262. document.getElementById('modal-bfd-peer-id').value = '';
  18263. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18264. if (dlPeer) {
  18265. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18266. }
  18267. document.getElementById('modal-bfd-peer-address').value = '';
  18268. document.getElementById('modal-bfd-peer-interface').value = '';
  18269. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18270. if (localAddrEl) localAddrEl.value = '';
  18271. document.getElementById('modal-bfd-peer-comment').value = '';
  18272. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18273. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18274. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18275. }
  18276. function openEditBfdPeerModal(id) {
  18277. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18278. if (!p) return;
  18279. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18280. document.getElementById('modal-bfd-peer-id').value = p.id;
  18281. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18282. if (dlPeer) {
  18283. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18284. }
  18285. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18286. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18287. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18288. if (localAddrEl) localAddrEl.value = p.local_address || '';
  18289. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18290. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18291. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18292. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18293. }
  18294. function closeBfdPeerModal() {
  18295. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18296. }
  18297. async function submitBfdPeer(e) {
  18298. e.preventDefault();
  18299. const id = document.getElementById('modal-bfd-peer-id').value;
  18300. const localAddr = document.getElementById('modal-bfd-peer-local-address')?.value.trim() || '';
  18301. const payload = {
  18302. id: id || undefined,
  18303. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18304. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18305. local_address: localAddr,
  18306. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18307. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18308. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18309. };
  18310. try {
  18311. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18312. method: 'POST',
  18313. headers: { 'Content-Type': 'application/json' },
  18314. body: JSON.stringify(payload)
  18315. });
  18316. if (!res.ok) throw new Error(await res.text());
  18317. closeBfdPeerModal();
  18318. showToast('Saved', `BFD peer saved`, 'success');
  18319. await loadDynamicRouting(false);
  18320. } catch (err) {
  18321. showToast('Error', err.message, 'error');
  18322. }
  18323. }
  18324. async function enableSelectedBfdPeer() {
  18325. const id = state.selectedBfdRow?.peers;
  18326. if (!id) return;
  18327. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18328. if (!p) return;
  18329. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) });
  18330. await loadDynamicRouting(false);
  18331. }
  18332. async function disableSelectedBfdPeer() {
  18333. const id = state.selectedBfdRow?.peers;
  18334. if (!id) return;
  18335. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18336. if (!p) return;
  18337. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) });
  18338. await loadDynamicRouting(false);
  18339. }
  18340. async function removeSelectedBfdPeer() {
  18341. const id = state.selectedBfdRow?.peers;
  18342. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18343. await fetch(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' });
  18344. state.selectedBfdRow.peers = null;
  18345. await loadDynamicRouting(false);
  18346. }
  18347. // ==============================================================================
  18348. // DYNAMIC ROUTING: BABEL MODULE
  18349. // ==============================================================================
  18350. state.babelInstances = [];
  18351. state.babelInterfaces = [];
  18352. state.babelInterfacesLive = [];
  18353. state.babelNeighbors = [];
  18354. state.babelRoutes = [];
  18355. state.selectedBabelRow = {};
  18356. state.activeBabelTab = 'instances';
  18357. function switchBabelTab(tab) {
  18358. state.activeBabelTab = tab;
  18359. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18360. const pane = document.getElementById(`babel-pane-${t}`);
  18361. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18362. if (pane) {
  18363. if (t === tab) pane.classList.remove('hidden');
  18364. else pane.classList.add('hidden');
  18365. }
  18366. if (btn) {
  18367. if (t === tab) {
  18368. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-teal-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18369. } else {
  18370. 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';
  18371. }
  18372. }
  18373. });
  18374. }
  18375. function selectBabelRow(tab, id) {
  18376. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18377. state.selectedBabelRow[tab] = id;
  18378. if (tab === 'instances') {
  18379. renderBabelInstances();
  18380. const btnEn = document.getElementById('btn-babel-inst-enable');
  18381. const btnDis = document.getElementById('btn-babel-inst-disable');
  18382. const btnRem = document.getElementById('btn-babel-inst-remove');
  18383. if (btnEn) btnEn.disabled = false;
  18384. if (btnDis) btnDis.disabled = false;
  18385. if (btnRem) btnRem.disabled = false;
  18386. } else if (tab === 'interfaces') {
  18387. renderBabelInterfaces();
  18388. const btnEn = document.getElementById('btn-babel-iface-enable');
  18389. const btnDis = document.getElementById('btn-babel-iface-disable');
  18390. const btnRem = document.getElementById('btn-babel-iface-remove');
  18391. if (btnEn) btnEn.disabled = false;
  18392. if (btnDis) btnDis.disabled = false;
  18393. if (btnRem) btnRem.disabled = false;
  18394. }
  18395. }
  18396. function renderBabelInstances() {
  18397. const tbody = document.getElementById('babel-instances-table-body');
  18398. if (!tbody) return;
  18399. const countEl = document.getElementById('babel-instances-footer-count');
  18400. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18401. let list = state.babelInstances || [];
  18402. if (filter) {
  18403. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18404. }
  18405. if (countEl) countEl.innerText = list.length;
  18406. const selId = state.selectedBabelRow?.instances;
  18407. tbody.innerHTML = list.map((inst, idx) => {
  18408. const isSel = inst.id === selId;
  18409. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18410. const flagD = inst.disabled
  18411. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18412. : (inst.running
  18413. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18414. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18415. const redist = [];
  18416. if (inst.redistribute_connected) redist.push('conn');
  18417. if (inst.redistribute_static) redist.push('static');
  18418. if (inst.redistribute_bgp) redist.push('bgp');
  18419. if (inst.redistribute_ospf) redist.push('ospf');
  18420. if (inst.redistribute_default) redist.push('default');
  18421. const filterBadges = [];
  18422. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  18423. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  18424. return `
  18425. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18426. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18427. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18428. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18429. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18430. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18431. ${filterBadges.join(' ')}
  18432. </td>
  18433. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18434. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18435. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18436. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18437. </tr>
  18438. `;
  18439. }).join('');
  18440. }
  18441. function renderBabelInterfaces() {
  18442. const tbody = document.getElementById('babel-interfaces-table-body');
  18443. if (!tbody) return;
  18444. const countEl = document.getElementById('babel-interfaces-footer-count');
  18445. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18446. let list = state.babelInterfaces || [];
  18447. if (filter) {
  18448. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18449. }
  18450. if (countEl) countEl.innerText = list.length;
  18451. const selId = state.selectedBabelRow?.interfaces;
  18452. tbody.innerHTML = list.map((iface, idx) => {
  18453. const isSel = iface.id === selId;
  18454. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18455. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18456. return `
  18457. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18458. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18459. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18460. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18461. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18462. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18463. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18464. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18465. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18466. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18467. </tr>
  18468. `;
  18469. }).join('');
  18470. }
  18471. function renderBabelLiveInterfaces() {
  18472. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18473. if (!tbody) return;
  18474. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18475. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18476. let list = state.babelInterfacesLive || [];
  18477. if (filter) {
  18478. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18479. }
  18480. if (countEl) countEl.innerText = list.length;
  18481. tbody.innerHTML = list.map((iface, idx) => {
  18482. const isUp = (iface.state || '').toLowerCase() === 'up';
  18483. const stateBadge = isUp
  18484. ? '<span class="px-1.5 py-0.5 rounded text-[10px] font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">UP</span>'
  18485. : '<span class="px-1.5 py-0.5 rounded text-[10px] font-bold bg-rose-500/20 text-rose-400 border border-rose-500/30">DOWN</span>';
  18486. return `
  18487. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18488. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18489. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18490. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18491. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18492. <td class="py-1.5 px-3">${stateBadge}</td>
  18493. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18494. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18495. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18496. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18497. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18498. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18499. </tr>
  18500. `;
  18501. }).join('');
  18502. }
  18503. function renderBabelNeighbors() {
  18504. const tbody = document.getElementById('babel-neighbors-table-body');
  18505. if (!tbody) return;
  18506. const countEl = document.getElementById('babel-neighbors-footer-count');
  18507. const list = state.babelNeighbors || [];
  18508. if (countEl) countEl.innerText = list.length;
  18509. tbody.innerHTML = list.map((nbr, idx) => `
  18510. <tr class="hover:bg-[#1a2636] text-slate-300">
  18511. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18512. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18513. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18514. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18515. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18516. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18517. </tr>
  18518. `).join('');
  18519. }
  18520. function renderBabelRoutes() {
  18521. const tbody = document.getElementById('babel-routes-table-body');
  18522. if (!tbody) return;
  18523. const countEl = document.getElementById('babel-routes-footer-count');
  18524. const list = state.babelRoutes || [];
  18525. if (countEl) countEl.innerText = list.length;
  18526. tbody.innerHTML = list.map((r, idx) => `
  18527. <tr class="hover:bg-[#1a2636] text-slate-300">
  18528. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18529. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18530. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18531. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18532. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18533. </tr>
  18534. `).join('');
  18535. }
  18536. function openBabelInstanceModal() {
  18537. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18538. document.getElementById('modal-babel-instance-id').value = '';
  18539. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18540. document.getElementById('modal-babel-instance-routerid').value = '';
  18541. document.getElementById('modal-babel-instance-metric').value = '10';
  18542. document.getElementById('modal-babel-instance-comment').value = '';
  18543. document.getElementById('modal-babel-instance-in-filter').value = '';
  18544. document.getElementById('modal-babel-instance-out-filter').value = '';
  18545. document.getElementById('modal-babel-instance-enabled').checked = true;
  18546. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18547. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18548. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18549. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18550. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18551. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18552. }
  18553. function openEditBabelInstanceModal(id) {
  18554. const inst = (state.babelInstances || []).find(i => i.id === id);
  18555. if (!inst) return;
  18556. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18557. document.getElementById('modal-babel-instance-id').value = inst.id;
  18558. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18559. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18560. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18561. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18562. document.getElementById('modal-babel-instance-in-filter').value = inst.in_filter || '';
  18563. document.getElementById('modal-babel-instance-out-filter').value = inst.out_filter || '';
  18564. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18565. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18566. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18567. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18568. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18569. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18570. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18571. }
  18572. function closeBabelInstanceModal() {
  18573. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18574. }
  18575. async function submitBabelInstance(e) {
  18576. e.preventDefault();
  18577. const id = document.getElementById('modal-babel-instance-id').value;
  18578. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18579. const payload = {
  18580. id: id || undefined,
  18581. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18582. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18583. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18584. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18585. in_filter: (document.getElementById('modal-babel-instance-in-filter')?.value || '').trim(),
  18586. out_filter: (document.getElementById('modal-babel-instance-out-filter')?.value || '').trim(),
  18587. enabled: isEnabled,
  18588. disabled: !isEnabled,
  18589. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18590. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18591. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18592. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18593. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18594. };
  18595. try {
  18596. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18597. method: 'POST',
  18598. headers: { 'Content-Type': 'application/json' },
  18599. body: JSON.stringify(payload)
  18600. });
  18601. if (!res.ok) throw new Error(await res.text());
  18602. closeBabelInstanceModal();
  18603. showToast('Saved', `Babel instance saved`, 'success');
  18604. await loadDynamicRouting(false);
  18605. } catch (err) {
  18606. showToast('Error', err.message, 'error');
  18607. }
  18608. }
  18609. async function enableSelectedBabelInstance() {
  18610. const id = state.selectedBabelRow?.instances;
  18611. if (!id) return;
  18612. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18613. await loadDynamicRouting(false);
  18614. }
  18615. async function disableSelectedBabelInstance() {
  18616. const id = state.selectedBabelRow?.instances;
  18617. if (!id) return;
  18618. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18619. await loadDynamicRouting(false);
  18620. }
  18621. async function removeSelectedBabelInstance() {
  18622. const id = state.selectedBabelRow?.instances;
  18623. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18624. await fetch(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' });
  18625. state.selectedBabelRow.instances = null;
  18626. await loadDynamicRouting(false);
  18627. }
  18628. function toggleBabelAuthKey() {
  18629. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18630. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18631. if (wrap) {
  18632. if (authVal === 'mac') wrap.classList.remove('hidden');
  18633. else wrap.classList.add('hidden');
  18634. }
  18635. }
  18636. function openBabelInterfaceModal() {
  18637. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18638. document.getElementById('modal-babel-iface-id').value = '';
  18639. const instSel = document.getElementById('modal-babel-iface-instance');
  18640. if (instSel) {
  18641. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18642. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18643. if (state.babelInstances && state.babelInstances.length > 0) {
  18644. instSel.value = state.babelInstances[0].name;
  18645. }
  18646. }
  18647. const dl = document.getElementById('babel-iface-datalist');
  18648. if (dl) {
  18649. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18650. }
  18651. document.getElementById('modal-babel-iface-pattern').value = '*';
  18652. document.getElementById('modal-babel-iface-type').value = 'wired';
  18653. document.getElementById('modal-babel-iface-auth').value = 'none';
  18654. document.getElementById('modal-babel-iface-auth-key').value = '';
  18655. toggleBabelAuthKey();
  18656. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18657. document.getElementById('modal-babel-iface-hello').value = '4';
  18658. document.getElementById('modal-babel-iface-update').value = '16';
  18659. document.getElementById('modal-babel-iface-comment').value = '';
  18660. document.getElementById('modal-babel-iface-enabled').checked = true;
  18661. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18662. }
  18663. function openEditBabelInterfaceModal(id) {
  18664. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18665. if (!iface) return;
  18666. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18667. document.getElementById('modal-babel-iface-id').value = iface.id;
  18668. const instSel = document.getElementById('modal-babel-iface-instance');
  18669. if (instSel) {
  18670. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18671. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18672. instSel.value = iface.instance || 'all';
  18673. }
  18674. const dl = document.getElementById('babel-iface-datalist');
  18675. if (dl) {
  18676. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18677. }
  18678. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18679. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18680. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18681. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18682. toggleBabelAuthKey();
  18683. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18684. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18685. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18686. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18687. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18688. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18689. }
  18690. function closeBabelInterfaceModal() {
  18691. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18692. }
  18693. async function submitBabelInterface(e) {
  18694. e.preventDefault();
  18695. const id = document.getElementById('modal-babel-iface-id').value;
  18696. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18697. const payload = {
  18698. id: id || undefined,
  18699. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18700. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18701. type: document.getElementById('modal-babel-iface-type').value,
  18702. auth: document.getElementById('modal-babel-iface-auth').value,
  18703. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18704. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18705. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18706. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18707. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18708. disabled: !isEnabled
  18709. };
  18710. try {
  18711. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18712. method: 'POST',
  18713. headers: { 'Content-Type': 'application/json' },
  18714. body: JSON.stringify(payload)
  18715. });
  18716. if (!res.ok) throw new Error(await res.text());
  18717. closeBabelInterfaceModal();
  18718. showToast('Saved', `Babel interface template saved`, 'success');
  18719. await loadDynamicRouting(false);
  18720. } catch (err) {
  18721. showToast('Error', err.message, 'error');
  18722. }
  18723. }
  18724. async function enableSelectedBabelInterface() {
  18725. const id = state.selectedBabelRow?.interfaces;
  18726. if (!id) return;
  18727. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18728. await loadDynamicRouting(false);
  18729. }
  18730. async function disableSelectedBabelInterface() {
  18731. const id = state.selectedBabelRow?.interfaces;
  18732. if (!id) return;
  18733. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18734. await loadDynamicRouting(false);
  18735. }
  18736. async function removeSelectedBabelInterface() {
  18737. const id = state.selectedBabelRow?.interfaces;
  18738. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18739. await fetch(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' });
  18740. state.selectedBabelRow.interfaces = null;
  18741. await loadDynamicRouting(false);
  18742. }
  18743. // ==============================================================================
  18744. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18745. // ==============================================================================
  18746. state.radvInstances = [];
  18747. state.radvInterfaces = [];
  18748. state.selectedRadvRow = {};
  18749. state.activeRadvTab = 'instances';
  18750. function switchRadvTab(tab) {
  18751. state.activeRadvTab = tab;
  18752. ['instances', 'interfaces'].forEach(t => {
  18753. const pane = document.getElementById(`radv-pane-${t}`);
  18754. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18755. if (pane) {
  18756. if (t === tab) pane.classList.remove('hidden');
  18757. else pane.classList.add('hidden');
  18758. }
  18759. if (btn) {
  18760. if (t === tab) {
  18761. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-blue-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18762. } else {
  18763. 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';
  18764. }
  18765. }
  18766. });
  18767. }
  18768. function selectRadvRow(tab, id) {
  18769. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18770. state.selectedRadvRow[tab] = id;
  18771. if (tab === 'instances') {
  18772. renderRAdvInstances();
  18773. const btnEn = document.getElementById('btn-radv-inst-enable');
  18774. const btnDis = document.getElementById('btn-radv-inst-disable');
  18775. const btnRem = document.getElementById('btn-radv-inst-remove');
  18776. if (btnEn) btnEn.disabled = false;
  18777. if (btnDis) btnDis.disabled = false;
  18778. if (btnRem) btnRem.disabled = false;
  18779. } else if (tab === 'interfaces') {
  18780. renderRAdvInterfaces();
  18781. const btnEn = document.getElementById('btn-radv-iface-enable');
  18782. const btnDis = document.getElementById('btn-radv-iface-disable');
  18783. const btnRem = document.getElementById('btn-radv-iface-remove');
  18784. if (btnEn) btnEn.disabled = false;
  18785. if (btnDis) btnDis.disabled = false;
  18786. if (btnRem) btnRem.disabled = false;
  18787. }
  18788. }
  18789. function renderRAdvInstances() {
  18790. const tbody = document.getElementById('radv-instances-table-body');
  18791. if (!tbody) return;
  18792. const countEl = document.getElementById('radv-instances-footer-count');
  18793. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18794. let list = state.radvInstances || [];
  18795. if (filter) {
  18796. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18797. }
  18798. if (countEl) countEl.innerText = list.length;
  18799. const selId = state.selectedRadvRow?.instances;
  18800. tbody.innerHTML = list.map((inst, idx) => {
  18801. const isSel = inst.id === selId;
  18802. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18803. const flagD = inst.disabled
  18804. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  18805. : (inst.running
  18806. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  18807. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  18808. return `
  18809. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18810. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18811. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18812. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18813. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18814. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18815. </td>
  18816. <td class="py-1.5 px-3">${inst.running ? '<span class="text-emerald-400 font-bold">running</span>' : '<span class="text-slate-500">stopped</span>'}</td>
  18817. </tr>
  18818. `;
  18819. }).join('');
  18820. }
  18821. function renderRAdvInterfaces() {
  18822. const tbody = document.getElementById('radv-interfaces-table-body');
  18823. if (!tbody) return;
  18824. const countEl = document.getElementById('radv-interfaces-footer-count');
  18825. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18826. let list = state.radvInterfaces || [];
  18827. if (filter) {
  18828. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18829. }
  18830. if (countEl) countEl.innerText = list.length;
  18831. const selId = state.selectedRadvRow?.interfaces;
  18832. tbody.innerHTML = list.map((iface, idx) => {
  18833. const isSel = iface.id === selId;
  18834. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18835. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18836. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18837. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18838. return `
  18839. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18840. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18841. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18842. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18843. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18844. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18845. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18846. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18847. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18848. </tr>
  18849. `;
  18850. }).join('');
  18851. }
  18852. function openRAdvInstanceModal() {
  18853. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18854. document.getElementById('modal-radv-instance-id').value = '';
  18855. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18856. document.getElementById('modal-radv-instance-comment').value = '';
  18857. document.getElementById('modal-radv-instance-enabled').checked = true;
  18858. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18859. }
  18860. function openEditRAdvInstanceModal(id) {
  18861. const inst = (state.radvInstances || []).find(i => i.id === id);
  18862. if (!inst) return;
  18863. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18864. document.getElementById('modal-radv-instance-id').value = inst.id;
  18865. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18866. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18867. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18868. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18869. }
  18870. function closeRAdvInstanceModal() {
  18871. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18872. }
  18873. async function submitRAdvInstance(e) {
  18874. e.preventDefault();
  18875. const id = document.getElementById('modal-radv-instance-id').value;
  18876. const payload = {
  18877. id: id || undefined,
  18878. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18879. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18880. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  18881. };
  18882. try {
  18883. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  18884. method: 'POST',
  18885. headers: { 'Content-Type': 'application/json' },
  18886. body: JSON.stringify(payload)
  18887. });
  18888. if (!res.ok) throw new Error(await res.text());
  18889. closeRAdvInstanceModal();
  18890. showToast('Saved', `RAdv instance saved`, 'success');
  18891. await loadDynamicRouting(false);
  18892. } catch (err) {
  18893. showToast('Error', err.message, 'error');
  18894. }
  18895. }
  18896. async function enableSelectedRadvInstance() {
  18897. const id = state.selectedRadvRow?.instances;
  18898. if (!id) return;
  18899. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18900. await loadDynamicRouting(false);
  18901. }
  18902. async function disableSelectedRadvInstance() {
  18903. const id = state.selectedRadvRow?.instances;
  18904. if (!id) return;
  18905. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18906. await loadDynamicRouting(false);
  18907. }
  18908. async function removeSelectedRadvInstance() {
  18909. const id = state.selectedRadvRow?.instances;
  18910. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  18911. await fetch(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' });
  18912. state.selectedRadvRow.instances = null;
  18913. await loadDynamicRouting(false);
  18914. }
  18915. function openRAdvInterfaceModal() {
  18916. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  18917. document.getElementById('modal-radv-iface-id').value = '';
  18918. const dl = document.getElementById('radv-iface-datalist');
  18919. if (dl) {
  18920. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18921. }
  18922. const instSel = document.getElementById('modal-radv-iface-instance');
  18923. if (instSel && instSel.tagName === 'SELECT') {
  18924. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18925. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18926. instSel.value = (state.radvInstances && state.radvInstances.length > 0) ? state.radvInstances[0].name : 'default';
  18927. } else if (instSel) {
  18928. instSel.value = 'default';
  18929. }
  18930. document.getElementById('modal-radv-iface-interface').value = '*';
  18931. document.getElementById('modal-radv-iface-min-ra').value = '200';
  18932. document.getElementById('modal-radv-iface-max-ra').value = '600';
  18933. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  18934. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  18935. document.getElementById('modal-radv-iface-prefixes').value = '';
  18936. document.getElementById('modal-radv-iface-rdnss').value = '';
  18937. document.getElementById('modal-radv-iface-comment').value = '';
  18938. document.getElementById('modal-radv-iface-enabled').checked = true;
  18939. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18940. }
  18941. function openEditRAdvInterfaceModal(id) {
  18942. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  18943. if (!iface) return;
  18944. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  18945. document.getElementById('modal-radv-iface-id').value = iface.id;
  18946. const dl = document.getElementById('radv-iface-datalist');
  18947. if (dl) {
  18948. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18949. }
  18950. const instSel = document.getElementById('modal-radv-iface-instance');
  18951. if (instSel && instSel.tagName === 'SELECT') {
  18952. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18953. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18954. instSel.value = iface.instance || 'default';
  18955. } else if (instSel) {
  18956. instSel.value = iface.instance || '';
  18957. }
  18958. document.getElementById('modal-radv-iface-interface').value = iface.interface || '*';
  18959. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  18960. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  18961. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  18962. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  18963. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  18964. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  18965. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  18966. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  18967. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18968. }
  18969. function closeRAdvInterfaceModal() {
  18970. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  18971. }
  18972. async function submitRAdvInterface(e) {
  18973. e.preventDefault();
  18974. const id = document.getElementById('modal-radv-iface-id').value;
  18975. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  18976. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  18977. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18978. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18979. const payload = {
  18980. id: id || undefined,
  18981. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  18982. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  18983. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  18984. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  18985. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  18986. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  18987. prefixes: prefixes,
  18988. rdnss: rdnss,
  18989. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  18990. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  18991. };
  18992. try {
  18993. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  18994. method: 'POST',
  18995. headers: { 'Content-Type': 'application/json' },
  18996. body: JSON.stringify(payload)
  18997. });
  18998. if (!res.ok) throw new Error(await res.text());
  18999. closeRAdvInterfaceModal();
  19000. showToast('Saved', `RAdv interface saved`, 'success');
  19001. await loadDynamicRouting(false);
  19002. } catch (err) {
  19003. showToast('Error', err.message, 'error');
  19004. }
  19005. }
  19006. async function enableSelectedRadvInterface() {
  19007. const id = state.selectedRadvRow?.interfaces;
  19008. if (!id) return;
  19009. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  19010. await loadDynamicRouting(false);
  19011. }
  19012. async function disableSelectedRadvInterface() {
  19013. const id = state.selectedRadvRow?.interfaces;
  19014. if (!id) return;
  19015. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  19016. await loadDynamicRouting(false);
  19017. }
  19018. async function removeSelectedRadvInterface() {
  19019. const id = state.selectedRadvRow?.interfaces;
  19020. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  19021. await fetch(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' });
  19022. state.selectedRadvRow.interfaces = null;
  19023. await loadDynamicRouting(false);
  19024. }
  19025. // ================= EIGRP ROUTING CONTROLLER =================
  19026. state.selectedEigrpRow = { instances: null, networks: null, interfaces: null };
  19027. function switchEigrpTab(tab) {
  19028. state.activeEigrpTab = tab;
  19029. const tabs = ['instances', 'networks', 'interfaces', 'neighbors', 'topology'];
  19030. tabs.forEach(t => {
  19031. const btn = document.getElementById(`eigrp-tab-btn-${t}`);
  19032. const pane = document.getElementById(`eigrp-pane-${t}`);
  19033. if (btn) {
  19034. if (t === tab) {
  19035. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-purple-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  19036. } else {
  19037. 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';
  19038. }
  19039. }
  19040. if (pane) {
  19041. if (t === tab) pane.classList.remove('hidden');
  19042. else pane.classList.add('hidden');
  19043. }
  19044. });
  19045. const dlIface = document.getElementById('eigrp-iface-datalist');
  19046. if (dlIface && state.interfaces) {
  19047. dlIface.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19048. }
  19049. const dlNet = document.getElementById('eigrp-net-datalist');
  19050. if (dlNet && state.interfaces) {
  19051. const cidrs = [];
  19052. state.interfaces.forEach(i => {
  19053. (i.addrs || []).forEach(a => {
  19054. if (a.includes('.') && a.includes('/')) cidrs.push(a);
  19055. });
  19056. });
  19057. dlNet.innerHTML = '<option value="0.0.0.0/0">' + cidrs.map(c => `<option value="${escapeHtml(c)}">`).join('');
  19058. }
  19059. }
  19060. function selectEigrpRow(kind, id) {
  19061. if (!state.selectedEigrpRow) state.selectedEigrpRow = {};
  19062. if (state.selectedEigrpRow[kind] === id) {
  19063. state.selectedEigrpRow[kind] = null;
  19064. } else {
  19065. state.selectedEigrpRow[kind] = id;
  19066. }
  19067. if (kind === 'instances') {
  19068. renderEigrpInstances();
  19069. const isSel = !!state.selectedEigrpRow.instances;
  19070. const btnEn = document.getElementById('btn-eigrp-inst-enable');
  19071. const btnDis = document.getElementById('btn-eigrp-inst-disable');
  19072. const btnRem = document.getElementById('btn-eigrp-inst-remove');
  19073. if (btnEn) btnEn.disabled = !isSel;
  19074. if (btnDis) btnDis.disabled = !isSel;
  19075. if (btnRem) btnRem.disabled = !isSel;
  19076. } else if (kind === 'networks') {
  19077. renderEigrpNetworks();
  19078. const isSel = !!state.selectedEigrpRow.networks;
  19079. const btnRem = document.getElementById('btn-eigrp-net-remove');
  19080. if (btnRem) btnRem.disabled = !isSel;
  19081. } else if (kind === 'interfaces') {
  19082. renderEigrpInterfaces();
  19083. const isSel = !!state.selectedEigrpRow.interfaces;
  19084. const btnEn = document.getElementById('btn-eigrp-iface-enable');
  19085. const btnDis = document.getElementById('btn-eigrp-iface-disable');
  19086. const btnRem = document.getElementById('btn-eigrp-iface-remove');
  19087. if (btnEn) btnEn.disabled = !isSel;
  19088. if (btnDis) btnDis.disabled = !isSel;
  19089. if (btnRem) btnRem.disabled = !isSel;
  19090. }
  19091. }
  19092. // --- EIGRP INSTANCES ---
  19093. function renderEigrpInstances() {
  19094. const tbody = document.getElementById('eigrp-instances-table-body');
  19095. if (!tbody) return;
  19096. const countEl = document.getElementById('eigrp-instances-footer-count');
  19097. const filter = (document.getElementById('filter-eigrp-instances')?.value || '').toLowerCase();
  19098. let list = state.eigrpInstances || [];
  19099. if (filter) {
  19100. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || String(i.as || '').includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19101. }
  19102. if (countEl) countEl.innerText = list.length;
  19103. const selId = state.selectedEigrpRow?.instances;
  19104. tbody.innerHTML = list.map((inst, idx) => {
  19105. const isSel = inst.id === selId;
  19106. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19107. const flagD = inst.disabled
  19108. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  19109. : (inst.running
  19110. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  19111. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  19112. const redist = [];
  19113. if (inst.redistribute_connected) redist.push('conn');
  19114. if (inst.redistribute_static) redist.push('static');
  19115. if (inst.redistribute_ospf) redist.push('ospf');
  19116. if (inst.redistribute_bgp) redist.push('bgp');
  19117. const filterBadges = [];
  19118. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  19119. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  19120. return `
  19121. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('instances', '${inst.id}')" ondblclick="openEditEigrpInstanceModal('${inst.id}')">
  19122. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19123. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19124. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  19125. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  19126. <span class="text-purple-400">⚡</span> <span>${escapeHtml(inst.name || 'default')}</span>
  19127. ${filterBadges.join(' ')}
  19128. </td>
  19129. <td class="py-1.5 px-3 font-mono text-purple-300 font-bold">${inst.as || 100}</td>
  19130. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  19131. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  19132. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.variance || 1}</td>
  19133. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.max_paths || 4}</td>
  19134. </tr>
  19135. `;
  19136. }).join('');
  19137. }
  19138. function openEigrpInstanceModal() {
  19139. document.getElementById('eigrp-instance-modal-title').innerText = 'Add EIGRP Instance';
  19140. document.getElementById('modal-eigrp-instance-id').value = '';
  19141. document.getElementById('modal-eigrp-instance-name').value = 'eigrp' + ((state.eigrpInstances || []).length + 1);
  19142. document.getElementById('modal-eigrp-instance-as').value = '100';
  19143. document.getElementById('modal-eigrp-instance-routerid').value = '';
  19144. document.getElementById('modal-eigrp-instance-comment').value = '';
  19145. document.getElementById('modal-eigrp-instance-in-filter').value = '';
  19146. document.getElementById('modal-eigrp-instance-out-filter').value = '';
  19147. document.getElementById('modal-eigrp-instance-variance').value = '1';
  19148. document.getElementById('modal-eigrp-instance-maxpaths').value = '4';
  19149. document.getElementById('modal-eigrp-instance-metric').value = '10000';
  19150. document.getElementById('modal-eigrp-instance-redist-conn').checked = false;
  19151. document.getElementById('modal-eigrp-instance-redist-static').checked = false;
  19152. document.getElementById('modal-eigrp-instance-redist-ospf').checked = false;
  19153. document.getElementById('modal-eigrp-instance-redist-bgp').checked = false;
  19154. document.getElementById('modal-eigrp-instance-enabled').checked = true;
  19155. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19156. }
  19157. function openEditEigrpInstanceModal(id) {
  19158. const inst = (state.eigrpInstances || []).find(i => i.id === id);
  19159. if (!inst) return;
  19160. document.getElementById('eigrp-instance-modal-title').innerText = `Edit EIGRP Instance: ${inst.name}`;
  19161. document.getElementById('modal-eigrp-instance-id').value = inst.id;
  19162. document.getElementById('modal-eigrp-instance-name').value = inst.name || '';
  19163. document.getElementById('modal-eigrp-instance-as').value = inst.as || 100;
  19164. document.getElementById('modal-eigrp-instance-routerid').value = inst.router_id || '';
  19165. document.getElementById('modal-eigrp-instance-comment').value = inst.comment || '';
  19166. document.getElementById('modal-eigrp-instance-in-filter').value = inst.in_filter || '';
  19167. document.getElementById('modal-eigrp-instance-out-filter').value = inst.out_filter || '';
  19168. document.getElementById('modal-eigrp-instance-variance').value = inst.variance || 1;
  19169. document.getElementById('modal-eigrp-instance-maxpaths').value = inst.max_paths || 4;
  19170. document.getElementById('modal-eigrp-instance-metric').value = inst.default_metric || 10000;
  19171. document.getElementById('modal-eigrp-instance-redist-conn').checked = !!inst.redistribute_connected;
  19172. document.getElementById('modal-eigrp-instance-redist-static').checked = !!inst.redistribute_static;
  19173. document.getElementById('modal-eigrp-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  19174. document.getElementById('modal-eigrp-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  19175. document.getElementById('modal-eigrp-instance-enabled').checked = !inst.disabled;
  19176. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19177. }
  19178. function closeEigrpInstanceModal() {
  19179. document.getElementById('eigrp-instance-modal')?.classList.add('hidden');
  19180. }
  19181. async function submitEigrpInstance(e) {
  19182. e.preventDefault();
  19183. const payload = {
  19184. id: document.getElementById('modal-eigrp-instance-id').value.trim() || undefined,
  19185. name: document.getElementById('modal-eigrp-instance-name').value.trim(),
  19186. as: parseInt(document.getElementById('modal-eigrp-instance-as').value, 10) || 100,
  19187. router_id: document.getElementById('modal-eigrp-instance-routerid').value.trim(),
  19188. comment: document.getElementById('modal-eigrp-instance-comment').value.trim(),
  19189. in_filter: (document.getElementById('modal-eigrp-instance-in-filter')?.value || '').trim(),
  19190. out_filter: (document.getElementById('modal-eigrp-instance-out-filter')?.value || '').trim(),
  19191. variance: parseInt(document.getElementById('modal-eigrp-instance-variance').value, 10) || 1,
  19192. max_paths: parseInt(document.getElementById('modal-eigrp-instance-maxpaths').value, 10) || 4,
  19193. default_metric: parseInt(document.getElementById('modal-eigrp-instance-metric').value, 10) || 10000,
  19194. redistribute_connected: document.getElementById('modal-eigrp-instance-redist-conn').checked,
  19195. redistribute_static: document.getElementById('modal-eigrp-instance-redist-static').checked,
  19196. redistribute_ospf: document.getElementById('modal-eigrp-instance-redist-ospf').checked,
  19197. redistribute_bgp: document.getElementById('modal-eigrp-instance-redist-bgp').checked,
  19198. disabled: !document.getElementById('modal-eigrp-instance-enabled').checked
  19199. };
  19200. try {
  19201. const res = await fetch(`${API_BASE}/routing/eigrp/instances`, {
  19202. method: 'POST',
  19203. headers: { 'Content-Type': 'application/json' },
  19204. body: JSON.stringify(payload)
  19205. });
  19206. if (!res.ok) throw new Error(await res.text());
  19207. closeEigrpInstanceModal();
  19208. showToast('Saved', `EIGRP instance saved`, 'success');
  19209. await loadDynamicRouting(false);
  19210. } catch (err) {
  19211. showToast('Error', err.message, 'error');
  19212. }
  19213. }
  19214. async function enableSelectedEigrpInstance() {
  19215. const id = state.selectedEigrpRow?.instances;
  19216. if (!id) return;
  19217. await fetch(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  19218. await loadDynamicRouting(false);
  19219. }
  19220. async function disableSelectedEigrpInstance() {
  19221. const id = state.selectedEigrpRow?.instances;
  19222. if (!id) return;
  19223. await fetch(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  19224. await loadDynamicRouting(false);
  19225. }
  19226. async function removeSelectedEigrpInstance() {
  19227. const id = state.selectedEigrpRow?.instances;
  19228. if (!id || !confirm('Are you sure you want to remove this EIGRP instance?')) return;
  19229. await fetch(`${API_BASE}/routing/eigrp/instances/${id}`, { method: 'DELETE' });
  19230. state.selectedEigrpRow.instances = null;
  19231. await loadDynamicRouting(false);
  19232. }
  19233. // --- EIGRP NETWORKS ---
  19234. function renderEigrpNetworks() {
  19235. const tbody = document.getElementById('eigrp-networks-table-body');
  19236. if (!tbody) return;
  19237. const countEl = document.getElementById('eigrp-networks-footer-count');
  19238. const filter = (document.getElementById('filter-eigrp-networks')?.value || '').toLowerCase();
  19239. let list = state.eigrpNetworks || [];
  19240. if (filter) {
  19241. list = list.filter(n => (n.network || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  19242. }
  19243. if (countEl) countEl.innerText = list.length;
  19244. const selId = state.selectedEigrpRow?.networks;
  19245. tbody.innerHTML = list.map((net, idx) => {
  19246. const isSel = net.id === selId;
  19247. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19248. return `
  19249. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('networks', '${net.id}')">
  19250. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19251. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(net.comment || '')}</td>
  19252. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(net.network || '')}</td>
  19253. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(net.instance || 'all')}</td>
  19254. </tr>
  19255. `;
  19256. }).join('');
  19257. }
  19258. function openEigrpNetworkModal() {
  19259. document.getElementById('modal-eigrp-network-id').value = '';
  19260. const instSel = document.getElementById('modal-eigrp-network-instance');
  19261. if (instSel) {
  19262. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19263. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19264. }
  19265. document.getElementById('modal-eigrp-network-cidr').value = '0.0.0.0/0';
  19266. document.getElementById('modal-eigrp-network-comment').value = '';
  19267. document.getElementById('eigrp-network-modal')?.classList.remove('hidden');
  19268. }
  19269. function closeEigrpNetworkModal() {
  19270. document.getElementById('eigrp-network-modal')?.classList.add('hidden');
  19271. }
  19272. async function submitEigrpNetwork(e) {
  19273. e.preventDefault();
  19274. const payload = {
  19275. id: document.getElementById('modal-eigrp-network-id').value.trim() || undefined,
  19276. instance: document.getElementById('modal-eigrp-network-instance').value,
  19277. network: document.getElementById('modal-eigrp-network-cidr').value.trim(),
  19278. comment: document.getElementById('modal-eigrp-network-comment').value.trim()
  19279. };
  19280. try {
  19281. const res = await fetch(`${API_BASE}/routing/eigrp/networks`, {
  19282. method: 'POST',
  19283. headers: { 'Content-Type': 'application/json' },
  19284. body: JSON.stringify(payload)
  19285. });
  19286. if (!res.ok) throw new Error(await res.text());
  19287. closeEigrpNetworkModal();
  19288. showToast('Saved', `EIGRP network saved`, 'success');
  19289. await loadDynamicRouting(false);
  19290. } catch (err) {
  19291. showToast('Error', err.message, 'error');
  19292. }
  19293. }
  19294. async function removeSelectedEigrpNetwork() {
  19295. const id = state.selectedEigrpRow?.networks;
  19296. if (!id || !confirm('Are you sure you want to remove this EIGRP network?')) return;
  19297. await fetch(`${API_BASE}/routing/eigrp/networks/${id}`, { method: 'DELETE' });
  19298. state.selectedEigrpRow.networks = null;
  19299. await loadDynamicRouting(false);
  19300. }
  19301. // --- EIGRP INTERFACES ---
  19302. function renderEigrpInterfaces() {
  19303. const tbody = document.getElementById('eigrp-interfaces-table-body');
  19304. if (!tbody) return;
  19305. const countEl = document.getElementById('eigrp-interfaces-footer-count');
  19306. const filter = (document.getElementById('filter-eigrp-interfaces')?.value || '').toLowerCase();
  19307. let list = state.eigrpInterfaces || [];
  19308. if (filter) {
  19309. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19310. }
  19311. if (countEl) countEl.innerText = list.length;
  19312. const selId = state.selectedEigrpRow?.interfaces;
  19313. tbody.innerHTML = list.map((iface, idx) => {
  19314. const isSel = iface.id === selId;
  19315. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19316. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400 font-bold">E</span>';
  19317. return `
  19318. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('interfaces', '${iface.id}')" ondblclick="openEditEigrpInterfaceModal('${iface.id}')">
  19319. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19320. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19321. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  19322. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  19323. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  19324. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 5}s / ${iface.hold_time || 15}s</td>
  19325. <td class="py-1.5 px-3 font-mono ${iface.passive ? 'text-amber-400 font-bold' : 'text-slate-400'}">${iface.passive ? 'Yes' : 'No'}</td>
  19326. <td class="py-1.5 px-3 font-mono ${iface.split_horizon ? 'text-emerald-400' : 'text-slate-400'}">${iface.split_horizon ? 'Yes' : 'No'}</td>
  19327. <td class="py-1.5 px-3 text-slate-300 uppercase font-mono">${escapeHtml(iface.auth_mode || 'none')}</td>
  19328. </tr>
  19329. `;
  19330. }).join('');
  19331. }
  19332. function toggleEigrpAuthKey() {
  19333. const mode = document.getElementById('modal-eigrp-iface-auth-mode')?.value;
  19334. const wrap = document.getElementById('modal-eigrp-iface-auth-key-wrap');
  19335. if (wrap) {
  19336. if (mode === 'md5') wrap.classList.remove('hidden');
  19337. else wrap.classList.add('hidden');
  19338. }
  19339. }
  19340. function openEigrpInterfaceModal() {
  19341. document.getElementById('eigrp-interface-modal-title').innerText = 'Add EIGRP Interface Profile';
  19342. document.getElementById('modal-eigrp-iface-id').value = '';
  19343. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19344. if (instSel) {
  19345. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19346. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19347. }
  19348. const dl = document.getElementById('eigrp-iface-datalist');
  19349. if (dl && state.interfaces) {
  19350. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19351. }
  19352. document.getElementById('modal-eigrp-iface-interface').value = '*';
  19353. document.getElementById('modal-eigrp-iface-hello').value = '5';
  19354. document.getElementById('modal-eigrp-iface-hold').value = '15';
  19355. document.getElementById('modal-eigrp-iface-auth-mode').value = 'none';
  19356. document.getElementById('modal-eigrp-iface-auth-key').value = '';
  19357. toggleEigrpAuthKey();
  19358. document.getElementById('modal-eigrp-iface-passive').checked = false;
  19359. document.getElementById('modal-eigrp-iface-split-horizon').checked = true;
  19360. document.getElementById('modal-eigrp-iface-comment').value = '';
  19361. document.getElementById('modal-eigrp-iface-enabled').checked = true;
  19362. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19363. }
  19364. function openEditEigrpInterfaceModal(id) {
  19365. const iface = (state.eigrpInterfaces || []).find(i => i.id === id);
  19366. if (!iface) return;
  19367. document.getElementById('eigrp-interface-modal-title').innerText = `Edit EIGRP Interface: ${iface.interface}`;
  19368. document.getElementById('modal-eigrp-iface-id').value = iface.id;
  19369. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19370. if (instSel) {
  19371. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19372. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19373. instSel.value = iface.instance || 'all';
  19374. }
  19375. const dl = document.getElementById('eigrp-iface-datalist');
  19376. if (dl && state.interfaces) {
  19377. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19378. }
  19379. document.getElementById('modal-eigrp-iface-interface').value = iface.interface || '*';
  19380. document.getElementById('modal-eigrp-iface-hello').value = iface.hello_interval || 5;
  19381. document.getElementById('modal-eigrp-iface-hold').value = iface.hold_time || 15;
  19382. document.getElementById('modal-eigrp-iface-auth-mode').value = iface.auth_mode || 'none';
  19383. document.getElementById('modal-eigrp-iface-auth-key').value = iface.auth_key || '';
  19384. toggleEigrpAuthKey();
  19385. document.getElementById('modal-eigrp-iface-passive').checked = !!iface.passive;
  19386. document.getElementById('modal-eigrp-iface-split-horizon').checked = iface.split_horizon !== false;
  19387. document.getElementById('modal-eigrp-iface-comment').value = iface.comment || '';
  19388. document.getElementById('modal-eigrp-iface-enabled').checked = !iface.disabled;
  19389. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19390. }
  19391. function closeEigrpInterfaceModal() {
  19392. document.getElementById('eigrp-interface-modal')?.classList.add('hidden');
  19393. }
  19394. async function submitEigrpInterface(e) {
  19395. e.preventDefault();
  19396. const payload = {
  19397. id: document.getElementById('modal-eigrp-iface-id').value.trim() || undefined,
  19398. instance: document.getElementById('modal-eigrp-iface-instance').value,
  19399. interface: document.getElementById('modal-eigrp-iface-interface').value.trim(),
  19400. hello_interval: parseInt(document.getElementById('modal-eigrp-iface-hello').value, 10) || 5,
  19401. hold_time: parseInt(document.getElementById('modal-eigrp-iface-hold').value, 10) || 15,
  19402. passive: document.getElementById('modal-eigrp-iface-passive').checked,
  19403. split_horizon: document.getElementById('modal-eigrp-iface-split-horizon').checked,
  19404. auth_mode: document.getElementById('modal-eigrp-iface-auth-mode').value,
  19405. auth_key: document.getElementById('modal-eigrp-iface-auth-key').value.trim(),
  19406. comment: document.getElementById('modal-eigrp-iface-comment').value.trim(),
  19407. disabled: !document.getElementById('modal-eigrp-iface-enabled').checked
  19408. };
  19409. try {
  19410. const res = await fetch(`${API_BASE}/routing/eigrp/interfaces`, {
  19411. method: 'POST',
  19412. headers: { 'Content-Type': 'application/json' },
  19413. body: JSON.stringify(payload)
  19414. });
  19415. if (!res.ok) throw new Error(await res.text());
  19416. closeEigrpInterfaceModal();
  19417. showToast('Saved', `EIGRP interface saved`, 'success');
  19418. await loadDynamicRouting(false);
  19419. } catch (err) {
  19420. showToast('Error', err.message, 'error');
  19421. }
  19422. }
  19423. async function enableSelectedEigrpInterface() {
  19424. const id = state.selectedEigrpRow?.interfaces;
  19425. if (!id) return;
  19426. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  19427. await loadDynamicRouting(false);
  19428. }
  19429. async function disableSelectedEigrpInterface() {
  19430. const id = state.selectedEigrpRow?.interfaces;
  19431. if (!id) return;
  19432. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  19433. await loadDynamicRouting(false);
  19434. }
  19435. async function removeSelectedEigrpInterface() {
  19436. const id = state.selectedEigrpRow?.interfaces;
  19437. if (!id || !confirm('Are you sure you want to remove this EIGRP interface?')) return;
  19438. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}`, { method: 'DELETE' });
  19439. state.selectedEigrpRow.interfaces = null;
  19440. await loadDynamicRouting(false);
  19441. }
  19442. // --- EIGRP NEIGHBORS (LIVE) ---
  19443. function renderEigrpNeighbors() {
  19444. const tbody = document.getElementById('eigrp-neighbors-table-body');
  19445. if (!tbody) return;
  19446. const countEl = document.getElementById('eigrp-neighbors-footer-count');
  19447. const filter = (document.getElementById('filter-eigrp-neighbors')?.value || '').toLowerCase();
  19448. let list = state.eigrpNeighbors || [];
  19449. if (filter) {
  19450. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.interface || '').toLowerCase().includes(filter) || String(n.as || '').includes(filter));
  19451. }
  19452. if (countEl) countEl.innerText = list.length;
  19453. tbody.innerHTML = list.map((nbr, idx) => `
  19454. <tr class="hover:bg-[#1a2636] text-slate-300">
  19455. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19456. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${nbr.as || '-'}</td>
  19457. <td class="py-1.5 px-3 font-mono font-semibold text-purple-300">${escapeHtml(nbr.address || '')}</td>
  19458. <td class="py-1.5 px-3 font-mono text-white">${escapeHtml(nbr.interface || '')}</td>
  19459. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.hold_time || 0}s</td>
  19460. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '-')}</td>
  19461. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.srtt || 0}</td>
  19462. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.rto || 0}</td>
  19463. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.q_cnt || 0}</td>
  19464. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.seq_num || 0}</td>
  19465. </tr>
  19466. `).join('');
  19467. }
  19468. // --- EIGRP TOPOLOGY (LIVE) ---
  19469. function renderEigrpTopology() {
  19470. const tbody = document.getElementById('eigrp-topology-table-body');
  19471. if (!tbody) return;
  19472. const countEl = document.getElementById('eigrp-topology-footer-count');
  19473. const filter = (document.getElementById('filter-eigrp-topology')?.value || '').toLowerCase();
  19474. let list = state.eigrpTopology || [];
  19475. if (filter) {
  19476. list = list.filter(t => (t.network || '').toLowerCase().includes(filter) || (t.next_hop || '').toLowerCase().includes(filter) || (t.interface || '').toLowerCase().includes(filter) || String(t.as || '').includes(filter));
  19477. }
  19478. if (countEl) countEl.innerText = list.length;
  19479. tbody.innerHTML = list.map((top, idx) => `
  19480. <tr class="hover:bg-[#1a2636] text-slate-300">
  19481. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19482. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${top.as || '-'}</td>
  19483. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(top.network || '')}</td>
  19484. <td class="py-1.5 px-3 font-mono text-slate-300">${top.successors || 1}</td>
  19485. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(top.fd || '-')}</td>
  19486. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(top.next_hop || '-')}</td>
  19487. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(top.interface || '-')}</td>
  19488. </tr>
  19489. `).join('');
  19490. }