app.js 938 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665
  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="event.stopPropagation(); 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="event.stopPropagation(); 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 dir = delta < 0 ? 'up' : 'down';
  12034. try {
  12035. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/move`, {
  12036. method: 'POST',
  12037. headers: { 'Content-Type': 'application/json' },
  12038. body: JSON.stringify({ direction: dir })
  12039. });
  12040. if (!res.ok) {
  12041. const err = await res.json().catch(() => ({}));
  12042. showToast('Error', err.error || 'Failed to move filter rule', 'error');
  12043. return;
  12044. }
  12045. await loadDynamicRouting(false);
  12046. } catch (e) {
  12047. showToast('Error', e.message, 'error');
  12048. }
  12049. }
  12050. async function moveSelectedRoutingFilter(delta) {
  12051. const id = state.selectedFilterRow?.['rules'];
  12052. if (!id) {
  12053. showToast('Notice', 'Please select a routing filter rule first', 'info');
  12054. return;
  12055. }
  12056. await moveRoutingFilterOrder(id, delta);
  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. }