app.js 932 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603
  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. (state.interfaces || []).forEach(i => {
  3667. const opt = document.createElement('option');
  3668. opt.value = i.name;
  3669. opt.innerText = `${i.name} (${i.role || i.type})`;
  3670. if (i.name === currentVal) opt.selected = true;
  3671. sel.appendChild(opt);
  3672. });
  3673. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3674. const optgroup = document.createElement('optgroup');
  3675. optgroup.label = 'SD-WAN Groups';
  3676. state.sdwanGroups.forEach(g => {
  3677. const opt = document.createElement('option');
  3678. opt.value = g.name;
  3679. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3680. if (g.name === currentVal) opt.selected = true;
  3681. optgroup.appendChild(opt);
  3682. });
  3683. sel.appendChild(optgroup);
  3684. }
  3685. }
  3686. function populateAddressListSelect(selectId, currentVal = '') {
  3687. const sel = document.getElementById(selectId);
  3688. if (!sel) return;
  3689. sel.innerHTML = '<option value="">(None)</option>';
  3690. const cleanVal = (currentVal || '').replace(/^!/, '');
  3691. 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_'));
  3692. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3693. customNames.forEach(name => {
  3694. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3695. const opt = document.createElement('option');
  3696. opt.value = name;
  3697. opt.innerText = `${name} (${count} entries)`;
  3698. if (name === cleanVal) opt.selected = true;
  3699. sel.appendChild(opt);
  3700. });
  3701. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3702. const opt = document.createElement('option');
  3703. opt.value = cleanVal;
  3704. opt.innerText = cleanVal;
  3705. opt.selected = true;
  3706. sel.appendChild(opt);
  3707. }
  3708. populateCommonAddrListDatalist();
  3709. }
  3710. function populateCommonAddrListDatalist() {
  3711. const dl = document.getElementById('fw-addrlist-datalist');
  3712. if (!dl) return;
  3713. dl.innerHTML = '';
  3714. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3715. names.forEach(name => {
  3716. const opt = document.createElement('option');
  3717. opt.value = name;
  3718. dl.appendChild(opt);
  3719. });
  3720. }
  3721. function populateGeoIPSelect(selectId, currentVal = '') {
  3722. const sel = document.getElementById(selectId);
  3723. if (!sel) return;
  3724. sel.innerHTML = '<option value="">(None)</option>';
  3725. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3726. // Presets optgroup
  3727. const grpPresets = document.createElement('optgroup');
  3728. grpPresets.label = '⚡ Regional Presets';
  3729. const presets = [
  3730. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3731. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3732. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3733. ];
  3734. presets.forEach(p => {
  3735. const opt = document.createElement('option');
  3736. opt.value = p.code;
  3737. opt.innerText = p.label;
  3738. if (p.code === cleanVal) opt.selected = true;
  3739. grpPresets.appendChild(opt);
  3740. });
  3741. sel.appendChild(grpPresets);
  3742. // All Countries optgroup
  3743. const grpCountries = document.createElement('optgroup');
  3744. grpCountries.label = '🌍 All Countries';
  3745. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3746. countries.forEach(c => {
  3747. const opt = document.createElement('option');
  3748. opt.value = c.code;
  3749. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3750. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3751. if (c.code === cleanVal) opt.selected = true;
  3752. grpCountries.appendChild(opt);
  3753. });
  3754. sel.appendChild(grpCountries);
  3755. }
  3756. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3757. function switchFwRuleTab(tab) {
  3758. state.activeFwRuleTab = tab;
  3759. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3760. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3761. btn.classList.add('text-slate-400', 'border-transparent');
  3762. });
  3763. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3764. if (activeBtn) {
  3765. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3766. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3767. }
  3768. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3769. const activePane = document.getElementById(`fw-pane-${tab}`);
  3770. if (activePane) activePane.classList.remove('hidden');
  3771. if (tab === 'statistics') {
  3772. startFwStatPolling();
  3773. } else {
  3774. stopFwStatPolling();
  3775. }
  3776. }
  3777. function toggleFwField(fieldKey, expand) {
  3778. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3779. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3780. if (!plusBtn || !fieldBox) return;
  3781. if (expand) {
  3782. plusBtn.classList.add('hidden');
  3783. fieldBox.classList.remove('hidden');
  3784. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3785. if (valInput) valInput.focus();
  3786. } else {
  3787. fieldBox.classList.add('hidden');
  3788. plusBtn.classList.remove('hidden');
  3789. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3790. if (valInput) {
  3791. if (valInput.tagName === 'SELECT') {
  3792. valInput.selectedIndex = 0;
  3793. } else {
  3794. valInput.value = '';
  3795. }
  3796. }
  3797. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3798. if (invInput) invInput.checked = false;
  3799. if (fieldKey === 'cs') {
  3800. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3801. const el = document.getElementById(id);
  3802. if (el) el.checked = false;
  3803. });
  3804. }
  3805. if (fieldKey === 'natstate') {
  3806. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3807. const el = document.getElementById(id);
  3808. if (el) el.checked = false;
  3809. });
  3810. }
  3811. if (fieldKey === 'days') {
  3812. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3813. const el = document.getElementById(`fw-day-${d}`);
  3814. if (el) el.checked = true;
  3815. });
  3816. }
  3817. }
  3818. }
  3819. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3820. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3821. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3822. toggleFwField(fieldKey, true);
  3823. let strVal = String(value);
  3824. if (hasInvert) {
  3825. const inv = strVal.startsWith('!');
  3826. if (inv) strVal = strVal.slice(1);
  3827. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3828. if (invEl) invEl.checked = inv;
  3829. else if (inv) strVal = '!'+strVal;
  3830. }
  3831. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3832. 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; }
  3833. } else {
  3834. toggleFwField(fieldKey, false);
  3835. }
  3836. }
  3837. function getFwFieldVal(fieldKey, hasInvert = false) {
  3838. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3839. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3840. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3841. let v = valEl ? valEl.value.trim() : '';
  3842. if (!v) return '';
  3843. if (hasInvert) {
  3844. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3845. if (invEl && invEl.checked) {
  3846. v = '!' + v.replace(/^!/, '');
  3847. }
  3848. }
  3849. return v;
  3850. }
  3851. function toggleMaximizeFilterModal() {
  3852. const win = document.getElementById('filter-modal-window');
  3853. if (!win) return;
  3854. if (win.classList.contains('max-w-[720px]')) {
  3855. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3856. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3857. } else {
  3858. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3859. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3860. }
  3861. }
  3862. const FW_NATIVE_CHAINS = {
  3863. filter: [
  3864. { id: 'forward', label: 'FORWARD (routed through router)' },
  3865. { id: 'input', label: 'INPUT (destined to this router)' },
  3866. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3867. ],
  3868. nat: [
  3869. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3870. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3871. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3872. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3873. ],
  3874. mangle: [
  3875. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3876. { id: 'input', label: 'INPUT (destined to this machine)' },
  3877. { id: 'forward', label: 'FORWARD (routed through router)' },
  3878. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3879. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3880. ]
  3881. };
  3882. function populateChainDropdown(table, currentChain) {
  3883. const sel = document.getElementById(`${table}-modal-chain-select`);
  3884. if (!sel) return;
  3885. const cur = (currentChain || '').trim();
  3886. const lower = cur.toLowerCase();
  3887. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3888. const rules = state[rulesKey] || [];
  3889. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3890. const customChains = new Set();
  3891. rules.forEach(r => {
  3892. if (r.chain) {
  3893. const c = r.chain.trim();
  3894. const l = c.toLowerCase();
  3895. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3896. customChains.add(c);
  3897. }
  3898. }
  3899. });
  3900. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3901. if (isCurrentCustom) {
  3902. customChains.add(cur);
  3903. }
  3904. let html = '';
  3905. FW_NATIVE_CHAINS[table].forEach(c => {
  3906. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3907. });
  3908. if (customChains.size > 0) {
  3909. html += `<optgroup label="Custom Chains">`;
  3910. customChains.forEach(c => {
  3911. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3912. });
  3913. html += `</optgroup>`;
  3914. }
  3915. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3916. sel.innerHTML = html;
  3917. if (isCurrentCustom) {
  3918. sel.value = cur;
  3919. } else if (nativeIds.includes(lower)) {
  3920. sel.value = lower;
  3921. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3922. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3923. } else {
  3924. sel.value = nativeIds[0];
  3925. }
  3926. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3927. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3928. if (isCurrentCustom || sel.value === '__custom__') {
  3929. if (customWrap) customWrap.classList.remove('hidden');
  3930. if (customInput) customInput.value = cur;
  3931. } else {
  3932. if (customWrap) customWrap.classList.add('hidden');
  3933. if (customInput) customInput.value = '';
  3934. }
  3935. const chainInput = document.getElementById(`${table}-modal-chain`);
  3936. if (chainInput) chainInput.value = cur || sel.value;
  3937. }
  3938. function syncFilterChainFromSelect() {
  3939. const sel = document.getElementById('filter-modal-chain-select');
  3940. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3941. const customInput = document.getElementById('filter-modal-custom-input');
  3942. const chainInput = document.getElementById('filter-modal-chain');
  3943. if (!sel || !chainInput) return;
  3944. if (sel.value === '__custom__') {
  3945. if (customWrap) customWrap.classList.remove('hidden');
  3946. if (customInput) {
  3947. customInput.value = '';
  3948. customInput.focus();
  3949. }
  3950. chainInput.value = '';
  3951. } else {
  3952. if (customWrap) customWrap.classList.add('hidden');
  3953. chainInput.value = sel.value;
  3954. }
  3955. handleFilterChainChange();
  3956. }
  3957. function syncFilterCustomChainInput() {
  3958. const customInput = document.getElementById('filter-modal-custom-input');
  3959. const chainInput = document.getElementById('filter-modal-chain');
  3960. if (customInput && chainInput) {
  3961. chainInput.value = customInput.value.trim();
  3962. }
  3963. handleFilterChainChange();
  3964. }
  3965. function handleFilterChainChange() {
  3966. const chainInput = document.getElementById('filter-modal-chain');
  3967. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  3968. const sel = document.getElementById('filter-modal-chain-select');
  3969. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  3970. if (['forward', 'input', 'output'].includes(chain)) {
  3971. sel.value = chain;
  3972. }
  3973. }
  3974. const hintEl = document.getElementById('filter-chain-hint');
  3975. if (hintEl) {
  3976. if (chain === 'forward') {
  3977. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  3978. } else if (chain === 'input') {
  3979. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  3980. } else if (chain === 'output') {
  3981. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  3982. } else {
  3983. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  3984. }
  3985. }
  3986. const rowIn = document.getElementById('fw-row-iniface');
  3987. const rowInList = document.getElementById('fw-row-inifacelist');
  3988. const rowOut = document.getElementById('fw-row-outiface');
  3989. const rowOutList = document.getElementById('fw-row-outifacelist');
  3990. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  3991. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  3992. const rowSrcMac = document.getElementById('fw-row-srcmac');
  3993. if (chain === 'input') {
  3994. if (rowIn) rowIn.classList.remove('hidden');
  3995. if (rowInList) rowInList.classList.remove('hidden');
  3996. if (rowOut) rowOut.classList.add('hidden');
  3997. if (rowOutList) rowOutList.classList.add('hidden');
  3998. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3999. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4000. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4001. } else if (chain === 'output') {
  4002. if (rowIn) rowIn.classList.add('hidden');
  4003. if (rowInList) rowInList.classList.add('hidden');
  4004. if (rowOut) rowOut.classList.remove('hidden');
  4005. if (rowOutList) rowOutList.classList.remove('hidden');
  4006. if (rowInBridge) rowInBridge.classList.add('hidden');
  4007. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4008. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4009. } else {
  4010. if (rowIn) rowIn.classList.remove('hidden');
  4011. if (rowInList) rowInList.classList.remove('hidden');
  4012. if (rowOut) rowOut.classList.remove('hidden');
  4013. if (rowOutList) rowOutList.classList.remove('hidden');
  4014. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4015. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4016. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4017. }
  4018. checkFilterActionChainCompatibility();
  4019. }
  4020. function checkFilterActionChainCompatibility() {
  4021. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  4022. const warnBox = document.getElementById('filter-action-incompatible-warn');
  4023. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  4024. if (!warnBox || !warnMsg) return;
  4025. if (chain === 'prerouting' || chain === 'postrouting') {
  4026. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  4027. warnBox.classList.remove('hidden');
  4028. } else {
  4029. warnBox.classList.add('hidden');
  4030. }
  4031. }
  4032. function openAddFilterModal() {
  4033. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  4034. switchFwRuleTab('general');
  4035. setFirewallDays('fw', '');
  4036. const badge = document.getElementById('fw-modal-badge');
  4037. if (badge) badge.innerText = 'New...';
  4038. document.getElementById('filter-modal-id').value = '';
  4039. document.getElementById('filter-modal-family').value = '4';
  4040. document.getElementById('filter-modal-enabled').checked = true;
  4041. document.getElementById('filter-modal-comment').value = '';
  4042. document.getElementById('filter-modal-chain').value = 'forward';
  4043. populateChainDropdown('filter', 'forward');
  4044. handleFilterChainChange();
  4045. document.getElementById('filter-modal-action').value = 'accept';
  4046. document.getElementById('filter-modal-log').checked = false;
  4047. populateInterfaceSelect('fw-val-iniface');
  4048. populateInterfaceSelect('fw-val-outiface');
  4049. populateAddressListSelect('fw-val-srclist');
  4050. populateAddressListSelect('fw-val-dstlist');
  4051. populateGeoIPSelect('fw-val-srcgeo');
  4052. populateGeoIPSelect('fw-val-dstgeo');
  4053. const allFieldKeys = [
  4054. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4055. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4056. 'routingmark', 'conntype', 'cs', 'natstate',
  4057. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4058. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4059. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4060. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4061. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4062. ];
  4063. allFieldKeys.forEach(k => toggleFwField(k, false));
  4064. resetRuleCounterDisplay();
  4065. toggleFilterActionFields();
  4066. refreshFirewallRejectTypes();
  4067. document.getElementById('filter-modal').classList.remove('hidden');
  4068. }
  4069. function openEditFilterModal(id) {
  4070. id = decodeURIComponent(id);
  4071. const r = (state.filterRules || []).find(rule => rule.id === id);
  4072. if (!r) return;
  4073. switchFwRuleTab('general');
  4074. const badge = document.getElementById('fw-modal-badge');
  4075. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4076. document.getElementById('filter-modal-id').value = r.id;
  4077. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4078. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4079. document.getElementById('filter-modal-comment').value = r.comment || '';
  4080. const filterChain = r.chain || 'forward';
  4081. document.getElementById('filter-modal-chain').value = filterChain;
  4082. populateChainDropdown('filter', filterChain);
  4083. handleFilterChainChange();
  4084. setFirewallActionSelection('filter', r.action || 'accept');
  4085. document.getElementById('filter-modal-log').checked = !!r.log;
  4086. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4087. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4088. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4089. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4090. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4091. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4092. setFwFieldVal('src', r.src_address, true);
  4093. setFwFieldVal('dst', r.dst_address, true);
  4094. setFwFieldVal('srclist', r.src_address_list, true);
  4095. setFwFieldVal('dstlist', r.dst_address_list, true);
  4096. setFwFieldVal('srcgeo', r.src_geoip, true);
  4097. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4098. if (r.protocol && r.protocol !== 'all') {
  4099. setFwFieldVal('proto', r.protocol, true);
  4100. } else {
  4101. toggleFwField('proto', false);
  4102. }
  4103. setFwFieldVal('sport', r.src_port, true);
  4104. setFwFieldVal('dport', r.dst_port, true);
  4105. setFwFieldVal('anyport', r.any_port, true);
  4106. setFwFieldVal('iniface', r.in_interface, true);
  4107. setFwFieldVal('outiface', r.out_interface, true);
  4108. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4109. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4110. setFwFieldVal('pktmark', r.packet_mark, true);
  4111. setFwFieldVal('connmark', r.connection_mark, true);
  4112. setFwFieldVal('routingmark', r.routing_mark, true);
  4113. setFwFieldVal('conntype', r.connection_type, false);
  4114. const states = r.connection_state || [];
  4115. if (states.length > 0) {
  4116. toggleFwField('cs', true);
  4117. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4118. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4119. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4120. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4121. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4122. } else {
  4123. toggleFwField('cs', false);
  4124. }
  4125. const natStates = r.connection_nat_state || [];
  4126. if (natStates.length > 0) {
  4127. toggleFwField('natstate', true);
  4128. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4129. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4130. } else {
  4131. toggleFwField('natstate', false);
  4132. }
  4133. // Advanced tab fields
  4134. setFwFieldVal('layer7', r.layer7_protocol, false);
  4135. setFwFieldVal('content', r.content, false);
  4136. setFwFieldVal('connbytes', r.connection_bytes, false);
  4137. setFwFieldVal('connrate', r.connection_rate, false);
  4138. setFwFieldVal('pcc', r.pcc, false);
  4139. setFwFieldVal('srcmac', r.src_mac_address, true);
  4140. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4141. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4142. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4143. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4144. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4145. setFwFieldVal('tlshost', r.tls_host, false);
  4146. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4147. setFwFieldVal('priority', r.priority, false);
  4148. setFwFieldVal('dscp', r.dscp, false);
  4149. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4150. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4151. setFwFieldVal('pktsize', r.packet_size, false);
  4152. setFwFieldVal('random', r.random, false);
  4153. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4154. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4155. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4156. setFwFieldVal('ttl', r.ttl, false);
  4157. // Extra tab fields
  4158. setFwFieldVal('time', r.time, false);
  4159. if (r.days) {
  4160. toggleFwField('days', true);
  4161. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4162. const chk = document.getElementById(`fw-day-${d}`);
  4163. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4164. });
  4165. } else {
  4166. toggleFwField('days', false);
  4167. }
  4168. setFwFieldVal('limit', r.limit, false);
  4169. setFwFieldVal('dstlimit', r.dst_limit, false);
  4170. setFwFieldVal('psd', r.psd, false);
  4171. // Action fields
  4172. if (r.reject_with) {
  4173. const rwEl = document.getElementById('filter-modal-rejectwith');
  4174. if (rwEl) rwEl.value = r.reject_with;
  4175. }
  4176. if (r.jump_target) {
  4177. const jtEl = document.getElementById('filter-modal-jumptarget');
  4178. if (jtEl) jtEl.value = r.jump_target;
  4179. }
  4180. if (r.address_list) {
  4181. const alEl = document.getElementById('filter-modal-action-addrlist');
  4182. if (alEl) alEl.value = r.address_list;
  4183. }
  4184. if (r.address_list_timeout) {
  4185. const toEl = document.getElementById('filter-modal-action-timeout');
  4186. if (toEl) toEl.value = r.address_list_timeout;
  4187. }
  4188. setFwFieldVal('logprefix', r.log_prefix, false);
  4189. // Statistics
  4190. const bEl = document.getElementById('fw-stat-bytes');
  4191. const pEl = document.getElementById('fw-stat-packets');
  4192. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4193. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4194. state.fwLastBytes = r.bytes || 0;
  4195. state.fwLastPackets = r.packets || 0;
  4196. state.fwLastTimestamp = Date.now();
  4197. state.fwStatRateHistory = new Array(30).fill(0);
  4198. state.fwStatPktHistory = new Array(30).fill(0);
  4199. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4200. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4201. toggleFilterActionFields();
  4202. refreshFirewallRejectTypes();
  4203. document.getElementById('filter-modal').classList.remove('hidden');
  4204. }
  4205. function closeFilterModal() {
  4206. stopFwStatPolling();
  4207. document.getElementById('filter-modal').classList.add('hidden');
  4208. }
  4209. function toggleFilterActionFields() {
  4210. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4211. const rejectBox = document.getElementById('filter-action-reject-box');
  4212. const jumpBox = document.getElementById('filter-action-jump-box');
  4213. const addrBox = document.getElementById('filter-action-addrlist-box');
  4214. if (rejectBox) {
  4215. if (act === 'reject') rejectBox.classList.remove('hidden');
  4216. else rejectBox.classList.add('hidden');
  4217. }
  4218. if (jumpBox) {
  4219. if (act === 'jump') jumpBox.classList.remove('hidden');
  4220. else jumpBox.classList.add('hidden');
  4221. }
  4222. if (addrBox) {
  4223. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4224. addrBox.classList.remove('hidden');
  4225. } else {
  4226. addrBox.classList.add('hidden');
  4227. }
  4228. }
  4229. if (act === 'log') {
  4230. const logEl = document.getElementById('filter-modal-log');
  4231. if (logEl) logEl.checked = true;
  4232. toggleFwField('logprefix', true);
  4233. }
  4234. }
  4235. function toggleFwLogPrefix() {
  4236. const isLog = document.getElementById('filter-modal-log')?.checked;
  4237. toggleFwField('logprefix', !!isLog);
  4238. }
  4239. function copyFilterRule() {
  4240. document.getElementById('filter-modal-id').value = '';
  4241. const badge = document.getElementById('fw-modal-badge');
  4242. if (badge) badge.innerText = 'New...';
  4243. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4244. }
  4245. function resetRuleCounterDisplay() {
  4246. state.fwStatRateHistory = new Array(30).fill(0);
  4247. state.fwStatPktHistory = new Array(30).fill(0);
  4248. state.fwLastBytes = 0;
  4249. state.fwLastPackets = 0;
  4250. state.fwLastTimestamp = Date.now();
  4251. const bEl = document.getElementById('fw-stat-bytes');
  4252. const pEl = document.getElementById('fw-stat-packets');
  4253. const rEl = document.getElementById('fw-stat-rate');
  4254. const prEl = document.getElementById('fw-stat-pktrate');
  4255. if (bEl) bEl.value = '0 B';
  4256. if (pEl) pEl.value = '0';
  4257. if (rEl) rEl.value = '0 bps';
  4258. if (prEl) prEl.value = '0 p/s';
  4259. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4260. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4261. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4262. }
  4263. async function resetAllFwCounters() {
  4264. try {
  4265. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4266. if (res.ok) {
  4267. resetRuleCounterDisplay();
  4268. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4269. loadFirewall(false);
  4270. }
  4271. } catch (err) {
  4272. showToast('Error', err.message, 'error');
  4273. }
  4274. }
  4275. async function applyFilterRule(closeAfter = false) {
  4276. const id = document.getElementById('filter-modal-id').value;
  4277. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4278. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4279. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4280. const chainLower = chain.toLowerCase();
  4281. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4282. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4283. switchFwRuleTab('general');
  4284. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4285. return;
  4286. }
  4287. const action = document.getElementById('filter-modal-action').value;
  4288. const comment = document.getElementById('filter-modal-comment').value.trim();
  4289. const enabled = document.getElementById('filter-modal-enabled').checked;
  4290. const src = getFwFieldVal('src', true);
  4291. const dst = getFwFieldVal('dst', true);
  4292. const srclist = getFwFieldVal('srclist', true);
  4293. const dstlist = getFwFieldVal('dstlist', true);
  4294. const srcgeo = getFwFieldVal('srcgeo', true);
  4295. const dstgeo = getFwFieldVal('dstgeo', true);
  4296. const proto = getFwFieldVal('proto', true);
  4297. const sport = getFwFieldVal('sport', true);
  4298. const dport = getFwFieldVal('dport', true);
  4299. const anyport = getFwFieldVal('anyport', true);
  4300. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4301. switchFwRuleTab('general'); toggleFwField('proto', true);
  4302. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4303. }
  4304. let iniface = getFwFieldVal('iniface', true);
  4305. let outiface = getFwFieldVal('outiface', true);
  4306. let inifacelist = getFwFieldVal('inifacelist', true);
  4307. let outifacelist = getFwFieldVal('outifacelist', true);
  4308. if (chainLower === 'input') {
  4309. outiface = '';
  4310. outifacelist = '';
  4311. } else if (chainLower === 'output') {
  4312. iniface = '';
  4313. inifacelist = '';
  4314. }
  4315. const pktmark = getFwFieldVal('pktmark', true);
  4316. const connmark = getFwFieldVal('connmark', true);
  4317. const routingmark = getFwFieldVal('routingmark', true);
  4318. const conntype = getFwFieldVal('conntype', false);
  4319. const states = [];
  4320. const csBox = document.getElementById('fw-field-cs');
  4321. if (csBox && !csBox.classList.contains('hidden')) {
  4322. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4323. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4324. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4325. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4326. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4327. }
  4328. const natStates = [];
  4329. const natBox = document.getElementById('fw-field-natstate');
  4330. if (natBox && !natBox.classList.contains('hidden')) {
  4331. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4332. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4333. }
  4334. const payload = {
  4335. ip_version: Number(document.getElementById('filter-modal-family').value),
  4336. id,
  4337. chain,
  4338. action,
  4339. protocol: proto || 'all',
  4340. src_address: src,
  4341. dst_address: dst,
  4342. src_port: sport,
  4343. dst_port: dport,
  4344. any_port: anyport,
  4345. in_interface: iniface,
  4346. out_interface: outiface,
  4347. in_interface_list: inifacelist,
  4348. out_interface_list: outifacelist,
  4349. packet_mark: pktmark,
  4350. connection_mark: connmark,
  4351. routing_mark: routingmark,
  4352. connection_type: conntype,
  4353. connection_state: states,
  4354. connection_nat_state: natStates,
  4355. src_address_list: srclist,
  4356. dst_address_list: dstlist,
  4357. src_geoip: srcgeo,
  4358. dst_geoip: dstgeo,
  4359. comment,
  4360. disabled: !enabled,
  4361. // Advanced tab
  4362. content: getFwFieldVal('content', false),
  4363. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4364. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4365. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4366. ipsec_policy: getFwFieldVal('ipsec', false),
  4367. dscp: getFwFieldVal('dscp', false),
  4368. tcp_mss: getFwFieldVal('tcpmss', false),
  4369. tos: document.getElementById('fw-val-tos')?.value || '',
  4370. packet_size: getFwFieldVal('pktsize', false),
  4371. random: getFwFieldVal('random', false),
  4372. tcp_flags: getFwFieldVal('tcpflags', false),
  4373. icmp_options: getFwFieldVal('icmpoptions', false),
  4374. ttl: getFwFieldVal('ttl', false),
  4375. days: selectedDays,
  4376. // Extra tab
  4377. time: getFwFieldVal('time', false),
  4378. limit: getFwFieldVal('limit', false),
  4379. // Action tab
  4380. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4381. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4382. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4383. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4384. log: document.getElementById('filter-modal-log')?.checked || false,
  4385. log_prefix: getFwFieldVal('logprefix', false)
  4386. };
  4387. try {
  4388. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4389. method: 'POST',
  4390. headers: { 'Content-Type': 'application/json' },
  4391. body: JSON.stringify(payload)
  4392. });
  4393. if (res.ok) {
  4394. const data = await res.json();
  4395. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4396. loadFirewall(false);
  4397. if (closeAfter) {
  4398. closeFilterModal();
  4399. } else {
  4400. if (data.id) {
  4401. document.getElementById('filter-modal-id').value = data.id;
  4402. const badge = document.getElementById('fw-modal-badge');
  4403. if (badge) badge.innerText = `#${data.id}`;
  4404. }
  4405. }
  4406. } else {
  4407. const err = await res.json();
  4408. showToast('Error', err.message || 'Failed to save rule', 'error');
  4409. }
  4410. } catch (err) {
  4411. showToast('Error', err.message, 'error');
  4412. }
  4413. }
  4414. function submitSaveFilterRule(e) {
  4415. if (e && e.preventDefault) e.preventDefault();
  4416. return applyFilterRule(true);
  4417. }
  4418. function startFwStatPolling() {
  4419. stopFwStatPolling();
  4420. pollRuleStats();
  4421. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4422. }
  4423. function stopFwStatPolling() {
  4424. if (state.fwStatInterval) {
  4425. clearInterval(state.fwStatInterval);
  4426. state.fwStatInterval = null;
  4427. }
  4428. }
  4429. async function pollRuleStats() {
  4430. const id = document.getElementById('filter-modal-id')?.value;
  4431. if (!id) {
  4432. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4433. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4434. return;
  4435. }
  4436. try {
  4437. const res = await fetch(`${API_BASE}/firewall/filter`);
  4438. if (!res.ok) return;
  4439. const rules = await res.json();
  4440. const r = rules.find(x => x.id === id);
  4441. if (!r) return;
  4442. const now = Date.now();
  4443. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4444. state.fwLastTimestamp = now;
  4445. const curBytes = r.bytes || 0;
  4446. const curPackets = r.packets || 0;
  4447. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4448. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4449. state.fwLastBytes = curBytes;
  4450. state.fwLastPackets = curPackets;
  4451. const rateBps = Math.round((deltaBytes * 8) / dt);
  4452. const ratePkt = Math.round(deltaPkts / dt);
  4453. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4454. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4455. state.fwStatRateHistory.push(rateBps);
  4456. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4457. state.fwStatPktHistory.push(ratePkt);
  4458. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4459. const bEl = document.getElementById('fw-stat-bytes');
  4460. const pEl = document.getElementById('fw-stat-packets');
  4461. const rEl = document.getElementById('fw-stat-rate');
  4462. const prEl = document.getElementById('fw-stat-pktrate');
  4463. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4464. if (pEl) pEl.value = curPackets.toLocaleString();
  4465. if (rEl) rEl.value = formatBps(rateBps);
  4466. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4467. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4468. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4469. } catch (e) {
  4470. console.error('Error polling rule stats', e);
  4471. }
  4472. }
  4473. function formatBps(bps) {
  4474. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4475. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4476. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4477. return bps + ' bps';
  4478. }
  4479. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4480. const svg = document.getElementById(svgId);
  4481. if (!svg) return;
  4482. const w = 500;
  4483. const h = 100;
  4484. const paddingRight = 45;
  4485. const graphWidth = w - paddingRight;
  4486. const maxVal = Math.max(5, ...dataArray);
  4487. const currentVal = dataArray[dataArray.length - 1] || 0;
  4488. const leg = document.getElementById(legendId);
  4489. if (leg) {
  4490. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4491. }
  4492. let gridLines = '';
  4493. for (let i = 0; i <= 5; i++) {
  4494. const y = 8 + (i * (h - 18) / 5);
  4495. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4496. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4497. gridLines += `
  4498. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4499. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4500. `;
  4501. }
  4502. const step = graphWidth / (dataArray.length - 1);
  4503. const points = dataArray.map((val, idx) => {
  4504. const x = idx * step;
  4505. const y = (h - 10) - (val / maxVal) * (h - 20);
  4506. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4507. });
  4508. const polylineStr = points.join(' ');
  4509. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4510. svg.innerHTML = `
  4511. ${gridLines}
  4512. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4513. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4514. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4515. `;
  4516. }
  4517. async function moveFilterRule(id, dir) {
  4518. id = decodeURIComponent(id);
  4519. try {
  4520. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4521. method: 'POST',
  4522. headers: { 'Content-Type': 'application/json' },
  4523. body: JSON.stringify({ direction: dir })
  4524. });
  4525. if (!res.ok) throw new Error(await responseError(res));
  4526. await loadFirewall(false);
  4527. } catch (err) {
  4528. showToast('Error', err.message, 'error');
  4529. }
  4530. }
  4531. async function toggleFilterRuleState(id, disabled) {
  4532. id = decodeURIComponent(id);
  4533. try {
  4534. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4535. method: 'POST',
  4536. headers: { 'Content-Type': 'application/json' },
  4537. body: JSON.stringify({ disabled })
  4538. });
  4539. if (!res.ok) throw new Error(await responseError(res));
  4540. await loadFirewall(false);
  4541. } catch (err) {
  4542. showToast('Error', err.message, 'error');
  4543. }
  4544. }
  4545. async function deleteFilterRule(id) {
  4546. id = decodeURIComponent(id);
  4547. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4548. try {
  4549. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4550. if (!res.ok) throw new Error(await responseError(res));
  4551. {
  4552. showToast('Deleted', 'Filter rule removed', 'success');
  4553. loadFirewall(false);
  4554. }
  4555. } catch (err) {
  4556. showToast('Error', err.message, 'error');
  4557. }
  4558. }
  4559. // ----------------- NAT Rules -----------------
  4560. function renderNATRules() {
  4561. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4562. const tbody = document.getElementById('nat-table-body');
  4563. const empty = document.getElementById('nat-empty');
  4564. if (!tbody) return;
  4565. tbody.innerHTML = '';
  4566. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4567. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4568. if (rules.length === 0) {
  4569. empty?.classList.remove('hidden');
  4570. return;
  4571. }
  4572. empty?.classList.add('hidden');
  4573. rules.forEach((raw, idx) => {
  4574. const r = safeFirewallRow(raw);
  4575. const tr = document.createElement('tr');
  4576. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4577. let toTarget = '-';
  4578. if (r.action === 'jump') {
  4579. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4580. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4581. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4582. } else if (r.action === 'redirect') {
  4583. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4584. } else if (r.action === 'masquerade') {
  4585. 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>`;
  4586. } else if (r.action === 'log') {
  4587. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4588. } else {
  4589. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4590. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4591. }
  4592. 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(' ');
  4593. tr.innerHTML = `
  4594. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4595. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4596. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4597. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4598. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4599. <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>
  4600. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4601. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4602. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4603. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4604. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4605. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4606. </td>
  4607. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4608. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4609. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4610. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4611. <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>
  4612. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4613. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4614. </td>
  4615. `;
  4616. tbody.appendChild(tr);
  4617. });
  4618. }
  4619. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4620. function switchNATRuleTab(tab) {
  4621. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4622. state.activeNATRuleTab = tab;
  4623. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4624. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4625. btn.classList.add('text-slate-400', 'border-transparent');
  4626. });
  4627. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4628. if (activeBtn) {
  4629. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4630. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4631. }
  4632. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4633. const activePane = document.getElementById(`nat-pane-${tab}`);
  4634. if (activePane) activePane.classList.remove('hidden');
  4635. if (tab === 'statistics') {
  4636. startNATStatPolling();
  4637. } else {
  4638. stopNATStatPolling();
  4639. }
  4640. }
  4641. function toggleNATField(fieldKey, expand) {
  4642. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4643. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4644. if (!plusBtn || !fieldBox) return;
  4645. if (expand) {
  4646. plusBtn.classList.add('hidden');
  4647. fieldBox.classList.remove('hidden');
  4648. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4649. if (valInput) valInput.focus();
  4650. } else {
  4651. fieldBox.classList.add('hidden');
  4652. plusBtn.classList.remove('hidden');
  4653. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4654. if (valInput) {
  4655. if (valInput.tagName === 'SELECT') {
  4656. valInput.selectedIndex = 0;
  4657. } else {
  4658. valInput.value = '';
  4659. }
  4660. }
  4661. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4662. if (invInput) invInput.checked = false;
  4663. if (fieldKey === 'days') {
  4664. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4665. const el = document.getElementById(`nat-day-${d}`);
  4666. if (el) el.checked = true;
  4667. });
  4668. }
  4669. }
  4670. }
  4671. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4672. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4673. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4674. toggleNATField(fieldKey, true);
  4675. let strVal = String(value);
  4676. if (hasInvert) {
  4677. const inv = strVal.startsWith('!');
  4678. if (inv) strVal = strVal.slice(1);
  4679. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4680. if (invEl) invEl.checked = inv;
  4681. else if (inv) strVal = '!'+strVal;
  4682. }
  4683. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4684. 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; }
  4685. } else {
  4686. toggleNATField(fieldKey, false);
  4687. }
  4688. }
  4689. function getNATFieldVal(fieldKey, hasInvert = false) {
  4690. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4691. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4692. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4693. let v = valEl ? valEl.value.trim() : '';
  4694. if (!v) return '';
  4695. if (hasInvert) {
  4696. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4697. if (invEl && invEl.checked) {
  4698. v = '!' + v.replace(/^!/, '');
  4699. }
  4700. }
  4701. return v;
  4702. }
  4703. function toggleMaximizeNATModal() {
  4704. const win = document.getElementById('nat-modal-window');
  4705. if (!win) return;
  4706. if (win.classList.contains('max-w-[720px]')) {
  4707. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4708. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4709. } else {
  4710. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4711. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4712. }
  4713. }
  4714. function syncNATChainFromSelect() {
  4715. const sel = document.getElementById('nat-modal-chain-select');
  4716. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4717. const customInput = document.getElementById('nat-modal-custom-input');
  4718. const chainInput = document.getElementById('nat-modal-chain');
  4719. if (!sel || !chainInput) return;
  4720. if (sel.value === '__custom__') {
  4721. if (customWrap) customWrap.classList.remove('hidden');
  4722. if (customInput) {
  4723. customInput.value = '';
  4724. customInput.focus();
  4725. }
  4726. chainInput.value = '';
  4727. } else {
  4728. if (customWrap) customWrap.classList.add('hidden');
  4729. chainInput.value = sel.value;
  4730. const actEl = document.getElementById('nat-modal-action');
  4731. if (actEl) {
  4732. const curAct = actEl.value;
  4733. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4734. actEl.value = 'dst-nat';
  4735. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4736. actEl.value = 'masquerade';
  4737. }
  4738. }
  4739. }
  4740. handleNATChainChange();
  4741. }
  4742. function syncNATCustomChainInput() {
  4743. const customInput = document.getElementById('nat-modal-custom-input');
  4744. const chainInput = document.getElementById('nat-modal-chain');
  4745. if (customInput && chainInput) {
  4746. chainInput.value = customInput.value.trim();
  4747. }
  4748. handleNATChainChange();
  4749. }
  4750. function handleNATChainChange() {
  4751. const chainInput = document.getElementById('nat-modal-chain');
  4752. const rawChain = (chainInput?.value || 'postrouting').trim();
  4753. const chain = nativeNATChain(rawChain).toLowerCase();
  4754. const sel = document.getElementById('nat-modal-chain-select');
  4755. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4756. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4757. sel.value = chain;
  4758. }
  4759. }
  4760. const hintEl = document.getElementById('nat-chain-hint');
  4761. if (hintEl) {
  4762. if (chain === 'prerouting') {
  4763. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4764. } else if (chain === 'postrouting') {
  4765. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4766. } else if (chain === 'output') {
  4767. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4768. } else if (chain === 'input') {
  4769. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4770. } else {
  4771. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4772. }
  4773. }
  4774. const rowIn = document.getElementById('nat-row-iniface');
  4775. const rowInList = document.getElementById('nat-row-inifacelist');
  4776. const rowOut = document.getElementById('nat-row-outiface');
  4777. const rowOutList = document.getElementById('nat-row-outifacelist');
  4778. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4779. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4780. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4781. if (chain === 'prerouting' || chain === 'input') {
  4782. if (rowIn) rowIn.classList.remove('hidden');
  4783. if (rowInList) rowInList.classList.remove('hidden');
  4784. if (rowOut) rowOut.classList.add('hidden');
  4785. if (rowOutList) rowOutList.classList.add('hidden');
  4786. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4787. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4788. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4789. } else if (chain === 'postrouting' || chain === 'output') {
  4790. if (rowIn) rowIn.classList.add('hidden');
  4791. if (rowInList) rowInList.classList.add('hidden');
  4792. if (rowOut) rowOut.classList.remove('hidden');
  4793. if (rowOutList) rowOutList.classList.remove('hidden');
  4794. if (rowInBridge) rowInBridge.classList.add('hidden');
  4795. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4796. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4797. } else {
  4798. if (rowIn) rowIn.classList.remove('hidden');
  4799. if (rowInList) rowInList.classList.remove('hidden');
  4800. if (rowOut) rowOut.classList.remove('hidden');
  4801. if (rowOutList) rowOutList.classList.remove('hidden');
  4802. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4803. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4804. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4805. }
  4806. checkNATActionChainCompatibility();
  4807. toggleNATActionFields();
  4808. }
  4809. function checkNATActionChainCompatibility() {
  4810. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4811. const chain = nativeNATChain(rawChain).toLowerCase();
  4812. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4813. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4814. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4815. if (!warnBox || !warnMsg) return;
  4816. let msg = '';
  4817. if (['dst-nat', 'redirect'].includes(action)) {
  4818. if (chain !== 'prerouting' && chain !== 'output') {
  4819. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4820. }
  4821. } else if (action === 'masquerade') {
  4822. if (chain !== 'postrouting') {
  4823. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4824. }
  4825. } else if (action === 'src-nat') {
  4826. if (chain !== 'postrouting' && chain !== 'input') {
  4827. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4828. }
  4829. }
  4830. if (msg) {
  4831. warnMsg.textContent = msg;
  4832. warnBox.classList.remove('hidden');
  4833. } else {
  4834. warnBox.classList.add('hidden');
  4835. }
  4836. }
  4837. function toggleNATActionFields() {
  4838. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4839. const rowAddr = document.getElementById('nat-row-toaddr');
  4840. const rowPort = document.getElementById('nat-row-toport');
  4841. const jumpBox = document.getElementById('nat-action-jump-box');
  4842. const addrBox = document.getElementById('nat-action-addrlist-box');
  4843. // Hide all dynamic rows first
  4844. if (rowAddr) rowAddr.classList.add('hidden');
  4845. if (rowPort) rowPort.classList.add('hidden');
  4846. if (jumpBox) jumpBox.classList.add('hidden');
  4847. if (addrBox) addrBox.classList.add('hidden');
  4848. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4849. if (rowAddr) rowAddr.classList.remove('hidden');
  4850. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4851. } else if (act === 'redirect' || act === 'masquerade') {
  4852. if (rowPort) rowPort.classList.remove('hidden');
  4853. } else if (act === 'jump') {
  4854. if (jumpBox) jumpBox.classList.remove('hidden');
  4855. } else if (act.includes('address-list') || act.includes('address list')) {
  4856. if (addrBox) addrBox.classList.remove('hidden');
  4857. }
  4858. if (act === 'log') {
  4859. const logEl = document.getElementById('nat-modal-log');
  4860. if (logEl) logEl.checked = true;
  4861. toggleNATField('logprefix', true);
  4862. }
  4863. }
  4864. function handleNATActionChange() {
  4865. toggleNATActionFields();
  4866. checkNATActionChainCompatibility();
  4867. }
  4868. function toggleNATLogPrefix() {
  4869. const isLog = document.getElementById('nat-modal-log')?.checked;
  4870. toggleNATField('logprefix', !!isLog);
  4871. }
  4872. function openAddNATModal() {
  4873. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4874. switchNATRuleTab('general');
  4875. setFirewallDays('nat', '');
  4876. const badge = document.getElementById('nat-modal-badge');
  4877. if (badge) badge.innerText = 'New...';
  4878. document.getElementById('nat-modal-id').value = '';
  4879. document.getElementById('nat-modal-family').value = '4';
  4880. document.getElementById('nat-modal-enabled').checked = true;
  4881. document.getElementById('nat-modal-comment').value = '';
  4882. document.getElementById('nat-modal-chain').value = 'postrouting';
  4883. populateChainDropdown('nat', 'postrouting');
  4884. handleNATChainChange();
  4885. document.getElementById('nat-modal-action').value = 'masquerade';
  4886. document.getElementById('nat-modal-toaddr').value = '';
  4887. document.getElementById('nat-modal-toport').value = '';
  4888. document.getElementById('nat-modal-log').checked = false;
  4889. populateInterfaceSelect('nat-val-iniface');
  4890. populateInterfaceSelect('nat-val-outiface');
  4891. populateAddressListSelect('nat-val-srclist');
  4892. populateAddressListSelect('nat-val-dstlist');
  4893. populateGeoIPSelect('nat-val-srcgeo');
  4894. populateGeoIPSelect('nat-val-dstgeo');
  4895. const allFieldKeys = [
  4896. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4897. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4898. 'routingmark', 'conntype',
  4899. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4900. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4901. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4902. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4903. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4904. ];
  4905. allFieldKeys.forEach(k => toggleNATField(k, false));
  4906. resetNATCounterDisplay();
  4907. toggleNATActionFields();
  4908. document.getElementById('nat-modal').classList.remove('hidden');
  4909. }
  4910. function openEditNATModal(id) {
  4911. id = decodeURIComponent(id);
  4912. const r = (state.natRules || []).find(rule => rule.id === id);
  4913. if (!r) return;
  4914. setFirewallDays('nat', r.days || '');
  4915. switchNATRuleTab('general');
  4916. const badge = document.getElementById('nat-modal-badge');
  4917. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4918. document.getElementById('nat-modal-id').value = r.id;
  4919. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4920. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4921. document.getElementById('nat-modal-comment').value = r.comment || '';
  4922. const natChain = nativeNATChain(r.chain || 'postrouting');
  4923. document.getElementById('nat-modal-chain').value = natChain;
  4924. populateChainDropdown('nat', natChain);
  4925. handleNATChainChange();
  4926. setFirewallActionSelection('nat', r.action || 'accept');
  4927. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4928. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4929. document.getElementById('nat-modal-log').checked = !!r.log;
  4930. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4931. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4932. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4933. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4934. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4935. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4936. setNATFieldVal('src', r.src_address, true);
  4937. setNATFieldVal('dst', r.dst_address, true);
  4938. setNATFieldVal('srclist', r.src_address_list, true);
  4939. setNATFieldVal('dstlist', r.dst_address_list, true);
  4940. setNATFieldVal('srcgeo', r.src_geoip, true);
  4941. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4942. if (r.protocol && r.protocol !== 'all') {
  4943. setNATFieldVal('proto', r.protocol, true);
  4944. } else {
  4945. toggleNATField('proto', false);
  4946. }
  4947. setNATFieldVal('sport', r.src_port, true);
  4948. setNATFieldVal('dport', r.dst_port, true);
  4949. setNATFieldVal('anyport', r.any_port, true);
  4950. setNATFieldVal('iniface', r.in_interface, true);
  4951. setNATFieldVal('outiface', r.out_interface, true);
  4952. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4953. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4954. setNATFieldVal('pktmark', r.packet_mark, true);
  4955. setNATFieldVal('connmark', r.connection_mark, true);
  4956. setNATFieldVal('routingmark', r.routing_mark, true);
  4957. setNATFieldVal('conntype', r.connection_type, false);
  4958. // Advanced tab fields
  4959. setNATFieldVal('layer7', r.layer7_protocol, false);
  4960. setNATFieldVal('content', r.content, false);
  4961. setNATFieldVal('connbytes', r.connection_bytes, false);
  4962. setNATFieldVal('connrate', r.connection_rate, false);
  4963. setNATFieldVal('pcc', r.pcc, false);
  4964. setNATFieldVal('srcmac', r.src_mac_address, true);
  4965. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4966. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4967. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4968. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4969. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4970. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4971. setNATFieldVal('priority', r.priority, false);
  4972. setNATFieldVal('dscp', r.dscp, false);
  4973. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4974. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4975. setNATFieldVal('pktsize', r.packet_size, false);
  4976. setNATFieldVal('random', r.random, false);
  4977. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4978. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4979. setNATFieldVal('ttl', r.ttl, false);
  4980. // Extra tab fields
  4981. setNATFieldVal('time', r.time, false);
  4982. if (r.days) {
  4983. toggleNATField('days', true);
  4984. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4985. const chk = document.getElementById(`nat-day-${d}`);
  4986. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4987. });
  4988. } else {
  4989. toggleNATField('days', false);
  4990. }
  4991. setNATFieldVal('limit', r.limit, false);
  4992. setNATFieldVal('dstlimit', r.dst_limit, false);
  4993. setNATFieldVal('psd', r.psd, false);
  4994. // Action fields
  4995. if (r.jump_target) {
  4996. const jtEl = document.getElementById('nat-modal-jumptarget');
  4997. if (jtEl) jtEl.value = r.jump_target;
  4998. }
  4999. if (r.address_list) {
  5000. const alEl = document.getElementById('nat-modal-action-addrlist');
  5001. if (alEl) alEl.value = r.address_list;
  5002. }
  5003. if (r.address_list_timeout) {
  5004. const toEl = document.getElementById('nat-modal-action-timeout');
  5005. if (toEl) toEl.value = r.address_list_timeout;
  5006. }
  5007. setNATFieldVal('logprefix', r.log_prefix, false);
  5008. // Statistics
  5009. const bEl = document.getElementById('nat-stat-bytes');
  5010. const pEl = document.getElementById('nat-stat-packets');
  5011. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5012. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5013. state.natLastBytes = r.bytes || 0;
  5014. state.natLastPackets = r.packets || 0;
  5015. state.natLastTimestamp = Date.now();
  5016. state.natStatRateHistory = new Array(30).fill(0);
  5017. state.natStatPktHistory = new Array(30).fill(0);
  5018. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5019. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5020. toggleNATActionFields();
  5021. document.getElementById('nat-modal').classList.remove('hidden');
  5022. }
  5023. function closeNATModal() {
  5024. stopNATStatPolling();
  5025. document.getElementById('nat-modal').classList.add('hidden');
  5026. }
  5027. function copyNATRule() {
  5028. document.getElementById('nat-modal-id').value = '';
  5029. const badge = document.getElementById('nat-modal-badge');
  5030. if (badge) badge.innerText = 'New...';
  5031. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  5032. }
  5033. function resetNATCounterDisplay() {
  5034. state.natStatRateHistory = new Array(30).fill(0);
  5035. state.natStatPktHistory = new Array(30).fill(0);
  5036. state.natLastBytes = 0;
  5037. state.natLastPackets = 0;
  5038. state.natLastTimestamp = Date.now();
  5039. const bEl = document.getElementById('nat-stat-bytes');
  5040. const pEl = document.getElementById('nat-stat-packets');
  5041. const rEl = document.getElementById('nat-stat-rate');
  5042. const prEl = document.getElementById('nat-stat-pktrate');
  5043. if (bEl) bEl.value = '0 B';
  5044. if (pEl) pEl.value = '0';
  5045. if (rEl) rEl.value = '0 bps';
  5046. if (prEl) prEl.value = '0 p/s';
  5047. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5048. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5049. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5050. }
  5051. async function applyNATRule(closeAfter = false) {
  5052. const id = document.getElementById('nat-modal-id').value;
  5053. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5054. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5055. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5056. const chainLower = nativeNATChain(chain).toLowerCase();
  5057. const action = document.getElementById('nat-modal-action').value;
  5058. const comment = document.getElementById('nat-modal-comment').value.trim();
  5059. const enabled = document.getElementById('nat-modal-enabled').checked;
  5060. const src = getNATFieldVal('src', true);
  5061. const dst = getNATFieldVal('dst', true);
  5062. const srclist = getNATFieldVal('srclist', true);
  5063. const dstlist = getNATFieldVal('dstlist', true);
  5064. const srcgeo = getNATFieldVal('srcgeo', true);
  5065. const dstgeo = getNATFieldVal('dstgeo', true);
  5066. const proto = getNATFieldVal('proto', true);
  5067. const sport = getNATFieldVal('sport', true);
  5068. const dport = getNATFieldVal('dport', true);
  5069. const anyport = getNATFieldVal('anyport', true);
  5070. let iniface = getNATFieldVal('iniface', true);
  5071. let outiface = getNATFieldVal('outiface', true);
  5072. let inifacelist = getNATFieldVal('inifacelist', true);
  5073. let outifacelist = getNATFieldVal('outifacelist', true);
  5074. if (chainLower === 'prerouting' || chainLower === 'input') {
  5075. outiface = '';
  5076. outifacelist = '';
  5077. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5078. iniface = '';
  5079. inifacelist = '';
  5080. }
  5081. const pktmark = getNATFieldVal('pktmark', true);
  5082. const connmark = getNATFieldVal('connmark', true);
  5083. const routingmark = getNATFieldVal('routingmark', true);
  5084. const conntype = getNATFieldVal('conntype', false);
  5085. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5086. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5087. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5088. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5089. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5090. switchNATRuleTab('general');
  5091. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5092. return;
  5093. }
  5094. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5095. switchNATRuleTab('general');
  5096. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5097. return;
  5098. }
  5099. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5100. switchNATRuleTab('general');
  5101. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5102. return;
  5103. }
  5104. 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; }
  5105. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5106. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5107. 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;
  5108. }
  5109. const payload = {
  5110. ip_version: Number(document.getElementById('nat-modal-family').value),
  5111. id,
  5112. chain,
  5113. action,
  5114. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5115. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5116. protocol: proto || 'all',
  5117. src_address: src,
  5118. dst_address: dst,
  5119. src_port: sport,
  5120. dst_port: dport,
  5121. any_port: anyport,
  5122. in_interface: iniface,
  5123. out_interface: outiface,
  5124. in_interface_list: inifacelist,
  5125. out_interface_list: outifacelist,
  5126. packet_mark: pktmark,
  5127. connection_mark: connmark,
  5128. routing_mark: routingmark,
  5129. connection_type: conntype,
  5130. src_address_list: srclist,
  5131. dst_address_list: dstlist,
  5132. src_geoip: srcgeo,
  5133. dst_geoip: dstgeo,
  5134. comment,
  5135. disabled: !enabled,
  5136. // Advanced tab
  5137. content: getNATFieldVal('content', false),
  5138. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5139. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5140. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5141. ipsec_policy: getNATFieldVal('ipsec', false),
  5142. dscp: getNATFieldVal('dscp', false),
  5143. tcp_mss: getNATFieldVal('tcpmss', false),
  5144. tos: document.getElementById('nat-val-tos')?.value || '',
  5145. packet_size: getNATFieldVal('pktsize', false),
  5146. random: getNATFieldVal('random', false),
  5147. icmp_options: getNATFieldVal('icmpoptions', false),
  5148. ttl: getNATFieldVal('ttl', false),
  5149. days: selectedDays,
  5150. // Extra tab
  5151. time: getNATFieldVal('time', false),
  5152. limit: getNATFieldVal('limit', false),
  5153. // Action tab
  5154. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5155. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5156. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5157. log: document.getElementById('nat-modal-log')?.checked || false,
  5158. log_prefix: getNATFieldVal('logprefix', false)
  5159. };
  5160. try {
  5161. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5162. method: 'POST',
  5163. headers: { 'Content-Type': 'application/json' },
  5164. body: JSON.stringify(payload)
  5165. });
  5166. if (res.ok) {
  5167. const data = await res.json();
  5168. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5169. loadFirewall(false);
  5170. if (closeAfter) {
  5171. closeNATModal();
  5172. } else {
  5173. if (data.id) {
  5174. document.getElementById('nat-modal-id').value = data.id;
  5175. const badge = document.getElementById('nat-modal-badge');
  5176. if (badge) badge.innerText = `#${data.id}`;
  5177. }
  5178. }
  5179. } else {
  5180. const err = await res.json();
  5181. showToast('Error', err.message || 'Failed to save rule', 'error');
  5182. }
  5183. } catch (err) {
  5184. showToast('Error', err.message, 'error');
  5185. }
  5186. }
  5187. function submitSaveNATRule(e) {
  5188. if (e && e.preventDefault) e.preventDefault();
  5189. return applyNATRule(true);
  5190. }
  5191. function startNATStatPolling() {
  5192. stopNATStatPolling();
  5193. pollNATRuleStats();
  5194. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5195. }
  5196. function stopNATStatPolling() {
  5197. if (state.natStatInterval) {
  5198. clearInterval(state.natStatInterval);
  5199. state.natStatInterval = null;
  5200. }
  5201. }
  5202. async function pollNATRuleStats() {
  5203. const id = document.getElementById('nat-modal-id')?.value;
  5204. if (!id) {
  5205. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5206. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5207. return;
  5208. }
  5209. try {
  5210. const res = await fetch(`${API_BASE}/firewall/nat`);
  5211. if (!res.ok) return;
  5212. const rules = await res.json();
  5213. const r = rules.find(x => x.id === id);
  5214. if (!r) return;
  5215. const now = Date.now();
  5216. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5217. state.natLastTimestamp = now;
  5218. const curBytes = r.bytes || 0;
  5219. const curPackets = r.packets || 0;
  5220. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5221. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5222. state.natLastBytes = curBytes;
  5223. state.natLastPackets = curPackets;
  5224. const rateBps = Math.round((deltaBytes * 8) / dt);
  5225. const ratePkt = Math.round(deltaPkts / dt);
  5226. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5227. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5228. state.natStatRateHistory.push(rateBps);
  5229. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5230. state.natStatPktHistory.push(ratePkt);
  5231. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5232. const bEl = document.getElementById('nat-stat-bytes');
  5233. const pEl = document.getElementById('nat-stat-packets');
  5234. const rEl = document.getElementById('nat-stat-rate');
  5235. const prEl = document.getElementById('nat-stat-pktrate');
  5236. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5237. if (pEl) pEl.value = curPackets.toLocaleString();
  5238. if (rEl) rEl.value = formatBps(rateBps);
  5239. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5240. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5241. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5242. } catch (e) {
  5243. console.error('Error polling NAT rule stats', e);
  5244. }
  5245. }
  5246. async function moveNATRule(id, dir) {
  5247. id = decodeURIComponent(id);
  5248. try {
  5249. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5250. method: 'POST',
  5251. headers: { 'Content-Type': 'application/json' },
  5252. body: JSON.stringify({ direction: dir })
  5253. });
  5254. if (!res.ok) throw new Error(await responseError(res));
  5255. await loadFirewall(false);
  5256. } catch (err) {
  5257. showToast('Error', err.message, 'error');
  5258. }
  5259. }
  5260. async function toggleNATRuleState(id, disabled) {
  5261. id = decodeURIComponent(id);
  5262. try {
  5263. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5264. method: 'POST',
  5265. headers: { 'Content-Type': 'application/json' },
  5266. body: JSON.stringify({ disabled })
  5267. });
  5268. if (!res.ok) throw new Error(await responseError(res));
  5269. await loadFirewall(false);
  5270. } catch (err) {
  5271. showToast('Error', err.message, 'error');
  5272. }
  5273. }
  5274. async function deleteNATRule(id) {
  5275. id = decodeURIComponent(id);
  5276. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5277. try {
  5278. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5279. if (!res.ok) throw new Error(await responseError(res));
  5280. {
  5281. showToast('Deleted', 'NAT rule removed', 'success');
  5282. loadFirewall(false);
  5283. }
  5284. } catch (err) {
  5285. showToast('Error', err.message, 'error');
  5286. }
  5287. }
  5288. // ----------------- Mangle Rules -----------------
  5289. function renderMangleRules() {
  5290. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5291. const tbody = document.getElementById('mangle-table-body');
  5292. const empty = document.getElementById('mangle-empty');
  5293. if (!tbody) return;
  5294. tbody.innerHTML = '';
  5295. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5296. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5297. if (rules.length === 0) {
  5298. empty?.classList.remove('hidden');
  5299. return;
  5300. }
  5301. empty?.classList.add('hidden');
  5302. rules.forEach((raw, idx) => {
  5303. const r = safeFirewallRow(raw);
  5304. const tr = document.createElement('tr');
  5305. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5306. let markVal = '<span class="text-slate-500">-</span>';
  5307. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5308. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5309. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5310. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5311. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5312. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5313. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5314. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5315. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5316. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5317. 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>`;
  5318. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5319. tr.innerHTML = `
  5320. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5321. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5322. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5323. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5324. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5325. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5326. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5327. <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>
  5328. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5329. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5330. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5331. </td>
  5332. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5333. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5334. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5335. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5336. <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>
  5337. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5338. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5339. </td>
  5340. `;
  5341. tbody.appendChild(tr);
  5342. });
  5343. }
  5344. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5345. function switchMangleRuleTab(tab) {
  5346. state.activeMangleRuleTab = tab;
  5347. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5348. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5349. btn.classList.add('text-slate-400', 'border-transparent');
  5350. });
  5351. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5352. if (activeBtn) {
  5353. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5354. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5355. }
  5356. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5357. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5358. if (activePane) activePane.classList.remove('hidden');
  5359. if (tab === 'statistics') {
  5360. startMangleStatPolling();
  5361. } else {
  5362. stopMangleStatPolling();
  5363. }
  5364. }
  5365. function toggleMangleField(fieldKey, expand) {
  5366. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5367. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5368. if (!plusBtn || !fieldBox) return;
  5369. if (expand) {
  5370. plusBtn.classList.add('hidden');
  5371. fieldBox.classList.remove('hidden');
  5372. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5373. if (valInput) valInput.focus();
  5374. } else {
  5375. fieldBox.classList.add('hidden');
  5376. plusBtn.classList.remove('hidden');
  5377. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5378. if (valInput) {
  5379. if (valInput.tagName === 'SELECT') {
  5380. valInput.selectedIndex = 0;
  5381. } else {
  5382. valInput.value = '';
  5383. }
  5384. }
  5385. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5386. if (invInput) invInput.checked = false;
  5387. if (fieldKey === 'cs') {
  5388. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5389. const el = document.getElementById(id);
  5390. if (el) el.checked = false;
  5391. });
  5392. }
  5393. if (fieldKey === 'natstate') {
  5394. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5395. const el = document.getElementById(id);
  5396. if (el) el.checked = false;
  5397. });
  5398. }
  5399. }
  5400. }
  5401. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5402. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5403. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5404. toggleMangleField(fieldKey, true);
  5405. let strVal = String(value);
  5406. if (hasInvert) {
  5407. const inv = strVal.startsWith('!');
  5408. if (inv) strVal = strVal.slice(1);
  5409. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5410. if (invEl) invEl.checked = inv;
  5411. else if (inv) strVal = '!'+strVal;
  5412. }
  5413. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5414. 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; }
  5415. } else {
  5416. toggleMangleField(fieldKey, false);
  5417. }
  5418. }
  5419. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5420. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5421. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5422. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5423. let v = valEl ? valEl.value.trim() : '';
  5424. if (!v) return '';
  5425. if (hasInvert) {
  5426. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5427. if (invEl && invEl.checked) {
  5428. v = '!' + v.replace(/^!/, '');
  5429. }
  5430. }
  5431. return v;
  5432. }
  5433. function toggleMaximizeMangleModal() {
  5434. const win = document.getElementById('mangle-modal-window');
  5435. if (!win) return;
  5436. if (win.classList.contains('max-w-[720px]')) {
  5437. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5438. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5439. } else {
  5440. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5441. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5442. }
  5443. }
  5444. function syncMangleChainFromSelect() {
  5445. const sel = document.getElementById('mangle-modal-chain-select');
  5446. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5447. const customInput = document.getElementById('mangle-modal-custom-input');
  5448. const chainInput = document.getElementById('mangle-modal-chain');
  5449. if (!sel || !chainInput) return;
  5450. if (sel.value === '__custom__') {
  5451. if (customWrap) customWrap.classList.remove('hidden');
  5452. if (customInput) {
  5453. customInput.value = '';
  5454. customInput.focus();
  5455. }
  5456. chainInput.value = '';
  5457. } else {
  5458. if (customWrap) customWrap.classList.add('hidden');
  5459. chainInput.value = sel.value;
  5460. }
  5461. handleMangleChainChange();
  5462. }
  5463. function syncMangleCustomChainInput() {
  5464. const customInput = document.getElementById('mangle-modal-custom-input');
  5465. const chainInput = document.getElementById('mangle-modal-chain');
  5466. if (customInput && chainInput) {
  5467. chainInput.value = customInput.value.trim();
  5468. }
  5469. handleMangleChainChange();
  5470. }
  5471. function handleMangleChainChange() {
  5472. const chainInput = document.getElementById('mangle-modal-chain');
  5473. const rawChain = (chainInput?.value || 'prerouting').trim();
  5474. const chain = rawChain.toLowerCase();
  5475. const sel = document.getElementById('mangle-modal-chain-select');
  5476. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5477. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5478. sel.value = chain;
  5479. }
  5480. }
  5481. const hintEl = document.getElementById('mangle-chain-hint');
  5482. if (hintEl) {
  5483. if (chain === 'prerouting') {
  5484. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5485. } else if (chain === 'input') {
  5486. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5487. } else if (chain === 'forward') {
  5488. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5489. } else if (chain === 'output') {
  5490. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5491. } else if (chain === 'postrouting') {
  5492. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5493. } else {
  5494. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5495. }
  5496. }
  5497. const rowIn = document.getElementById('mangle-row-iniface');
  5498. const rowInList = document.getElementById('mangle-row-inifacelist');
  5499. const rowOut = document.getElementById('mangle-row-outiface');
  5500. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5501. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5502. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5503. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5504. if (chain === 'prerouting' || chain === 'input') {
  5505. if (rowIn) rowIn.classList.remove('hidden');
  5506. if (rowInList) rowInList.classList.remove('hidden');
  5507. if (rowOut) rowOut.classList.add('hidden');
  5508. if (rowOutList) rowOutList.classList.add('hidden');
  5509. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5510. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5511. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5512. } else if (chain === 'output' || chain === 'postrouting') {
  5513. if (rowIn) rowIn.classList.add('hidden');
  5514. if (rowInList) rowInList.classList.add('hidden');
  5515. if (rowOut) rowOut.classList.remove('hidden');
  5516. if (rowOutList) rowOutList.classList.remove('hidden');
  5517. if (rowInBridge) rowInBridge.classList.add('hidden');
  5518. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5519. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5520. } else {
  5521. if (rowIn) rowIn.classList.remove('hidden');
  5522. if (rowInList) rowInList.classList.remove('hidden');
  5523. if (rowOut) rowOut.classList.remove('hidden');
  5524. if (rowOutList) rowOutList.classList.remove('hidden');
  5525. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5526. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5527. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5528. }
  5529. checkMangleActionChainCompatibility();
  5530. toggleMangleActionFields();
  5531. }
  5532. function checkMangleActionChainCompatibility() {
  5533. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5534. const chain = rawChain.toLowerCase();
  5535. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5536. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5537. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5538. if (!warnBox || !warnMsg) return;
  5539. let msg = '';
  5540. if (action === 'set-priority' && chain !== 'postrouting') {
  5541. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5542. }
  5543. if (msg) {
  5544. warnMsg.textContent = msg;
  5545. warnBox.classList.remove('hidden');
  5546. } else {
  5547. warnBox.classList.add('hidden');
  5548. }
  5549. }
  5550. function toggleMangleActionFields() {
  5551. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5552. // Hide all dynamic rows first
  5553. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5554. const el = document.getElementById(`mangle-row-${id}`);
  5555. if (el) el.classList.add('hidden');
  5556. });
  5557. const jumpBox = document.getElementById('mangle-action-jump-box');
  5558. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5559. if (jumpBox) jumpBox.classList.add('hidden');
  5560. if (addrBox) addrBox.classList.add('hidden');
  5561. // Activate matching rows
  5562. if (act === 'mark-connection') {
  5563. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5564. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5565. } else if (act === 'mark-routing') {
  5566. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5567. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5568. } else if (act === 'mark-packet') {
  5569. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5570. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5571. } else if (act === 'change-mss') {
  5572. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5573. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5574. } else if (act === 'change-dscp') {
  5575. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5576. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5577. } else if (act === 'change-ttl') {
  5578. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5579. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5580. } else if (act === 'set-priority') {
  5581. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5582. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5583. } else if (act === 'route') {
  5584. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5585. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5586. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5587. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5588. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5589. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5590. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5591. } else if (act === 'jump') {
  5592. if (jumpBox) jumpBox.classList.remove('hidden');
  5593. } else if (act.includes('address-list') || act.includes('address list')) {
  5594. if (addrBox) addrBox.classList.remove('hidden');
  5595. }
  5596. if (act === 'log') {
  5597. const logEl = document.getElementById('mangle-modal-log');
  5598. if (logEl) logEl.checked = true;
  5599. toggleMangleField('logprefix', true);
  5600. }
  5601. checkMangleActionChainCompatibility();
  5602. }
  5603. function toggleMangleLogPrefix() {
  5604. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5605. toggleMangleField('logprefix', !!isLog);
  5606. }
  5607. const allMangleFieldKeys = [
  5608. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5609. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5610. 'routingmark', 'conntype', 'cs', 'natstate',
  5611. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5612. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5613. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5614. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5615. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5616. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5617. ];
  5618. function openAddMangleModal() {
  5619. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5620. switchMangleRuleTab('general');
  5621. const badge = document.getElementById('mangle-modal-badge');
  5622. if (badge) badge.innerText = 'New...';
  5623. document.getElementById('mangle-modal-id').value = '';
  5624. document.getElementById('mangle-modal-family').value = '4';
  5625. document.getElementById('mangle-modal-enabled').checked = true;
  5626. document.getElementById('mangle-modal-comment').value = '';
  5627. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5628. populateChainDropdown('mangle', 'prerouting');
  5629. handleMangleChainChange();
  5630. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5631. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5632. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5633. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5634. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5635. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5636. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5637. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5638. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5639. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5640. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5641. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5642. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5643. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5644. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5645. populateInterfaceSelect('mangle-val-iniface');
  5646. populateInterfaceSelect('mangle-val-outiface');
  5647. populateAddressListSelect('mangle-val-srclist');
  5648. populateAddressListSelect('mangle-val-dstlist');
  5649. populateGeoIPSelect('mangle-val-srcgeo');
  5650. populateGeoIPSelect('mangle-val-dstgeo');
  5651. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5652. resetMangleCounterDisplay();
  5653. toggleMangleActionFields();
  5654. document.getElementById('mangle-modal').classList.remove('hidden');
  5655. }
  5656. function openEditMangleModal(id) {
  5657. id = decodeURIComponent(id);
  5658. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5659. if (!r) return;
  5660. switchMangleRuleTab('general');
  5661. const badge = document.getElementById('mangle-modal-badge');
  5662. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5663. document.getElementById('mangle-modal-id').value = r.id;
  5664. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5665. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5666. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5667. const mangleChain = r.chain || 'prerouting';
  5668. document.getElementById('mangle-modal-chain').value = mangleChain;
  5669. populateChainDropdown('mangle', mangleChain);
  5670. handleMangleChainChange();
  5671. setFirewallActionSelection('mangle', r.action || 'accept');
  5672. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5673. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5674. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5675. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5676. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5677. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5678. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5679. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5680. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5681. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5682. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5683. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5684. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5685. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5686. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5687. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5688. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5689. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5690. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5691. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5692. setMangleFieldVal('src', r.src_address, true);
  5693. setMangleFieldVal('dst', r.dst_address, true);
  5694. setMangleFieldVal('srclist', r.src_address_list, true);
  5695. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5696. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5697. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5698. if (r.protocol && r.protocol !== 'all') {
  5699. setMangleFieldVal('proto', r.protocol, true);
  5700. } else {
  5701. toggleMangleField('proto', false);
  5702. }
  5703. setMangleFieldVal('sport', r.src_port, true);
  5704. setMangleFieldVal('dport', r.dst_port, true);
  5705. setMangleFieldVal('anyport', r.any_port, true);
  5706. setMangleFieldVal('iniface', r.in_interface, true);
  5707. setMangleFieldVal('outiface', r.out_interface, true);
  5708. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5709. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5710. setMangleFieldVal('pktmark', r.packet_mark, true);
  5711. setMangleFieldVal('connmark', r.connection_mark, true);
  5712. setMangleFieldVal('routingmark', r.routing_mark, true);
  5713. setMangleFieldVal('conntype', r.connection_type, false);
  5714. // Connection State
  5715. const states = r.connection_state || [];
  5716. if (states.length > 0) {
  5717. toggleMangleField('cs', true);
  5718. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5719. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5720. if (el) el.checked = states.includes(s);
  5721. });
  5722. } else {
  5723. toggleMangleField('cs', false);
  5724. }
  5725. // Connection NAT State
  5726. const natStates = r.connection_nat_state || [];
  5727. if (natStates.length > 0) {
  5728. toggleMangleField('natstate', true);
  5729. ['srcnat', 'dstnat'].forEach(s => {
  5730. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5731. if (el) el.checked = natStates.includes(s);
  5732. });
  5733. } else {
  5734. toggleMangleField('natstate', false);
  5735. }
  5736. // Advanced tab fields
  5737. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5738. setMangleFieldVal('content', r.content, false);
  5739. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5740. setMangleFieldVal('connrate', r.connection_rate, false);
  5741. setMangleFieldVal('pcc', r.pcc, false);
  5742. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5743. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5744. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5745. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5746. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5747. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5748. setMangleFieldVal('tlshost', r.tls_host, false);
  5749. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5750. setMangleFieldVal('priority', r.priority, false);
  5751. setMangleFieldVal('dscp', r.dscp, false);
  5752. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5753. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5754. setMangleFieldVal('pktsize', r.packet_size, false);
  5755. setMangleFieldVal('random', r.random, false);
  5756. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5757. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5758. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5759. setMangleFieldVal('ttl', r.ttl, false);
  5760. // Extra tab fields
  5761. setMangleFieldVal('nth', r.nth, false);
  5762. setMangleFieldVal('connlimit', r.connection_limit, false);
  5763. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5764. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5765. setMangleFieldVal('hotspot', r.hotspot, false);
  5766. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5767. setMangleFieldVal('limit', r.limit, false);
  5768. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5769. setMangleFieldVal('time', r.time, false);
  5770. setMangleFieldVal('psd', r.psd, false);
  5771. // Action fields
  5772. if (r.jump_target) {
  5773. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5774. if (jtEl) jtEl.value = r.jump_target;
  5775. }
  5776. if (r.address_list) {
  5777. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5778. if (alEl) alEl.value = r.address_list;
  5779. }
  5780. if (r.address_list_timeout) {
  5781. const toEl = document.getElementById('mangle-modal-action-timeout');
  5782. if (toEl) toEl.value = r.address_list_timeout;
  5783. }
  5784. setMangleFieldVal('logprefix', r.log_prefix, false);
  5785. // Statistics
  5786. const bEl = document.getElementById('mangle-stat-bytes');
  5787. const pEl = document.getElementById('mangle-stat-packets');
  5788. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5789. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5790. state.mangleLastBytes = r.bytes || 0;
  5791. state.mangleLastPackets = r.packets || 0;
  5792. state.mangleLastTimestamp = Date.now();
  5793. state.mangleStatRateHistory = new Array(30).fill(0);
  5794. state.mangleStatPktHistory = new Array(30).fill(0);
  5795. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5796. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5797. toggleMangleActionFields();
  5798. document.getElementById('mangle-modal').classList.remove('hidden');
  5799. }
  5800. function closeMangleModal() {
  5801. stopMangleStatPolling();
  5802. document.getElementById('mangle-modal').classList.add('hidden');
  5803. }
  5804. function copyMangleRule() {
  5805. document.getElementById('mangle-modal-id').value = '';
  5806. const badge = document.getElementById('mangle-modal-badge');
  5807. if (badge) badge.innerText = 'New...';
  5808. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5809. }
  5810. function resetMangleCounterDisplay() {
  5811. state.mangleStatRateHistory = new Array(30).fill(0);
  5812. state.mangleStatPktHistory = new Array(30).fill(0);
  5813. state.mangleLastBytes = 0;
  5814. state.mangleLastPackets = 0;
  5815. state.mangleLastTimestamp = Date.now();
  5816. const bEl = document.getElementById('mangle-stat-bytes');
  5817. const pEl = document.getElementById('mangle-stat-packets');
  5818. const rEl = document.getElementById('mangle-stat-rate');
  5819. const prEl = document.getElementById('mangle-stat-pktrate');
  5820. if (bEl) bEl.value = '0 B';
  5821. if (pEl) pEl.value = '0';
  5822. if (rEl) rEl.value = '0 bps';
  5823. if (prEl) prEl.value = '0 p/s';
  5824. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5825. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5826. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5827. }
  5828. async function applyMangleRule(closeAfter = false) {
  5829. const id = document.getElementById('mangle-modal-id').value;
  5830. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5831. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5832. const chainLower = chain.toLowerCase();
  5833. const action = document.getElementById('mangle-modal-action').value;
  5834. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5835. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5836. const src = getMangleFieldVal('src', true);
  5837. const dst = getMangleFieldVal('dst', true);
  5838. const srclist = getMangleFieldVal('srclist', true);
  5839. const dstlist = getMangleFieldVal('dstlist', true);
  5840. const srcgeo = getMangleFieldVal('srcgeo', true);
  5841. const dstgeo = getMangleFieldVal('dstgeo', true);
  5842. const proto = getMangleFieldVal('proto', true);
  5843. const sport = getMangleFieldVal('sport', true);
  5844. const dport = getMangleFieldVal('dport', true);
  5845. const anyport = getMangleFieldVal('anyport', true);
  5846. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5847. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5848. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5849. }
  5850. let iniface = getMangleFieldVal('iniface', true);
  5851. let outiface = getMangleFieldVal('outiface', true);
  5852. let inifacelist = getMangleFieldVal('inifacelist', true);
  5853. let outifacelist = getMangleFieldVal('outifacelist', true);
  5854. if (chainLower === 'prerouting' || chainLower === 'input') {
  5855. outiface = '';
  5856. outifacelist = '';
  5857. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5858. iniface = '';
  5859. inifacelist = '';
  5860. }
  5861. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5862. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5863. switchMangleRuleTab('general');
  5864. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5865. return;
  5866. }
  5867. const pktmark = getMangleFieldVal('pktmark', true);
  5868. const connmark = getMangleFieldVal('connmark', true);
  5869. const routingmark = getMangleFieldVal('routingmark', true);
  5870. const conntype = getMangleFieldVal('conntype', false);
  5871. const states = [];
  5872. const csBox = document.getElementById('mangle-field-cs');
  5873. if (csBox && !csBox.classList.contains('hidden')) {
  5874. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5875. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5876. });
  5877. }
  5878. const natStates = [];
  5879. const natBox = document.getElementById('mangle-field-natstate');
  5880. if (natBox && !natBox.classList.contains('hidden')) {
  5881. ['srcnat', 'dstnat'].forEach(s => {
  5882. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5883. });
  5884. }
  5885. const payload = {
  5886. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5887. id,
  5888. chain,
  5889. action,
  5890. protocol: proto || 'all',
  5891. src_address: src,
  5892. dst_address: dst,
  5893. src_port: sport,
  5894. dst_port: dport,
  5895. any_port: anyport,
  5896. in_interface: iniface,
  5897. out_interface: outiface,
  5898. in_interface_list: inifacelist,
  5899. out_interface_list: outifacelist,
  5900. packet_mark: pktmark,
  5901. connection_mark: connmark,
  5902. routing_mark: routingmark,
  5903. connection_type: conntype,
  5904. connection_state: states,
  5905. connection_nat_state: natStates,
  5906. src_address_list: srclist,
  5907. dst_address_list: dstlist,
  5908. src_geoip: srcgeo,
  5909. dst_geoip: dstgeo,
  5910. comment,
  5911. disabled: !enabled,
  5912. // Advanced tab
  5913. content: getMangleFieldVal('content', false),
  5914. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5915. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5916. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5917. ipsec_policy: getMangleFieldVal('ipsec', false),
  5918. dscp: getMangleFieldVal('dscp', false),
  5919. tcp_mss: getMangleFieldVal('tcpmss', false),
  5920. tos: document.getElementById('mangle-val-tos')?.value || '',
  5921. packet_size: getMangleFieldVal('pktsize', false),
  5922. random: getMangleFieldVal('random', false),
  5923. tcp_flags: getMangleFieldVal('tcpflags', false),
  5924. icmp_options: getMangleFieldVal('icmpoptions', false),
  5925. ttl: getMangleFieldVal('ttl', false),
  5926. // Extra tab
  5927. nth: getMangleFieldVal('nth', false),
  5928. connection_limit: getMangleFieldVal('connlimit', false),
  5929. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5930. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5931. ip_fragment: getMangleFieldVal('ipfragment', false),
  5932. limit: getMangleFieldVal('limit', false),
  5933. time: getMangleFieldVal('time', false),
  5934. // Action tab
  5935. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5936. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5937. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5938. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5939. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5940. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5941. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5942. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5943. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5944. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5945. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5946. log: document.getElementById('mangle-modal-log')?.checked || false,
  5947. log_prefix: getMangleFieldVal('logprefix', false)
  5948. };
  5949. try {
  5950. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5951. method: 'POST',
  5952. headers: { 'Content-Type': 'application/json' },
  5953. body: JSON.stringify(payload)
  5954. });
  5955. if (res.ok) {
  5956. const data = await res.json();
  5957. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5958. loadFirewall(false);
  5959. if (closeAfter) {
  5960. closeMangleModal();
  5961. } else {
  5962. if (data.id) {
  5963. document.getElementById('mangle-modal-id').value = data.id;
  5964. const badge = document.getElementById('mangle-modal-badge');
  5965. if (badge) badge.innerText = `#${data.id}`;
  5966. }
  5967. }
  5968. } else {
  5969. const err = await res.json();
  5970. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5971. }
  5972. } catch (err) {
  5973. showToast('Error', err.message, 'error');
  5974. }
  5975. }
  5976. function submitSaveMangleRule(e) {
  5977. if (e && e.preventDefault) e.preventDefault();
  5978. return applyMangleRule(true);
  5979. }
  5980. function startMangleStatPolling() {
  5981. stopMangleStatPolling();
  5982. pollMangleRuleStats();
  5983. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5984. }
  5985. function stopMangleStatPolling() {
  5986. if (state.mangleStatInterval) {
  5987. clearInterval(state.mangleStatInterval);
  5988. state.mangleStatInterval = null;
  5989. }
  5990. }
  5991. async function pollMangleRuleStats() {
  5992. const id = document.getElementById('mangle-modal-id')?.value;
  5993. if (!id) {
  5994. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5995. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5996. return;
  5997. }
  5998. try {
  5999. const res = await fetch(`${API_BASE}/firewall/mangle`);
  6000. if (!res.ok) return;
  6001. const rules = await res.json();
  6002. const r = rules.find(x => x.id === id);
  6003. if (!r) return;
  6004. const now = Date.now();
  6005. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  6006. state.mangleLastTimestamp = now;
  6007. const curBytes = r.bytes || 0;
  6008. const curPackets = r.packets || 0;
  6009. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  6010. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  6011. state.mangleLastBytes = curBytes;
  6012. state.mangleLastPackets = curPackets;
  6013. const rateBps = Math.round((deltaBytes * 8) / dt);
  6014. const ratePkt = Math.round(deltaPkts / dt);
  6015. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  6016. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  6017. state.mangleStatRateHistory.push(rateBps);
  6018. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  6019. state.mangleStatPktHistory.push(ratePkt);
  6020. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  6021. const bEl = document.getElementById('mangle-stat-bytes');
  6022. const pEl = document.getElementById('mangle-stat-packets');
  6023. const rEl = document.getElementById('mangle-stat-rate');
  6024. const prEl = document.getElementById('mangle-stat-pktrate');
  6025. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  6026. if (pEl) pEl.value = curPackets.toLocaleString();
  6027. if (rEl) rEl.value = formatBps(rateBps);
  6028. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  6029. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  6030. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  6031. } catch (e) {
  6032. console.error('Error polling Mangle rule stats', e);
  6033. }
  6034. }
  6035. async function moveMangleRule(id, dir) {
  6036. id = decodeURIComponent(id);
  6037. try {
  6038. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  6039. method: 'POST',
  6040. headers: { 'Content-Type': 'application/json' },
  6041. body: JSON.stringify({ direction: dir })
  6042. });
  6043. if (!res.ok) throw new Error(await responseError(res));
  6044. await loadFirewall(false);
  6045. } catch (err) {
  6046. showToast('Error', err.message, 'error');
  6047. }
  6048. }
  6049. async function toggleMangleRuleState(id, disabled) {
  6050. id = decodeURIComponent(id);
  6051. try {
  6052. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6053. method: 'POST',
  6054. headers: { 'Content-Type': 'application/json' },
  6055. body: JSON.stringify({ disabled })
  6056. });
  6057. if (!res.ok) throw new Error(await responseError(res));
  6058. await loadFirewall(false);
  6059. } catch (err) {
  6060. showToast('Error', err.message, 'error');
  6061. }
  6062. }
  6063. async function deleteMangleRule(id) {
  6064. id = decodeURIComponent(id);
  6065. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6066. try {
  6067. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6068. if (!res.ok) throw new Error(await responseError(res));
  6069. {
  6070. showToast('Deleted', 'Mangle rule removed', 'success');
  6071. loadFirewall(false);
  6072. }
  6073. } catch (err) {
  6074. showToast('Error', err.message, 'error');
  6075. }
  6076. }
  6077. // ----------------- Address Lists -----------------
  6078. function renderAddressLists() {
  6079. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6080. const tbody = document.getElementById('addrlist-table-body');
  6081. const empty = document.getElementById('addrlist-empty');
  6082. if (!tbody) return;
  6083. tbody.innerHTML = '';
  6084. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6085. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6086. // Update filter select
  6087. const sel = document.getElementById('addrlist-filter-name');
  6088. if (sel) {
  6089. const cur = sel.value;
  6090. sel.innerHTML = '<option value="">All Lists</option>';
  6091. const set = new Set((state.addressLists || []).map(a => a.name));
  6092. set.forEach(n => {
  6093. const opt = document.createElement('option');
  6094. opt.value = n;
  6095. opt.innerText = n;
  6096. if (n === cur) opt.selected = true;
  6097. sel.appendChild(opt);
  6098. });
  6099. }
  6100. if (entries.length === 0) {
  6101. empty?.classList.remove('hidden');
  6102. return;
  6103. }
  6104. empty?.classList.add('hidden');
  6105. entries.forEach((raw, idx) => {
  6106. const e = safeFirewallRow(raw);
  6107. const tr = document.createElement('tr');
  6108. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6109. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6110. tr.innerHTML = `
  6111. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6112. <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>
  6113. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6114. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6115. <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>
  6116. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6117. ${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>
  6118. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6119. `}
  6120. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6121. </td>
  6122. `;
  6123. tbody.appendChild(tr);
  6124. });
  6125. populateCommonAddrListDatalist();
  6126. }
  6127. function openAddAddrListModal() {
  6128. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6129. document.getElementById('addrlist-modal-id').value = '';
  6130. document.getElementById('addrlist-modal-name').value = '';
  6131. document.getElementById('addrlist-modal-addr').value = '';
  6132. document.getElementById('addrlist-modal-comment').value = '';
  6133. document.getElementById('addrlist-modal-disabled').checked = false;
  6134. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6135. if (submitBtn) submitBtn.innerText = 'Add to List';
  6136. document.getElementById('addrlist-modal').classList.remove('hidden');
  6137. }
  6138. function openEditAddrListModal(id) {
  6139. id = decodeURIComponent(id);
  6140. const e = (state.addressLists || []).find(item => item.id === id);
  6141. if (!e) return;
  6142. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6143. document.getElementById('addrlist-modal-id').value = e.id;
  6144. document.getElementById('addrlist-modal-name').value = e.name;
  6145. document.getElementById('addrlist-modal-addr').value = e.address;
  6146. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6147. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6148. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6149. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6150. document.getElementById('addrlist-modal').classList.remove('hidden');
  6151. }
  6152. function closeAddrListModal() {
  6153. document.getElementById('addrlist-modal').classList.add('hidden');
  6154. }
  6155. async function submitSaveAddrList(e) {
  6156. e.preventDefault();
  6157. const id = document.getElementById('addrlist-modal-id').value;
  6158. const name = document.getElementById('addrlist-modal-name').value.trim();
  6159. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6160. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6161. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6162. try {
  6163. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6164. method: 'POST',
  6165. headers: { 'Content-Type': 'application/json' },
  6166. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6167. });
  6168. if (res.ok) {
  6169. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6170. closeAddrListModal();
  6171. loadFirewall(false);
  6172. } else {
  6173. const err = await res.json();
  6174. showToast('Error', err.message || 'Failed to save address list', 'error');
  6175. }
  6176. } catch (err) {
  6177. showToast('Error', err.message, 'error');
  6178. }
  6179. }
  6180. async function toggleAddrListState(id, disabled) {
  6181. id = decodeURIComponent(id);
  6182. try {
  6183. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6184. method: 'POST',
  6185. headers: { 'Content-Type': 'application/json' },
  6186. body: JSON.stringify({ disabled })
  6187. });
  6188. if (res.ok) {
  6189. loadFirewall(false);
  6190. }
  6191. } catch (err) {
  6192. showToast('Error', err.message, 'error');
  6193. }
  6194. }
  6195. async function deleteAddrList(id) {
  6196. id = decodeURIComponent(id);
  6197. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6198. try {
  6199. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6200. if (res.ok) {
  6201. showToast('Deleted', 'Address list item removed', 'info');
  6202. loadFirewall(false);
  6203. }
  6204. } catch (err) {
  6205. showToast('Error', err.message, 'error');
  6206. }
  6207. }
  6208. // ----------------- Geo-Location IP Management -----------------
  6209. async function loadGeoIP() {
  6210. try {
  6211. const [statusRes, countriesRes] = await Promise.all([
  6212. fetch(`${API_BASE}/firewall/geoip/status`),
  6213. fetch(`${API_BASE}/firewall/geoip/countries`)
  6214. ]);
  6215. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6216. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6217. updateGeoHeader();
  6218. renderGeoCountries();
  6219. } catch (err) {
  6220. console.error('Failed to load GeoIP:', err);
  6221. }
  6222. }
  6223. function getGeoUsageMap() {
  6224. const usage = {};
  6225. const checkRule = (r, type) => {
  6226. ['src_geoip', 'dst_geoip'].forEach(field => {
  6227. let val = (r && r[field]) || '';
  6228. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6229. if (code) {
  6230. if (!usage[code]) usage[code] = [];
  6231. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6232. if (!usage[code].includes(label)) usage[code].push(label);
  6233. }
  6234. });
  6235. };
  6236. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6237. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6238. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6239. return usage;
  6240. }
  6241. function updateGeoHeader() {
  6242. const s = state.geoStatus || {};
  6243. const statusBadge = document.getElementById('geo-status-badge');
  6244. if (statusBadge) {
  6245. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6246. statusBadge.className = s.auto_update
  6247. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6248. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6249. }
  6250. const intervalLabel = document.getElementById('geo-interval-label');
  6251. if (intervalLabel) {
  6252. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6253. }
  6254. const usageMap = getGeoUsageMap();
  6255. const inUseCount = Object.keys(usageMap).length;
  6256. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6257. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6258. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6259. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6260. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6261. if (lastSyncEl) {
  6262. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6263. const d = new Date(s.last_updated);
  6264. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6265. } else {
  6266. lastSyncEl.innerText = 'Never (Sync Pending)';
  6267. }
  6268. }
  6269. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6270. if (nextSyncEl) {
  6271. if (s.next_update && !s.next_update.startsWith('0001')) {
  6272. const d = new Date(s.next_update);
  6273. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6274. } else {
  6275. nextSyncEl.innerText = '-';
  6276. }
  6277. }
  6278. const badge = document.getElementById('fw-badge-geo');
  6279. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6280. }
  6281. function renderGeoCountries() {
  6282. const tbody = document.getElementById('geo-table-body');
  6283. const empty = document.getElementById('geo-empty');
  6284. if (!tbody) return;
  6285. tbody.innerHTML = '';
  6286. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6287. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6288. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6289. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6290. const usageMap = getGeoUsageMap();
  6291. const countries = (state.geoCountries || []).filter(c => {
  6292. const isUsed = !!usageMap[c.code];
  6293. if (inUseOnly && !isUsed) return false;
  6294. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6295. if (continent && c.continent !== continent) return false;
  6296. if (q) {
  6297. const matchCode = c.code.toLowerCase().includes(q);
  6298. const matchName = c.name.toLowerCase().includes(q);
  6299. if (!matchCode && !matchName) return false;
  6300. }
  6301. return true;
  6302. });
  6303. if (countries.length === 0) {
  6304. empty?.classList.remove('hidden');
  6305. return;
  6306. }
  6307. empty?.classList.add('hidden');
  6308. countries.forEach(c => {
  6309. const tr = document.createElement('tr');
  6310. const isUsed = !!usageMap[c.code];
  6311. const rulesUsing = usageMap[c.code] || [];
  6312. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6313. let statusHtml = '';
  6314. if (isUsed) {
  6315. 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>`;
  6316. } else if (c.subnet_count > 0) {
  6317. 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>';
  6318. } else {
  6319. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6320. }
  6321. tr.innerHTML = `
  6322. <td class="py-2.5 px-3 text-center">
  6323. <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'}">
  6324. ${c.code}
  6325. </span>
  6326. </td>
  6327. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6328. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6329. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6330. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6331. </td>
  6332. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6333. <td class="py-2.5 px-3">
  6334. ${statusHtml}
  6335. </td>
  6336. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6337. <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>
  6338. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6339. </td>
  6340. `;
  6341. tbody.appendChild(tr);
  6342. });
  6343. }
  6344. function quickFilterGeo(preset) {
  6345. const searchInput = document.getElementById('geo-search-input');
  6346. const continentSel = document.getElementById('geo-continent-filter');
  6347. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6348. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6349. if (searchInput) searchInput.value = '';
  6350. if (continentSel) continentSel.value = '';
  6351. if (inUseCheck) inUseCheck.checked = false;
  6352. if (cachedCheck) cachedCheck.checked = false;
  6353. if (preset === 'GR') {
  6354. if (searchInput) searchInput.value = 'Greece';
  6355. } else if (preset === 'Europe') {
  6356. if (continentSel) continentSel.value = 'Europe';
  6357. } else if (preset === 'HIGHRISK') {
  6358. if (searchInput) searchInput.value = 'China';
  6359. }
  6360. renderGeoCountries();
  6361. }
  6362. async function toggleGeoCountry(code, enabled) {
  6363. try {
  6364. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6365. method: 'POST',
  6366. headers: { 'Content-Type': 'application/json' },
  6367. body: JSON.stringify({ enabled })
  6368. });
  6369. if (res.ok) {
  6370. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6371. loadGeoIP();
  6372. } else {
  6373. const err = await res.json();
  6374. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6375. }
  6376. } catch (err) {
  6377. showToast('Error', err.message, 'error');
  6378. }
  6379. }
  6380. async function updateGeoCountry(code) {
  6381. try {
  6382. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6383. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6384. if (res.ok) {
  6385. const data = await res.json();
  6386. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6387. loadGeoIP();
  6388. } else {
  6389. const err = await res.json();
  6390. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6391. }
  6392. } catch (err) {
  6393. showToast('Error', err.message, 'error');
  6394. }
  6395. }
  6396. async function triggerGeoUpdateNow() {
  6397. const spinner = document.getElementById('geo-update-spinner');
  6398. if (spinner) spinner.classList.remove('hidden');
  6399. try {
  6400. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6401. if (res.ok) {
  6402. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6403. setTimeout(() => {
  6404. loadGeoIP();
  6405. if (spinner) spinner.classList.add('hidden');
  6406. }, 2500);
  6407. } else {
  6408. const err = await res.json();
  6409. showToast('Notice', err.message || 'Update in progress', 'info');
  6410. if (spinner) spinner.classList.add('hidden');
  6411. }
  6412. } catch (err) {
  6413. showToast('Error', err.message, 'error');
  6414. if (spinner) spinner.classList.add('hidden');
  6415. }
  6416. }
  6417. async function applyGeoPreset(preset) {
  6418. try {
  6419. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6420. method: 'POST',
  6421. headers: { 'Content-Type': 'application/json' },
  6422. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6423. });
  6424. if (res.ok) {
  6425. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6426. loadGeoIP();
  6427. }
  6428. } catch (err) {
  6429. showToast('Error', err.message, 'error');
  6430. }
  6431. }
  6432. function openGeoIntervalModal() {
  6433. const s = state.geoStatus || {};
  6434. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6435. const sel = document.getElementById('geo-cfg-interval');
  6436. const customBox = document.getElementById('geo-cfg-custom-box');
  6437. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6438. const curHours = s.interval_hours || 24;
  6439. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6440. if (matchOption) {
  6441. sel.value = String(curHours);
  6442. customBox.classList.add('hidden');
  6443. } else {
  6444. sel.value = 'custom';
  6445. customHoursInput.value = curHours;
  6446. customBox.classList.remove('hidden');
  6447. }
  6448. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6449. }
  6450. function closeGeoIntervalModal() {
  6451. document.getElementById('geo-interval-modal').classList.add('hidden');
  6452. }
  6453. function toggleCustomGeoInterval() {
  6454. const val = document.getElementById('geo-cfg-interval').value;
  6455. const customBox = document.getElementById('geo-cfg-custom-box');
  6456. if (val === 'custom') {
  6457. customBox.classList.remove('hidden');
  6458. } else {
  6459. customBox.classList.add('hidden');
  6460. }
  6461. }
  6462. async function submitGeoIntervalSettings(e) {
  6463. e.preventDefault();
  6464. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6465. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6466. let hours = 24;
  6467. if (intervalVal === 'custom') {
  6468. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6469. } else {
  6470. hours = parseInt(intervalVal, 10) || 24;
  6471. }
  6472. try {
  6473. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6474. method: 'POST',
  6475. headers: { 'Content-Type': 'application/json' },
  6476. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6477. });
  6478. if (res.ok) {
  6479. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6480. closeGeoIntervalModal();
  6481. loadGeoIP();
  6482. } else {
  6483. const err = await res.json();
  6484. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6485. }
  6486. } catch (err) {
  6487. showToast('Error', err.message, 'error');
  6488. }
  6489. }
  6490. async function viewGeoSubnets(code, name) {
  6491. if (!name) {
  6492. const found = (state.geoCountries || []).find(x => x.code === code);
  6493. name = found ? found.name : code;
  6494. }
  6495. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6496. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6497. const listEl = document.getElementById('geo-subnets-list');
  6498. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6499. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6500. try {
  6501. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6502. if (res.ok) {
  6503. const data = await res.json();
  6504. const subnets = data.subnets || [];
  6505. if (subnets.length === 0) {
  6506. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6507. } else {
  6508. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6509. }
  6510. } else {
  6511. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6512. }
  6513. } catch (err) {
  6514. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6515. }
  6516. }
  6517. function closeGeoSubnetsModal() {
  6518. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6519. }
  6520. // ----------------- Active Connections Tracking -----------------
  6521. async function loadConnections() {
  6522. try {
  6523. const res = await fetch(`${API_BASE}/firewall/connections`);
  6524. const data = await res.json();
  6525. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6526. state.connections = Array.isArray(data) ? data : [];
  6527. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6528. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6529. renderConnections();
  6530. } catch (err) {
  6531. console.error('Failed to load connections:', err);
  6532. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6533. }
  6534. }
  6535. function renderConnections() {
  6536. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6537. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6538. const tbody = document.getElementById('conns-table-body');
  6539. const empty = document.getElementById('conns-empty');
  6540. if (!tbody) return;
  6541. tbody.innerHTML = '';
  6542. const conns = (state.connections || []).filter(c => {
  6543. if (protoFilter && c.protocol !== protoFilter) return false;
  6544. if (search) {
  6545. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6546. if (!line.includes(search)) return false;
  6547. }
  6548. return true;
  6549. });
  6550. if (conns.length === 0) {
  6551. empty?.classList.remove('hidden');
  6552. return;
  6553. }
  6554. empty?.classList.add('hidden');
  6555. conns.slice(0, 150).forEach(c => {
  6556. const tr = document.createElement('tr');
  6557. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6558. let stateColor = 'text-slate-400';
  6559. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6560. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6561. tr.innerHTML = `
  6562. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6563. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6564. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6565. <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>
  6566. <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>
  6567. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6568. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6569. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6570. <td class="py-2.5 px-3 text-right font-sans">
  6571. ${['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>` : ''}
  6572. </td>
  6573. `;
  6574. tbody.appendChild(tr);
  6575. });
  6576. }
  6577. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6578. try {
  6579. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6580. method: 'POST',
  6581. headers: { 'Content-Type': 'application/json' },
  6582. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6583. });
  6584. if (res.ok) {
  6585. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6586. loadConnections();
  6587. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6588. } catch (err) {
  6589. showToast('Error', err.message, 'error');
  6590. }
  6591. }
  6592. async function resetFirewallCounters() {
  6593. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6594. try {
  6595. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6596. if (res.ok) {
  6597. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6598. loadFirewall(false);
  6599. }
  6600. } catch (err) {
  6601. showToast('Error', err.message, 'error');
  6602. }
  6603. }
  6604. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6605. function switchRoutesSubTab(tab) {
  6606. state.routesSubTab = tab;
  6607. const tabs = ['routes', 'rules', 'tables'];
  6608. tabs.forEach(t => {
  6609. const panel = document.getElementById(`routes-subtab-${t}`);
  6610. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6611. if (panel) {
  6612. if (t === tab) panel.classList.remove('hidden');
  6613. else panel.classList.add('hidden');
  6614. }
  6615. if (btn) {
  6616. if (t === tab) {
  6617. 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';
  6618. } else {
  6619. 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';
  6620. }
  6621. }
  6622. });
  6623. setTimeout(initTableSorting, 50);
  6624. }
  6625. async function loadRoutes() {
  6626. try {
  6627. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6628. fetch(`${API_BASE}/routes`),
  6629. fetch(`${API_BASE}/routing/rules`),
  6630. fetch(`${API_BASE}/routing/tables`)
  6631. ]);
  6632. if (routesRes.ok) state.routes = await routesRes.json();
  6633. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6634. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6635. const bRoutes = document.getElementById('routes-badge-routes');
  6636. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6637. const showSystem = document.getElementById('prule-show-system')?.checked;
  6638. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6639. const bRules = document.getElementById('routes-badge-rules');
  6640. if (bRules) bRules.innerText = userRules.length;
  6641. const bTables = document.getElementById('routes-badge-tables');
  6642. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6643. const bRoutesCount = document.getElementById('badge-routes-count');
  6644. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6645. renderRoutesList();
  6646. renderPolicyRules();
  6647. renderRoutingTables();
  6648. } catch (err) {
  6649. console.error('Failed to load routing:', err);
  6650. }
  6651. }
  6652. function getRouteProtocolBadge(proto) {
  6653. const p = (proto || 'static').toLowerCase();
  6654. switch (p) {
  6655. case 'bgp':
  6656. 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>`;
  6657. case 'ibgp':
  6658. 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>`;
  6659. case 'ospf':
  6660. 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>`;
  6661. case 'rip':
  6662. 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>`;
  6663. case 'babel':
  6664. 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>`;
  6665. case 'eigrp':
  6666. 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>`;
  6667. case 'static':
  6668. 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>`;
  6669. case 'connected':
  6670. 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>`;
  6671. case 'dhcp':
  6672. 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>`;
  6673. case 'multicast':
  6674. 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>`;
  6675. default:
  6676. 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>`;
  6677. }
  6678. }
  6679. function renderRoutesList() {
  6680. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6681. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6682. const tbody = document.getElementById('routes-table-body');
  6683. const empty = document.getElementById('routes-empty');
  6684. if (!tbody) return;
  6685. // Update table filter select
  6686. const sel = document.getElementById('routes-filter-table');
  6687. if (sel) {
  6688. const cur = sel.value;
  6689. sel.innerHTML = '<option value="">All Tables</option>';
  6690. (state.routingTables || []).forEach(t => {
  6691. const opt = document.createElement('option');
  6692. opt.value = t.name;
  6693. opt.innerText = t.name;
  6694. if (t.name === cur) opt.selected = true;
  6695. sel.appendChild(opt);
  6696. });
  6697. }
  6698. const routes = (state.routes || []).filter(r => {
  6699. if (tableFilter && r.routing_table !== tableFilter) return false;
  6700. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6701. if (typeFilter === 'multicast' && !r.multicast) return false;
  6702. if (typeFilter === 'static' && !r.static) return false;
  6703. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6704. if (typeFilter === 'connected' && !r.connect) return false;
  6705. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6706. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6707. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6708. return true;
  6709. });
  6710. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6711. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6712. let summaryText = `${routes.length} Routes`;
  6713. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6714. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6715. const badgeEl = document.getElementById('routes-count-badge');
  6716. if (badgeEl) badgeEl.innerText = summaryText;
  6717. if (routes.length === 0) {
  6718. empty?.classList.remove('hidden');
  6719. tbody.innerHTML = '';
  6720. return;
  6721. }
  6722. empty?.classList.add('hidden');
  6723. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6724. if (tbody.dataset.sig === sig) {
  6725. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6726. }
  6727. tbody.dataset.sig = sig;
  6728. tbody.innerHTML = '';
  6729. routes.forEach(r => {
  6730. const tr = document.createElement('tr');
  6731. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6732. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6733. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6734. let flags = '';
  6735. if (r.dynamic) flags += 'D';
  6736. if (r.active) flags += 'A';
  6737. if (r.connect) flags += 'C';
  6738. if (r.static) flags += 'S';
  6739. if (r.ecmp) flags += 'E';
  6740. if (r.multicast) flags += 'M';
  6741. if (r.disabled) flags += 'X';
  6742. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6743. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6744. if (r.check_gateway === 'internet') {
  6745. if (r.health_status === 'online') {
  6746. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6747. healthCell = `
  6748. <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)">
  6749. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6750. <span>Internet OK (${ms}ms)</span>
  6751. </span>
  6752. `;
  6753. } else if (r.health_status === 'offline') {
  6754. healthCell = `
  6755. <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.">
  6756. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6757. <span>Internet Down</span>
  6758. </span>
  6759. `;
  6760. } else {
  6761. healthCell = `
  6762. <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">
  6763. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6764. <span>Checking...</span>
  6765. </span>
  6766. `;
  6767. }
  6768. } else if (r.check_gateway === 'ping') {
  6769. if (r.health_status === 'online') {
  6770. healthCell = `
  6771. <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">
  6772. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6773. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6774. </span>
  6775. `;
  6776. } else if (r.health_status === 'offline') {
  6777. healthCell = `
  6778. <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">
  6779. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6780. <span>Gateway Dead</span>
  6781. </span>
  6782. `;
  6783. }
  6784. }
  6785. const flagDescriptions = [];
  6786. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6787. if (r.active) flagDescriptions.push('Active (A)');
  6788. if (r.connect) flagDescriptions.push('Connected (C)');
  6789. if (r.static) flagDescriptions.push('Static (S)');
  6790. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6791. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6792. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6793. tr.innerHTML = `
  6794. <td class="py-2.5 px-3 text-center">
  6795. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6796. 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')
  6797. }" title="Flags: ${flagDescriptions.join(', ')}">
  6798. ${flags || '-'}
  6799. </span>
  6800. </td>
  6801. <td class="py-2.5 px-3">
  6802. <div class="flex items-center gap-1.5 flex-wrap">
  6803. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6804. ${r.ecmp ? `
  6805. <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)">
  6806. <span>⚡ ECMP</span>
  6807. </span>
  6808. ` : ''}
  6809. ${r.multicast ? `
  6810. <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">
  6811. <span>IGMP</span>
  6812. </span>
  6813. ` : ''}
  6814. </div>
  6815. </td>
  6816. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6817. <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>
  6818. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6819. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6820. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6821. <td class="py-2.5 px-3">${healthCell}</td>
  6822. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6823. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6824. ${r.static ? `
  6825. <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>
  6826. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6827. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6828. ` : `
  6829. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6830. `}
  6831. </td>
  6832. `;
  6833. tbody.appendChild(tr);
  6834. });
  6835. }
  6836. function openAddRouteModal() {
  6837. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6838. document.getElementById('route-modal-id').value = '';
  6839. document.getElementById('route-modal-old-dst').value = '';
  6840. document.getElementById('route-modal-old-gw').value = '';
  6841. document.getElementById('route-modal-old-distance').value = '';
  6842. document.getElementById('route-modal-old-table').value = '';
  6843. document.getElementById('route-modal-old-iface').value = '';
  6844. const dstInput = document.getElementById('route-modal-dst');
  6845. const gwInput = document.getElementById('route-modal-gw');
  6846. const distInput = document.getElementById('route-modal-distance');
  6847. const ifaceSelect = document.getElementById('route-modal-iface');
  6848. const tableSelect = document.getElementById('route-modal-table');
  6849. const commentInput = document.getElementById('route-modal-comment');
  6850. const disCheck = document.getElementById('route-modal-disabled');
  6851. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6852. dstInput.disabled = false;
  6853. dstInput.value = '0.0.0.0/0';
  6854. gwInput.disabled = false;
  6855. gwInput.value = '';
  6856. distInput.disabled = false;
  6857. distInput.value = '1';
  6858. ifaceSelect.disabled = false;
  6859. tableSelect.disabled = false;
  6860. commentInput.disabled = false;
  6861. commentInput.value = '';
  6862. disCheck.disabled = false;
  6863. disCheck.checked = false;
  6864. if (saveBtn) saveBtn.classList.remove('hidden');
  6865. const checkGw = document.getElementById('route-modal-check-gw');
  6866. if (checkGw) checkGw.value = 'internet';
  6867. const checkTarget = document.getElementById('route-modal-check-target');
  6868. if (checkTarget) checkTarget.value = '1.1.1.1';
  6869. const checkInterval = document.getElementById('route-modal-check-interval');
  6870. if (checkInterval) checkInterval.value = '5';
  6871. const checkThresh = document.getElementById('route-modal-check-threshold');
  6872. if (checkThresh) checkThresh.value = '3';
  6873. toggleRouteCheckModeUI();
  6874. populateInterfaceSelect('route-modal-iface');
  6875. // Populate tables
  6876. tableSelect.innerHTML = '';
  6877. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6878. const opt = document.createElement('option');
  6879. opt.value = t.name;
  6880. opt.innerText = t.name;
  6881. if (t.name === 'main') opt.selected = true;
  6882. tableSelect.appendChild(opt);
  6883. });
  6884. document.getElementById('route-modal').classList.remove('hidden');
  6885. }
  6886. function openEditRouteModal(id) {
  6887. const r = (state.routes || []).find(route => route.id === id);
  6888. if (!r) return;
  6889. const isStatic = !!r.static;
  6890. document.getElementById('route-modal-title').innerText = isStatic
  6891. ? `Edit Route: ${r.dst_address}`
  6892. : `Route Properties (Read Only): ${r.dst_address}`;
  6893. document.getElementById('route-modal-id').value = r.id;
  6894. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6895. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6896. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6897. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6898. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6899. const dstInput = document.getElementById('route-modal-dst');
  6900. const gwInput = document.getElementById('route-modal-gw');
  6901. const distInput = document.getElementById('route-modal-distance');
  6902. const ifaceSelect = document.getElementById('route-modal-iface');
  6903. const tableSelect = document.getElementById('route-modal-table');
  6904. const commentInput = document.getElementById('route-modal-comment');
  6905. const disCheck = document.getElementById('route-modal-disabled');
  6906. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6907. dstInput.value = r.dst_address;
  6908. gwInput.value = r.gateway || '';
  6909. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6910. commentInput.value = r.comment || '';
  6911. disCheck.checked = !!r.disabled;
  6912. const checkGw = document.getElementById('route-modal-check-gw');
  6913. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6914. const checkTarget = document.getElementById('route-modal-check-target');
  6915. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6916. const checkInterval = document.getElementById('route-modal-check-interval');
  6917. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6918. const checkThresh = document.getElementById('route-modal-check-threshold');
  6919. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6920. toggleRouteCheckModeUI();
  6921. dstInput.disabled = !isStatic;
  6922. gwInput.disabled = !isStatic;
  6923. distInput.disabled = !isStatic;
  6924. ifaceSelect.disabled = !isStatic;
  6925. tableSelect.disabled = !isStatic;
  6926. commentInput.disabled = !isStatic;
  6927. disCheck.disabled = !isStatic;
  6928. if (checkGw) checkGw.disabled = !isStatic;
  6929. if (checkTarget) checkTarget.disabled = !isStatic;
  6930. if (checkInterval) checkInterval.disabled = !isStatic;
  6931. if (checkThresh) checkThresh.disabled = !isStatic;
  6932. if (saveBtn) {
  6933. if (isStatic) {
  6934. saveBtn.classList.remove('hidden');
  6935. } else {
  6936. saveBtn.classList.add('hidden');
  6937. }
  6938. }
  6939. populateInterfaceSelect('route-modal-iface', r.interface);
  6940. tableSelect.innerHTML = '';
  6941. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6942. const opt = document.createElement('option');
  6943. opt.value = t.name;
  6944. opt.innerText = t.name;
  6945. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6946. tableSelect.appendChild(opt);
  6947. });
  6948. document.getElementById('route-modal').classList.remove('hidden');
  6949. }
  6950. function closeRouteModal() {
  6951. document.getElementById('route-modal').classList.add('hidden');
  6952. }
  6953. function setRouteCheckTarget(ip) {
  6954. const inp = document.getElementById('route-modal-check-target');
  6955. if (inp) inp.value = ip;
  6956. }
  6957. function toggleRouteCheckModeUI() {
  6958. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6959. const targetRow = document.getElementById('route-row-check-target');
  6960. const paramsRow = document.getElementById('route-row-check-params');
  6961. if (mode === 'none') {
  6962. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6963. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6964. } else if (mode === 'ping') {
  6965. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6966. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6967. } else { // internet
  6968. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6969. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6970. }
  6971. }
  6972. async function submitSaveRoute(e) {
  6973. e.preventDefault();
  6974. const id = document.getElementById('route-modal-id').value;
  6975. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6976. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6977. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6978. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6979. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6980. const dst = document.getElementById('route-modal-dst').value.trim();
  6981. const gw = document.getElementById('route-modal-gw').value.trim();
  6982. const table = document.getElementById('route-modal-table').value;
  6983. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6984. const iface = document.getElementById('route-modal-iface').value;
  6985. const comment = document.getElementById('route-modal-comment').value.trim();
  6986. const disabled = document.getElementById('route-modal-disabled').checked;
  6987. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6988. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6989. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6990. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6991. if (!dst) {
  6992. showToast('Error', 'Destination address is required', 'error');
  6993. return;
  6994. }
  6995. if (!gw && !iface) {
  6996. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6997. return;
  6998. }
  6999. const payload = {
  7000. id,
  7001. old_dst_address: oldDst,
  7002. old_gateway: oldGw,
  7003. old_routing_table: oldTable,
  7004. old_interface: oldIface,
  7005. dst_address: dst,
  7006. gateway: gw || iface,
  7007. routing_table: table,
  7008. distance,
  7009. interface: iface,
  7010. comment,
  7011. disabled,
  7012. check_gateway,
  7013. check_target,
  7014. check_interval,
  7015. check_threshold
  7016. };
  7017. if (oldDistStr !== undefined && oldDistStr !== '') {
  7018. payload.old_distance = parseInt(oldDistStr, 10);
  7019. }
  7020. try {
  7021. const res = await fetch(`${API_BASE}/routes`, {
  7022. method: 'POST',
  7023. headers: { 'Content-Type': 'application/json' },
  7024. body: JSON.stringify(payload)
  7025. });
  7026. if (res.ok) {
  7027. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7028. closeRouteModal();
  7029. loadRoutes();
  7030. } else {
  7031. const err = await res.json();
  7032. showToast('Error', err.message || 'Failed to save route', 'error');
  7033. }
  7034. } catch (err) {
  7035. showToast('Error', err.message, 'error');
  7036. }
  7037. }
  7038. async function toggleRouteState(id, disabled) {
  7039. try {
  7040. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7041. method: 'POST',
  7042. headers: { 'Content-Type': 'application/json' },
  7043. body: JSON.stringify({ disabled })
  7044. });
  7045. if (res.ok) loadRoutes();
  7046. } catch (err) {
  7047. showToast('Error', err.message, 'error');
  7048. }
  7049. }
  7050. async function deleteRoute(id) {
  7051. if (!confirm('Are you sure you want to delete this route?')) return;
  7052. try {
  7053. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7054. if (res.ok) {
  7055. showToast('Deleted', 'Route removed', 'success');
  7056. loadRoutes();
  7057. }
  7058. } catch (err) {
  7059. showToast('Error', err.message, 'error');
  7060. }
  7061. }
  7062. // ----------------- Policy Rules (/ip route rule) -----------------
  7063. function renderPolicyRules() {
  7064. const tbody = document.getElementById('rules-table-body');
  7065. const empty = document.getElementById('rules-empty');
  7066. if (!tbody) return;
  7067. const showSystem = document.getElementById('prule-show-system')?.checked;
  7068. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7069. const countBadge = document.getElementById('rules-count-badge');
  7070. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7071. const bRules = document.getElementById('routes-badge-rules');
  7072. if (bRules) bRules.innerText = filtered.length;
  7073. if (filtered.length === 0) {
  7074. empty?.classList.remove('hidden');
  7075. tbody.innerHTML = '';
  7076. return;
  7077. }
  7078. empty?.classList.add('hidden');
  7079. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7080. if (tbody.dataset.sig === sig) return;
  7081. tbody.dataset.sig = sig;
  7082. tbody.innerHTML = '';
  7083. filtered.forEach(pr => {
  7084. const isSys = pr.is_default || pr.is_system;
  7085. const tr = document.createElement('tr');
  7086. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7087. tr.innerHTML = `
  7088. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7089. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7090. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7091. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7092. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7093. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7094. <td class="py-2.5 px-3 text-right font-sans">
  7095. ${!pr.is_default ? `
  7096. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7097. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7098. </td>
  7099. `;
  7100. tbody.appendChild(tr);
  7101. });
  7102. }
  7103. function openAddPolicyRuleModal() {
  7104. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7105. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7106. document.getElementById('prule-modal-mark').value = '';
  7107. document.getElementById('prule-modal-src').value = '';
  7108. document.getElementById('prule-modal-dst').value = '';
  7109. const sel = document.getElementById('prule-modal-table');
  7110. sel.innerHTML = '';
  7111. (state.routingTables || []).forEach(t => {
  7112. const opt = document.createElement('option');
  7113. opt.value = t.name;
  7114. opt.innerText = t.name;
  7115. sel.appendChild(opt);
  7116. });
  7117. document.getElementById('prule-modal').classList.remove('hidden');
  7118. }
  7119. function closePolicyRuleModal() {
  7120. document.getElementById('prule-modal').classList.add('hidden');
  7121. }
  7122. async function submitSavePolicyRule(e) {
  7123. e.preventDefault();
  7124. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7125. const mark = document.getElementById('prule-modal-mark').value.trim();
  7126. const src = document.getElementById('prule-modal-src').value.trim();
  7127. const dst = document.getElementById('prule-modal-dst').value.trim();
  7128. const table = document.getElementById('prule-modal-table').value;
  7129. const action = document.getElementById('prule-modal-action').value;
  7130. try {
  7131. const res = await fetch(`${API_BASE}/routing/rules`, {
  7132. method: 'POST',
  7133. headers: { 'Content-Type': 'application/json' },
  7134. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7135. });
  7136. if (res.ok) {
  7137. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7138. closePolicyRuleModal();
  7139. loadRoutes();
  7140. } else {
  7141. const err = await res.json();
  7142. showToast('Error', err.message, 'error');
  7143. }
  7144. } catch (err) {
  7145. showToast('Error', err.message, 'error');
  7146. }
  7147. }
  7148. async function deletePolicyRule(id) {
  7149. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7150. try {
  7151. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7152. if (res.ok) {
  7153. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7154. loadRoutes();
  7155. }
  7156. } catch (err) {
  7157. showToast('Error', err.message, 'error');
  7158. }
  7159. }
  7160. // ----------------- Routing Tables -----------------
  7161. function renderRoutingTables() {
  7162. const tbody = document.getElementById('tables-table-body');
  7163. if (!tbody) return;
  7164. const tables = state.routingTables || [];
  7165. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7166. if (tbody.dataset.sig === sig) return;
  7167. tbody.dataset.sig = sig;
  7168. tbody.innerHTML = '';
  7169. (state.routingTables || []).forEach(t => {
  7170. const tr = document.createElement('tr');
  7171. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7172. tr.innerHTML = `
  7173. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7174. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7175. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7176. `;
  7177. tbody.appendChild(tr);
  7178. });
  7179. }
  7180. function openAddTableModal() {
  7181. document.getElementById('table-modal-name').value = '';
  7182. document.getElementById('table-modal-id').value = '';
  7183. document.getElementById('table-modal-comment').value = '';
  7184. document.getElementById('table-modal').classList.remove('hidden');
  7185. }
  7186. function closeTableModal() {
  7187. document.getElementById('table-modal').classList.add('hidden');
  7188. }
  7189. async function submitSaveTable(e) {
  7190. e.preventDefault();
  7191. const name = document.getElementById('table-modal-name').value.trim();
  7192. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7193. const comment = document.getElementById('table-modal-comment').value.trim();
  7194. try {
  7195. const res = await fetch(`${API_BASE}/routing/tables`, {
  7196. method: 'POST',
  7197. headers: { 'Content-Type': 'application/json' },
  7198. body: JSON.stringify({ name, table_id: id, comment })
  7199. });
  7200. if (res.ok) {
  7201. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7202. closeTableModal();
  7203. loadRoutes();
  7204. } else {
  7205. const err = await res.json();
  7206. showToast('Error', err.message, 'error');
  7207. }
  7208. } catch (err) {
  7209. showToast('Error', err.message, 'error');
  7210. }
  7211. }
  7212. async function loadDebianConfig() {
  7213. const view = document.getElementById('debian-config-view');
  7214. view.innerText = 'Generating live configuration...';
  7215. try {
  7216. const res = await fetch(`${API_BASE}/debian/config`);
  7217. const data = await res.json();
  7218. view.innerText = data.content || '# Empty config';
  7219. } catch (err) {
  7220. view.innerText = 'Failed to generate Debian network config.';
  7221. }
  7222. }
  7223. async function saveDebianConfig() {
  7224. try {
  7225. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7226. const data = await res.json();
  7227. if (res.ok) {
  7228. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7229. loadDebianConfig();
  7230. }
  7231. } catch (err) {
  7232. showToast('Error', err.message, 'error');
  7233. }
  7234. }
  7235. function showToast(title, message, type = 'info') {
  7236. const container = document.getElementById('toast-container');
  7237. const toast = document.createElement('div');
  7238. const borderColors = {
  7239. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7240. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7241. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7242. };
  7243. 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}`;
  7244. toast.innerHTML = `
  7245. <div class="flex-1">
  7246. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7247. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7248. </div>
  7249. `;
  7250. container.appendChild(toast);
  7251. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7252. setTimeout(() => {
  7253. toast.classList.add('opacity-0', 'translate-y-2');
  7254. setTimeout(() => toast.remove(), 300);
  7255. }, 4000);
  7256. }
  7257. function formatTraffic(bytesPerSec) {
  7258. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7259. const kb = bytesPerSec / 1024;
  7260. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7261. const mb = kb / 1024;
  7262. return `${mb.toFixed(2)} MB/s`;
  7263. }
  7264. function toggleSidebar() {
  7265. const sb = document.getElementById('sidebar');
  7266. sb.classList.toggle('-translate-x-full');
  7267. }
  7268. // ======================== EoIP (Ethernet over IP) ========================
  7269. async function loadEoIP(populate = true) {
  7270. try {
  7271. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7272. const data = await res.json();
  7273. state.eoipTunnels = Array.isArray(data) ? data : [];
  7274. const badge = document.getElementById('eoip-count-badge');
  7275. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7276. const sideBadge = document.getElementById('badge-eoip-count');
  7277. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7278. renderEoIPTunnels();
  7279. } catch (err) {
  7280. console.error('Failed to load EoIP:', err);
  7281. }
  7282. }
  7283. function renderEoIPTunnels() {
  7284. const tbody = document.getElementById('eoip-table-body');
  7285. const empty = document.getElementById('eoip-empty');
  7286. if (!tbody) return;
  7287. tbody.innerHTML = '';
  7288. const tunnels = state.eoipTunnels || [];
  7289. if (tunnels.length === 0) {
  7290. empty?.classList.remove('hidden');
  7291. return;
  7292. }
  7293. empty?.classList.add('hidden');
  7294. tunnels.forEach(t => {
  7295. const tr = document.createElement('tr');
  7296. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7297. tr.innerHTML = `
  7298. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7299. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7300. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7301. <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>
  7302. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7303. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7304. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7305. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7306. <td class="py-2.5 px-3 font-mono text-[11px]">
  7307. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7308. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7309. </td>
  7310. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7311. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7312. <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>
  7313. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7314. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7315. </td>
  7316. `;
  7317. tbody.appendChild(tr);
  7318. });
  7319. }
  7320. function openAddEoIPModal() {
  7321. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7322. document.getElementById('eoip-modal-id').value = '';
  7323. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7324. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7325. document.getElementById('eoip-modal-remote').value = '';
  7326. document.getElementById('eoip-modal-ip').value = '';
  7327. document.getElementById('eoip-modal-local').value = '';
  7328. document.getElementById('eoip-modal-mac').value = '';
  7329. document.getElementById('eoip-modal-mtu').value = '1500';
  7330. document.getElementById('eoip-modal-comment').value = '';
  7331. document.getElementById('eoip-modal-clampmss').checked = true;
  7332. document.getElementById('eoip-modal-disabled').checked = false;
  7333. document.getElementById('eoip-modal').classList.remove('hidden');
  7334. }
  7335. function openEditEoIPModal(id) {
  7336. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7337. if (!t) return;
  7338. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7339. document.getElementById('eoip-modal-id').value = t.id;
  7340. document.getElementById('eoip-modal-name').value = t.name;
  7341. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7342. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7343. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7344. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7345. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7346. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7347. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7348. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7349. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7350. document.getElementById('eoip-modal').classList.remove('hidden');
  7351. }
  7352. function closeEoIPModal() {
  7353. document.getElementById('eoip-modal').classList.add('hidden');
  7354. }
  7355. async function submitSaveEoIP(e) {
  7356. e.preventDefault();
  7357. const id = document.getElementById('eoip-modal-id').value;
  7358. const name = document.getElementById('eoip-modal-name').value.trim();
  7359. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7360. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7361. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7362. const local = document.getElementById('eoip-modal-local').value.trim();
  7363. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7364. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7365. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7366. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7367. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7368. try {
  7369. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7370. method: 'POST',
  7371. headers: { 'Content-Type': 'application/json' },
  7372. body: JSON.stringify({
  7373. id,
  7374. name,
  7375. tunnel_id: tunnelId,
  7376. remote_address: remote,
  7377. ip_address: ipAddress,
  7378. local_address: local,
  7379. mac_address: mac,
  7380. mtu,
  7381. clamp_mss: clampMss,
  7382. comment,
  7383. disabled
  7384. })
  7385. });
  7386. if (res.ok) {
  7387. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7388. closeEoIPModal();
  7389. loadEoIP(false);
  7390. fetchData(false);
  7391. } else {
  7392. const err = await res.json();
  7393. showToast('Error', err.message, 'error');
  7394. }
  7395. } catch (err) {
  7396. showToast('Error', err.message, 'error');
  7397. }
  7398. }
  7399. async function toggleEoIPState(id, disabled) {
  7400. try {
  7401. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7402. method: 'POST',
  7403. headers: { 'Content-Type': 'application/json' },
  7404. body: JSON.stringify({ disabled })
  7405. });
  7406. if (res.ok) {
  7407. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7408. loadEoIP(false);
  7409. fetchData(false);
  7410. }
  7411. } catch (err) {
  7412. showToast('Error', err.message, 'error');
  7413. }
  7414. }
  7415. async function deleteEoIP(id) {
  7416. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7417. try {
  7418. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7419. if (res.ok) {
  7420. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7421. loadEoIP(false);
  7422. fetchData(false);
  7423. }
  7424. } catch (err) {
  7425. showToast('Error', err.message, 'error');
  7426. }
  7427. }
  7428. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7429. async function loadVXLAN(populate = true) {
  7430. try {
  7431. const [tunnelsRes, vtepsRes] = await Promise.all([
  7432. fetch(`${API_BASE}/vpn/vxlan`),
  7433. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7434. ]);
  7435. if (tunnelsRes.ok) {
  7436. state.vxlanTunnels = await tunnelsRes.json() || [];
  7437. }
  7438. if (vtepsRes.ok) {
  7439. state.vxlanVteps = await vtepsRes.json() || [];
  7440. }
  7441. renderVXLANTable();
  7442. renderVXLANVtepsTable();
  7443. const countBadge = document.getElementById('vxlan-count-badge');
  7444. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7445. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7446. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7447. const navBadge = document.getElementById('badge-vxlan-count');
  7448. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7449. } catch (err) {
  7450. console.error('Error loading VXLAN:', err);
  7451. }
  7452. }
  7453. function renderVXLANTable() {
  7454. const tbody = document.getElementById('vxlan-table-body');
  7455. const empty = document.getElementById('vxlan-empty');
  7456. if (!tbody || !empty) return;
  7457. tbody.innerHTML = '';
  7458. const tunnels = state.vxlanTunnels || [];
  7459. if (tunnels.length === 0) {
  7460. empty.classList.remove('hidden');
  7461. return;
  7462. }
  7463. empty.classList.add('hidden');
  7464. tunnels.forEach(t => {
  7465. const tr = document.createElement('tr');
  7466. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7467. let flag = '';
  7468. if (t.disabled) {
  7469. 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>';
  7470. } else if (t.running) {
  7471. 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>';
  7472. } else {
  7473. 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>';
  7474. }
  7475. const vtepCount = (t.vteps || []).length;
  7476. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7477. tr.innerHTML = `
  7478. <td class="py-2.5 px-3 text-center">${flag}</td>
  7479. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7480. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7481. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7482. <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>
  7483. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7484. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7485. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7486. <td class="py-2.5 px-3 font-mono">
  7487. <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>
  7488. </td>
  7489. <td class="py-2.5 px-3 font-mono text-[11px]">
  7490. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7491. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7492. </td>
  7493. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7494. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7495. <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>
  7496. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7497. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7498. </td>
  7499. `;
  7500. tbody.appendChild(tr);
  7501. });
  7502. }
  7503. function renderVXLANVtepsTable() {
  7504. const tbody = document.getElementById('vxlan-vteps-table-body');
  7505. const empty = document.getElementById('vxlan-vteps-empty');
  7506. if (!tbody || !empty) return;
  7507. tbody.innerHTML = '';
  7508. const vteps = state.vxlanVteps || [];
  7509. if (vteps.length === 0) {
  7510. empty.classList.remove('hidden');
  7511. return;
  7512. }
  7513. empty.classList.add('hidden');
  7514. vteps.forEach(v => {
  7515. const tr = document.createElement('tr');
  7516. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7517. tr.innerHTML = `
  7518. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7519. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7520. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7521. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7522. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7523. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7524. </td>
  7525. `;
  7526. tbody.appendChild(tr);
  7527. });
  7528. }
  7529. function openAddVXLANModal() {
  7530. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7531. document.getElementById('vxlan-modal-id').value = '';
  7532. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7533. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7534. document.getElementById('vxlan-modal-port').value = '4789';
  7535. document.getElementById('vxlan-modal-ip').value = '';
  7536. document.getElementById('vxlan-modal-parent').value = '';
  7537. document.getElementById('vxlan-modal-local').value = '';
  7538. document.getElementById('vxlan-modal-remote').value = '';
  7539. document.getElementById('vxlan-modal-group').value = '';
  7540. document.getElementById('vxlan-modal-mac').value = '';
  7541. document.getElementById('vxlan-modal-mtu').value = '1500';
  7542. document.getElementById('vxlan-modal-comment').value = '';
  7543. document.getElementById('vxlan-modal-learning').checked = true;
  7544. document.getElementById('vxlan-modal-disabled').checked = false;
  7545. document.getElementById('vxlan-modal').classList.remove('hidden');
  7546. }
  7547. function openEditVXLANModal(id) {
  7548. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7549. if (!t) return;
  7550. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7551. document.getElementById('vxlan-modal-id').value = t.id;
  7552. document.getElementById('vxlan-modal-name').value = t.name;
  7553. document.getElementById('vxlan-modal-vni').value = t.vni;
  7554. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7555. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7556. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7557. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7558. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7559. document.getElementById('vxlan-modal-group').value = t.group || '';
  7560. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7561. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7562. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7563. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7564. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7565. document.getElementById('vxlan-modal').classList.remove('hidden');
  7566. }
  7567. function closeVXLANModal() {
  7568. document.getElementById('vxlan-modal').classList.add('hidden');
  7569. }
  7570. async function submitSaveVXLAN(e) {
  7571. e.preventDefault();
  7572. const id = document.getElementById('vxlan-modal-id').value;
  7573. const name = document.getElementById('vxlan-modal-name').value.trim();
  7574. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7575. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7576. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7577. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7578. const local = document.getElementById('vxlan-modal-local').value.trim();
  7579. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7580. const group = document.getElementById('vxlan-modal-group').value.trim();
  7581. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7582. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7583. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7584. const learning = document.getElementById('vxlan-modal-learning').checked;
  7585. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7586. try {
  7587. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7588. method: 'POST',
  7589. headers: { 'Content-Type': 'application/json' },
  7590. body: JSON.stringify({
  7591. id,
  7592. name,
  7593. vni,
  7594. port,
  7595. ip_address: ipAddress,
  7596. parent_interface: parentInterface,
  7597. local_address: local,
  7598. remote_address: remote,
  7599. group,
  7600. mac_address: mac,
  7601. mtu,
  7602. learning,
  7603. comment,
  7604. disabled
  7605. })
  7606. });
  7607. if (res.ok) {
  7608. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7609. closeVXLANModal();
  7610. loadVXLAN(false);
  7611. fetchData(false);
  7612. } else {
  7613. const err = await res.json();
  7614. showToast('Error', err.message, 'error');
  7615. }
  7616. } catch (err) {
  7617. showToast('Error', err.message, 'error');
  7618. }
  7619. }
  7620. async function toggleVXLANState(id, disabled) {
  7621. try {
  7622. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7623. method: 'POST',
  7624. headers: { 'Content-Type': 'application/json' },
  7625. body: JSON.stringify({ disabled })
  7626. });
  7627. if (res.ok) {
  7628. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7629. loadVXLAN(false);
  7630. fetchData(false);
  7631. }
  7632. } catch (err) {
  7633. showToast('Error', err.message, 'error');
  7634. }
  7635. }
  7636. async function deleteVXLAN(id) {
  7637. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7638. try {
  7639. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7640. if (res.ok) {
  7641. showToast('Deleted', 'VXLAN interface removed', 'success');
  7642. loadVXLAN(false);
  7643. fetchData(false);
  7644. }
  7645. } catch (err) {
  7646. showToast('Error', err.message, 'error');
  7647. }
  7648. }
  7649. function openAddVXLANVtepModal(defaultIface = '') {
  7650. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7651. if (sel) {
  7652. sel.innerHTML = '';
  7653. const tunnels = state.vxlanTunnels || [];
  7654. tunnels.forEach(t => {
  7655. const opt = document.createElement('option');
  7656. opt.value = t.name;
  7657. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7658. if (defaultIface && t.name === defaultIface) {
  7659. opt.selected = true;
  7660. }
  7661. sel.appendChild(opt);
  7662. });
  7663. }
  7664. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7665. document.getElementById('vxlan-vtep-modal-port').value = '';
  7666. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7667. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7668. }
  7669. function closeVXLANVtepModal() {
  7670. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7671. }
  7672. async function submitSaveVXLANVtep(e) {
  7673. e.preventDefault();
  7674. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7675. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7676. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7677. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7678. try {
  7679. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7680. method: 'POST',
  7681. headers: { 'Content-Type': 'application/json' },
  7682. body: JSON.stringify({
  7683. interface: iface,
  7684. remote_ip: remote,
  7685. port,
  7686. comment
  7687. })
  7688. });
  7689. if (res.ok) {
  7690. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7691. closeVXLANVtepModal();
  7692. loadVXLAN(false);
  7693. fetchData(false);
  7694. } else {
  7695. const err = await res.json();
  7696. showToast('Error', err.message, 'error');
  7697. }
  7698. } catch (err) {
  7699. showToast('Error', err.message, 'error');
  7700. }
  7701. }
  7702. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7703. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7704. try {
  7705. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7706. method: 'DELETE'
  7707. });
  7708. if (res.ok) {
  7709. showToast('Deleted', 'Remote VTEP removed', 'success');
  7710. loadVXLAN(false);
  7711. fetchData(false);
  7712. }
  7713. } catch (err) {
  7714. showToast('Error', err.message, 'error');
  7715. }
  7716. }
  7717. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7718. const aeroRateSamples = new Map();
  7719. const aeroLiveRates = new Map();
  7720. async function loadAeroTUN(populate = true) {
  7721. try {
  7722. const [tunnelsRes, statsRes] = await Promise.all([
  7723. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7724. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7725. ]);
  7726. if (tunnelsRes.ok) {
  7727. const data = await tunnelsRes.json();
  7728. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7729. const now = Date.now();
  7730. for (const t of state.aerotunTunnels) {
  7731. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7732. 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) {
  7733. 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});
  7734. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7735. 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});
  7736. }
  7737. }
  7738. if (statsRes.ok) {
  7739. state.aerotunStats = await statsRes.json();
  7740. }
  7741. const countBadge = document.getElementById('aerotun-count-badge');
  7742. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7743. const sideBadge = document.getElementById('badge-aerotun-count');
  7744. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7745. renderAeroTUN();
  7746. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7747. } catch (err) {
  7748. console.error('Failed to load AeroTUN:', err);
  7749. }
  7750. }
  7751. function renderAeroTUN() {
  7752. const tbody = document.getElementById('aerotun-table-body');
  7753. const empty = document.getElementById('aerotun-empty');
  7754. // Update summary cards
  7755. const stats = state.aerotunStats || {};
  7756. const tunnels = state.aerotunTunnels || [];
  7757. const statActive = document.getElementById('aerotun-stat-active');
  7758. if (statActive) {
  7759. const activeCount = tunnels.filter(t => t.connected).length;
  7760. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7761. }
  7762. const statSaved = document.getElementById('aerotun-stat-saved');
  7763. if (statSaved) {
  7764. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7765. }
  7766. const statRatio = document.getElementById('aerotun-stat-ratio');
  7767. if (statRatio) {
  7768. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7769. }
  7770. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7771. if (statTraffic) {
  7772. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7773. }
  7774. if (!tbody) return;
  7775. tbody.innerHTML = '';
  7776. if (tunnels.length === 0) {
  7777. empty?.classList.remove('hidden');
  7778. return;
  7779. }
  7780. empty?.classList.add('hidden');
  7781. tunnels.forEach(t => {
  7782. const tr = document.createElement('tr');
  7783. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7784. const modeBadge = t.mode === 'server'
  7785. ? `<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>`
  7786. : `<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>`;
  7787. const endpointInfo = t.mode === 'server'
  7788. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7789. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7790. const compBadge = t.compression
  7791. ? `<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>`
  7792. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7793. const activePeer = t.connected && t.active_peer_endpoint
  7794. ? `<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>`
  7795. : `<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>`;
  7796. const rawRx = formatBytes(t.rx_bytes || 0);
  7797. const rawTx = formatBytes(t.tx_bytes || 0);
  7798. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7799. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7800. const rate = aeroLiveRates.get(t.id);
  7801. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7802. tr.innerHTML = `
  7803. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7804. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7805. <span>${escapeHtml(t.name)}</span>
  7806. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7807. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7808. </td>
  7809. <td class="py-2.5 px-3">${modeBadge}</td>
  7810. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7811. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7812. <td class="py-2.5 px-3">${compBadge}</td>
  7813. <td class="py-2.5 px-3">${activePeer}</td>
  7814. <td class="py-2.5 px-3 font-mono text-[11px]">
  7815. <span class="text-emerald-400">↓ ${rawRx}</span>
  7816. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7817. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7818. </td>
  7819. <td class="py-2.5 px-3 font-mono text-[11px]">
  7820. <span class="text-slate-400">↓ ${wireRx}</span>
  7821. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7822. </td>
  7823. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7824. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7825. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7826. ${t.running
  7827. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7828. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7829. }
  7830. <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>
  7831. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7832. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7833. </td>
  7834. `;
  7835. tbody.appendChild(tr);
  7836. });
  7837. }
  7838. async function openAeroTUNHealth(encodedID) {
  7839. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7840. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7841. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7842. document.getElementById('aerotun-compare-host').value=underlay;
  7843. document.getElementById('aerotun-compare-result').textContent='';
  7844. document.getElementById('aerotun-health-result').textContent = '';
  7845. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7846. await refreshAeroTUNHealth();
  7847. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7848. }
  7849. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7850. async function refreshAeroTUNHealth() {
  7851. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7852. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7853. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7854. try {
  7855. 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;
  7856. 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);
  7857. const d=t.drop_breakdown;
  7858. 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}`:''}`;
  7859. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7860. if(!events.length){node.textContent='No events recorded yet.';return}
  7861. 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)}
  7862. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7863. }
  7864. async function runAeroTUNHealthCheck() {
  7865. 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…';
  7866. 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()}
  7867. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7868. finally {button.disabled=false}
  7869. }
  7870. let aeroCompareRunning=false, aeroCompareCancel=false;
  7871. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7872. async function runAeroTUNComparison() {
  7873. if(aeroCompareRunning)return;
  7874. 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();
  7875. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7876. 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}
  7877. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7878. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7879. 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()};
  7880. const results=[];
  7881. try {
  7882. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7883. if(aeroCompareCancel)break;
  7884. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7885. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7886. 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;
  7887. 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}}
  7888. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7889. 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.`);
  7890. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7891. }
  7892. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7893. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7894. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7895. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7896. }
  7897. let aeroModalGeneration = 0;
  7898. let aeroIdentityDraft = '';
  7899. let aeroSaving = false;
  7900. let aeroPSKRequest = 0;
  7901. function discardAeroIdentityDraft(id) {
  7902. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7903. }
  7904. async function generateAeroTUNIdentity() {
  7905. const generation = aeroModalGeneration;
  7906. const retry = document.getElementById('aerotun-retry-identity');
  7907. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7908. retry.classList.add('hidden');
  7909. document.getElementById('aerotun-modal-public').value = '';
  7910. try {
  7911. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7912. if (!res.ok) throw new Error(await responseError(res));
  7913. const draft = await res.json();
  7914. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7915. aeroIdentityDraft = draft.draft_id;
  7916. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7917. updateAeroTUNSetupHint();
  7918. } catch (err) {
  7919. if (generation !== aeroModalGeneration) return;
  7920. retry.classList.remove('hidden');
  7921. updateAeroTUNSetupHint();
  7922. showToast('Identity Generation Failed', err.message, 'error');
  7923. }
  7924. }
  7925. function onAeroTUNModeChange() {
  7926. const mode = document.getElementById('aerotun-modal-mode').value;
  7927. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7928. const portInput = document.getElementById('aerotun-modal-port');
  7929. if (mode === 'server') {
  7930. if (!portInput.value) portInput.value = '51830';
  7931. endpointInput.placeholder = 'Optional / learned roaming peer';
  7932. } else {
  7933. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7934. if (!portInput.value) portInput.value = '';
  7935. }
  7936. }
  7937. function onAeroTUNPeerChange() {
  7938. const peer = document.getElementById('aerotun-modal-peer');
  7939. const allowed = document.getElementById('aerotun-modal-allowed');
  7940. const previous = peer.dataset.allowedDefault || '';
  7941. const host = peer.value.trim().split('/')[0];
  7942. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7943. if (allowed.value.trim() === previous) allowed.value = next;
  7944. peer.dataset.allowedDefault = next;
  7945. }
  7946. async function generateAeroTUNKey(automatic = false) {
  7947. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7948. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7949. try {
  7950. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7951. if (!res.ok) throw new Error(await responseError(res));
  7952. const data = await res.json();
  7953. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7954. input.value = data.key;
  7955. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7956. } catch (err) {
  7957. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7958. }
  7959. }
  7960. function updateAeroTUNSetupHint() {
  7961. const version = document.getElementById('aerotun-modal-protocol').value;
  7962. const key = document.getElementById('aerotun-modal-public').value;
  7963. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7964. const hint = document.getElementById('aerotun-setup-hint');
  7965. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7966. if (!hint) return;
  7967. 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.';
  7968. }
  7969. async function copyAeroTUNPublicKey() {
  7970. const input = document.getElementById('aerotun-modal-public');
  7971. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7972. try {
  7973. await navigator.clipboard.writeText(input.value);
  7974. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7975. } catch {
  7976. input.focus(); input.select();
  7977. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7978. }
  7979. }
  7980. async function copyAeroTUNPSK() {
  7981. const input = document.getElementById('aerotun-modal-psk');
  7982. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7983. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7984. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7985. }
  7986. function openAddAeroTUNModal() {
  7987. if (aeroSaving) return;
  7988. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7989. const tunnels = state.aerotunTunnels || [];
  7990. const usedNames = new Set(tunnels.map(t => t.name));
  7991. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7992. 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++;
  7993. if (index >= 256) index = 0;
  7994. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7995. document.getElementById('aerotun-modal-id').value = '';
  7996. document.getElementById('aerotun-modal-protocol').value='3';
  7997. document.getElementById('aerotun-modal-public').value='';
  7998. document.getElementById('aerotun-modal-peerkey').value='';
  7999. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  8000. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  8001. document.getElementById('aerotun-modal-mode').value = 'server';
  8002. document.getElementById('aerotun-modal-port').value = 51830 + index;
  8003. document.getElementById('aerotun-modal-endpoint').value = '';
  8004. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  8005. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  8006. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  8007. document.getElementById('aerotun-modal-psk').value = '';
  8008. document.getElementById('aerotun-modal-mtu').value = '1420';
  8009. document.getElementById('aerotun-modal-comment').value = '';
  8010. document.getElementById('aerotun-modal-compression').checked = false;
  8011. document.getElementById('aerotun-modal-defroute').checked = false;
  8012. document.getElementById('aerotun-modal-disabled').checked = true;
  8013. document.getElementById('aerotun-modal-psk').type = 'password';
  8014. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8015. onAeroTUNModeChange();
  8016. updateAeroTUNSetupHint();
  8017. document.getElementById('aerotun-modal').classList.remove('hidden');
  8018. generateAeroTUNKey(true);
  8019. generateAeroTUNIdentity();
  8020. }
  8021. function openEditAeroTUNModal(id) {
  8022. if (aeroSaving) return;
  8023. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8024. if (!t) return;
  8025. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8026. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8027. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8028. document.getElementById('aerotun-modal-id').value = t.id;
  8029. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8030. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8031. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8032. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8033. document.getElementById('aerotun-modal-name').value = t.name;
  8034. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8035. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8036. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8037. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8038. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8039. const peerHost = (t.peer_address || '').split('/')[0];
  8040. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8041. document.getElementById('aerotun-modal-psk').value = '';
  8042. document.getElementById('aerotun-modal-psk').type = 'password';
  8043. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8044. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8045. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8046. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8047. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8048. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8049. onAeroTUNModeChange();
  8050. updateAeroTUNSetupHint();
  8051. document.getElementById('aerotun-modal').classList.remove('hidden');
  8052. }
  8053. function closeAeroTUNModal() {
  8054. if (aeroSaving) return;
  8055. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8056. document.getElementById('aerotun-modal-psk').value = '';
  8057. document.getElementById('aerotun-modal').classList.add('hidden');
  8058. }
  8059. async function submitSaveAeroTUN(e) {
  8060. e.preventDefault();
  8061. if (aeroSaving) return;
  8062. const id = document.getElementById('aerotun-modal-id').value;
  8063. const name = document.getElementById('aerotun-modal-name').value.trim();
  8064. const mode = document.getElementById('aerotun-modal-mode').value;
  8065. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8066. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8067. const local = document.getElementById('aerotun-modal-local').value.trim();
  8068. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8069. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8070. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8071. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8072. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8073. const compression = document.getElementById('aerotun-modal-compression').checked;
  8074. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8075. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8076. if (mode === 'client' && !endpoint) {
  8077. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8078. return;
  8079. }
  8080. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8081. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8082. return;
  8083. }
  8084. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8085. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8086. return;
  8087. }
  8088. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8089. if (version === 3 && !id && !aeroIdentityDraft) {
  8090. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8091. return;
  8092. }
  8093. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8094. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8095. document.getElementById('aerotun-modal-allowed').focus();
  8096. return;
  8097. }
  8098. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8099. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8100. return;
  8101. }
  8102. if (!psk && !id) {
  8103. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8104. return;
  8105. }
  8106. aeroSaving = true;
  8107. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8108. if (submit) submit.disabled = true;
  8109. try {
  8110. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8111. method: 'POST',
  8112. headers: { 'Content-Type': 'application/json' },
  8113. body: JSON.stringify({
  8114. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8115. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8116. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8117. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8118. id,
  8119. name,
  8120. mode,
  8121. listen_port: port,
  8122. remote_endpoint: endpoint,
  8123. local_address: local,
  8124. peer_address: peer,
  8125. psk,
  8126. mtu,
  8127. compression,
  8128. default_route: defaultRoute,
  8129. comment,
  8130. disabled
  8131. })
  8132. });
  8133. if (res.ok) {
  8134. await res.json();
  8135. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8136. aeroIdentityDraft = '';
  8137. aeroSaving = false;
  8138. closeAeroTUNModal();
  8139. await loadAeroTUN(false);
  8140. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8141. fetchData(false);
  8142. } else {
  8143. const err = await responseError(res);
  8144. if (err.includes('configuration saved but tunnel failed to start')) {
  8145. aeroIdentityDraft = '';
  8146. aeroSaving = false;
  8147. closeAeroTUNModal();
  8148. await loadAeroTUN(false);
  8149. showToast('Saved, but not started', err, 'error');
  8150. } else showToast('Error Saving Tunnel', err, 'error');
  8151. }
  8152. } catch (err) {
  8153. showToast('Network Error', err.message, 'error');
  8154. } finally {
  8155. aeroSaving = false;
  8156. if (submit) submit.disabled = false;
  8157. }
  8158. }
  8159. async function startAeroTUNTunnel(id) {
  8160. try {
  8161. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8162. if (res.ok) {
  8163. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8164. loadAeroTUN(false);
  8165. fetchData(false);
  8166. } else {
  8167. const err = await res.text();
  8168. showToast('Failed to Start', err, 'error');
  8169. }
  8170. } catch (err) {
  8171. showToast('Error', err.message, 'error');
  8172. }
  8173. }
  8174. async function stopAeroTUNTunnel(id) {
  8175. try {
  8176. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8177. if (res.ok) {
  8178. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8179. loadAeroTUN(false);
  8180. fetchData(false);
  8181. } else {
  8182. const err = await res.text();
  8183. showToast('Failed to Stop', err, 'error');
  8184. }
  8185. } catch (err) {
  8186. showToast('Error', err.message, 'error');
  8187. }
  8188. }
  8189. async function toggleAeroTUNState(id, disabled) {
  8190. try {
  8191. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8192. method: 'POST',
  8193. headers: { 'Content-Type': 'application/json' },
  8194. body: JSON.stringify({ disabled })
  8195. });
  8196. if (res.ok) {
  8197. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8198. loadAeroTUN(false);
  8199. fetchData(false);
  8200. }
  8201. } catch (err) {
  8202. showToast('Error', err.message, 'error');
  8203. }
  8204. }
  8205. async function deleteAeroTUN(id) {
  8206. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8207. try {
  8208. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8209. if (res.ok) {
  8210. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8211. loadAeroTUN(false);
  8212. fetchData(false);
  8213. }
  8214. } catch (err) {
  8215. showToast('Error', err.message, 'error');
  8216. }
  8217. }
  8218. // ======================== PPP Central Hub & Servers ========================
  8219. function switchPPPSubTab(tab) {
  8220. state.pppSubTab = tab;
  8221. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8222. tabs.forEach(t => {
  8223. const panel = document.getElementById(`ppp-subtab-${t}`);
  8224. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8225. if (panel) {
  8226. if (t === tab) panel.classList.remove('hidden');
  8227. else panel.classList.add('hidden');
  8228. }
  8229. if (btn) {
  8230. if (t === tab) {
  8231. 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';
  8232. } else {
  8233. 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';
  8234. }
  8235. }
  8236. });
  8237. const addBtn = document.getElementById('ppp-primary-add-btn');
  8238. if (addBtn) {
  8239. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8240. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8241. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8242. else addBtn.innerHTML = '<span>Save Config</span>';
  8243. }
  8244. if (tab === 'active') loadPPPSessions();
  8245. }
  8246. function openCurrentPPPModal() {
  8247. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8248. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8249. else if (state.pppSubTab === 'active') loadPPPSessions();
  8250. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8251. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8252. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8253. }
  8254. async function loadPPP(populateDropdowns = true) {
  8255. await Promise.all([
  8256. loadPPPSecrets(),
  8257. loadPPPProfiles(),
  8258. loadPPPServers(),
  8259. loadPPPSessions()
  8260. ]);
  8261. }
  8262. async function loadPPPSecrets() {
  8263. try {
  8264. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8265. const data = await res.json();
  8266. state.pppSecrets = Array.isArray(data) ? data : [];
  8267. const b = document.getElementById('ppp-badge-secrets');
  8268. if (b) b.innerText = state.pppSecrets.length;
  8269. const b2 = document.getElementById('secrets-count-badge');
  8270. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8271. renderPPPSecrets();
  8272. } catch (err) {
  8273. console.error('Failed to load PPP secrets:', err);
  8274. }
  8275. }
  8276. function renderPPPSecrets() {
  8277. const tbody = document.getElementById('secrets-table-body');
  8278. const empty = document.getElementById('secrets-empty');
  8279. if (!tbody) return;
  8280. tbody.innerHTML = '';
  8281. const secrets = state.pppSecrets || [];
  8282. if (secrets.length === 0) {
  8283. empty?.classList.remove('hidden');
  8284. return;
  8285. }
  8286. empty?.classList.add('hidden');
  8287. secrets.forEach(s => {
  8288. const tr = document.createElement('tr');
  8289. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8290. tr.innerHTML = `
  8291. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8292. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8293. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8294. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8295. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8296. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8297. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8298. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8299. <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>
  8300. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8301. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8302. </td>
  8303. `;
  8304. tbody.appendChild(tr);
  8305. });
  8306. }
  8307. async function loadPPPProfiles() {
  8308. try {
  8309. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8310. const data = await res.json();
  8311. state.pppProfiles = Array.isArray(data) ? data : [];
  8312. const b = document.getElementById('ppp-badge-profiles');
  8313. if (b) b.innerText = state.pppProfiles.length;
  8314. const b2 = document.getElementById('profiles-count-badge');
  8315. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8316. // Populate profile selects across modals
  8317. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8318. selects.forEach(sid => {
  8319. const el = document.getElementById(sid);
  8320. if (!el) return;
  8321. const cur = el.value;
  8322. el.innerHTML = '';
  8323. state.pppProfiles.forEach(p => {
  8324. const opt = document.createElement('option');
  8325. opt.value = p.name;
  8326. opt.innerText = `${p.name} (${p.remote_address})`;
  8327. if (p.name === cur) opt.selected = true;
  8328. el.appendChild(opt);
  8329. });
  8330. });
  8331. renderPPPProfiles();
  8332. } catch (err) {
  8333. console.error('Failed to load PPP profiles:', err);
  8334. }
  8335. }
  8336. function renderPPPProfiles() {
  8337. const tbody = document.getElementById('profiles-table-body');
  8338. if (!tbody) return;
  8339. tbody.innerHTML = '';
  8340. (state.pppProfiles || []).forEach(p => {
  8341. const isDefault = p.name.startsWith('default');
  8342. const tr = document.createElement('tr');
  8343. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8344. tr.innerHTML = `
  8345. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8346. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8347. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8348. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8349. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8350. <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>
  8351. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8352. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8353. ${!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>`}
  8354. </td>
  8355. `;
  8356. tbody.appendChild(tr);
  8357. });
  8358. }
  8359. async function loadPPPServers() {
  8360. try {
  8361. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8362. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8363. fetch(`${API_BASE}/vpn/servers/pptp`),
  8364. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8365. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8366. ]);
  8367. if (pppoeRes.ok) {
  8368. state.pppoeServer = await pppoeRes.json();
  8369. const s = state.pppoeServer;
  8370. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8371. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8372. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8373. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8374. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8375. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8376. const pill = document.getElementById('pppoe-server-status-pill');
  8377. if (pill) {
  8378. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8379. 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';
  8380. }
  8381. setDotBadge('ppp-badge-pppoe-state', s.running);
  8382. }
  8383. if (pptpRes.ok) {
  8384. state.pptpServer = await pptpRes.json();
  8385. const s = state.pptpServer;
  8386. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8387. document.getElementById('pptp-server-port').value = s.port || 1723;
  8388. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8389. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8390. const pill = document.getElementById('pptp-server-status-pill');
  8391. if (pill) {
  8392. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8393. 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';
  8394. }
  8395. setDotBadge('ppp-badge-pptp-state', s.running);
  8396. }
  8397. if (l2tpRes.ok) {
  8398. state.l2tpServer = await l2tpRes.json();
  8399. const s = state.l2tpServer;
  8400. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8401. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8402. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8403. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8404. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8405. const pill = document.getElementById('l2tp-server-status-pill');
  8406. if (pill) {
  8407. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8408. 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';
  8409. }
  8410. setDotBadge('ppp-badge-l2tp-state', s.running);
  8411. }
  8412. if (ipsecRes.ok) {
  8413. state.ipsecServer = await ipsecRes.json();
  8414. const s = state.ipsecServer;
  8415. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8416. if (modalEn) modalEn.checked = !!s.enabled;
  8417. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8418. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8419. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8420. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8421. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8422. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8423. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8424. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8425. const pill = document.getElementById('modal-ipsec-server-status');
  8426. if (pill) {
  8427. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8428. 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';
  8429. }
  8430. }
  8431. } catch (err) {
  8432. console.error('Failed to load VPN servers:', err);
  8433. }
  8434. }
  8435. async function loadPPPSessions() {
  8436. try {
  8437. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8438. const data = await res.json();
  8439. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8440. const b = document.getElementById('ppp-badge-active');
  8441. if (b) b.innerText = state.pppActiveSessions.length;
  8442. const sideB = document.getElementById('badge-ppp-sessions');
  8443. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8444. renderPPPSessions();
  8445. } catch (err) {
  8446. console.error('Failed to load active PPP sessions:', err);
  8447. }
  8448. }
  8449. function renderPPPSessions() {
  8450. const tbody = document.getElementById('active-ppp-table-body');
  8451. const empty = document.getElementById('active-ppp-empty');
  8452. if (!tbody) return;
  8453. tbody.innerHTML = '';
  8454. const list = state.pppActiveSessions || [];
  8455. if (list.length === 0) {
  8456. empty?.classList.remove('hidden');
  8457. return;
  8458. }
  8459. empty?.classList.add('hidden');
  8460. list.forEach(s => {
  8461. const tr = document.createElement('tr');
  8462. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8463. tr.innerHTML = `
  8464. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8465. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8466. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8467. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8468. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8469. <td class="py-2.5 px-3 text-[11px]">
  8470. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8471. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8472. </td>
  8473. <td class="py-2.5 px-3 text-right font-sans">
  8474. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8475. </td>
  8476. `;
  8477. tbody.appendChild(tr);
  8478. });
  8479. }
  8480. async function disconnectPPPSession(iface) {
  8481. if (!confirm(`Disconnect session ${iface}?`)) return;
  8482. try {
  8483. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8484. if (res.ok) {
  8485. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8486. loadPPPSessions();
  8487. }
  8488. } catch (err) {
  8489. showToast('Error', err.message, 'error');
  8490. }
  8491. }
  8492. // PPP Secret Modal handlers
  8493. function openAddPPPSecretModal() {
  8494. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8495. document.getElementById('secret-modal-id').value = '';
  8496. document.getElementById('secret-modal-name').value = '';
  8497. document.getElementById('secret-modal-password').value = '';
  8498. document.getElementById('secret-modal-service').value = 'any';
  8499. document.getElementById('secret-modal-profile').value = 'default';
  8500. document.getElementById('secret-modal-local').value = '';
  8501. document.getElementById('secret-modal-remote').value = '';
  8502. document.getElementById('secret-modal-comment').value = '';
  8503. document.getElementById('secret-modal-disabled').checked = false;
  8504. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8505. }
  8506. function openEditPPPSecretModal(id) {
  8507. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8508. if (!s) return;
  8509. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8510. document.getElementById('secret-modal-id').value = s.id;
  8511. document.getElementById('secret-modal-name').value = s.name;
  8512. document.getElementById('secret-modal-password').value = s.password;
  8513. document.getElementById('secret-modal-service').value = s.service || 'any';
  8514. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8515. document.getElementById('secret-modal-local').value = s.local_address || '';
  8516. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8517. document.getElementById('secret-modal-comment').value = s.comment || '';
  8518. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8519. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8520. }
  8521. function closePPPSecretModal() {
  8522. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8523. }
  8524. async function submitSavePPPSecret(e) {
  8525. e.preventDefault();
  8526. const id = document.getElementById('secret-modal-id').value;
  8527. const name = document.getElementById('secret-modal-name').value.trim();
  8528. const password = document.getElementById('secret-modal-password').value.trim();
  8529. const service = document.getElementById('secret-modal-service').value;
  8530. const profile = document.getElementById('secret-modal-profile').value;
  8531. const local = document.getElementById('secret-modal-local').value.trim();
  8532. const remote = document.getElementById('secret-modal-remote').value.trim();
  8533. const comment = document.getElementById('secret-modal-comment').value.trim();
  8534. const disabled = document.getElementById('secret-modal-disabled').checked;
  8535. try {
  8536. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8537. method: 'POST',
  8538. headers: { 'Content-Type': 'application/json' },
  8539. body: JSON.stringify({
  8540. id,
  8541. name,
  8542. password,
  8543. service,
  8544. profile,
  8545. local_address: local,
  8546. remote_address: remote,
  8547. comment,
  8548. disabled
  8549. })
  8550. });
  8551. if (res.ok) {
  8552. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8553. closePPPSecretModal();
  8554. loadPPPSecrets();
  8555. } else {
  8556. const err = await res.json();
  8557. showToast('Error', err.message, 'error');
  8558. }
  8559. } catch (err) {
  8560. showToast('Error', err.message, 'error');
  8561. }
  8562. }
  8563. async function togglePPPSecretState(id, disabled) {
  8564. try {
  8565. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8566. method: 'POST',
  8567. headers: { 'Content-Type': 'application/json' },
  8568. body: JSON.stringify({ disabled })
  8569. });
  8570. if (res.ok) {
  8571. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8572. loadPPPSecrets();
  8573. }
  8574. } catch (err) {
  8575. showToast('Error', err.message, 'error');
  8576. }
  8577. }
  8578. async function deletePPPSecret(id) {
  8579. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8580. try {
  8581. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8582. if (res.ok) {
  8583. showToast('Deleted', 'Secret account removed', 'success');
  8584. loadPPPSecrets();
  8585. }
  8586. } catch (err) {
  8587. showToast('Error', err.message, 'error');
  8588. }
  8589. }
  8590. // PPP Profile Modal handlers
  8591. function openAddPPPProfileModal() {
  8592. document.getElementById('profile-modal-name').value = '';
  8593. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8594. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8595. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8596. document.getElementById('profile-modal-encryption').value = 'required';
  8597. document.getElementById('profile-modal-onlyone').checked = true;
  8598. document.getElementById('profile-modal-comment').value = '';
  8599. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8600. }
  8601. function closePPPProfileModal() {
  8602. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8603. }
  8604. async function submitSavePPPProfile(e) {
  8605. e.preventDefault();
  8606. const name = document.getElementById('profile-modal-name').value.trim();
  8607. const local = document.getElementById('profile-modal-local').value.trim();
  8608. const remote = document.getElementById('profile-modal-remote').value.trim();
  8609. const dns = document.getElementById('profile-modal-dns').value.trim();
  8610. const enc = document.getElementById('profile-modal-encryption').value;
  8611. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8612. const comment = document.getElementById('profile-modal-comment').value.trim();
  8613. try {
  8614. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8615. method: 'POST',
  8616. headers: { 'Content-Type': 'application/json' },
  8617. body: JSON.stringify({
  8618. id: name,
  8619. name,
  8620. local_address: local,
  8621. remote_address: remote,
  8622. dns_servers: dns,
  8623. use_encryption: enc,
  8624. only_one: onlyone,
  8625. comment
  8626. })
  8627. });
  8628. if (res.ok) {
  8629. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8630. closePPPProfileModal();
  8631. loadPPPProfiles();
  8632. } else {
  8633. const err = await res.json();
  8634. showToast('Error', err.message, 'error');
  8635. }
  8636. } catch (err) {
  8637. showToast('Error', err.message, 'error');
  8638. }
  8639. }
  8640. async function deletePPPProfile(name) {
  8641. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8642. try {
  8643. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8644. if (res.ok) {
  8645. showToast('Deleted', 'Profile removed', 'success');
  8646. loadPPPProfiles();
  8647. } else {
  8648. const err = await res.json();
  8649. showToast('Error', err.message, 'error');
  8650. }
  8651. } catch (err) {
  8652. showToast('Error', err.message, 'error');
  8653. }
  8654. }
  8655. // Server Config submissions
  8656. async function savePPPoEServerConfig(e) {
  8657. e.preventDefault();
  8658. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8659. const name = document.getElementById('pppoe-server-name').value.trim();
  8660. const iface = document.getElementById('pppoe-server-iface').value;
  8661. const profile = document.getElementById('pppoe-server-profile').value;
  8662. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8663. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8664. try {
  8665. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8666. method: 'POST',
  8667. headers: { 'Content-Type': 'application/json' },
  8668. body: JSON.stringify({
  8669. enabled,
  8670. service_name: name,
  8671. interface: iface,
  8672. default_profile: profile,
  8673. max_mtu: mtu,
  8674. max_mru: mtu,
  8675. one_session_per_host: onesession
  8676. })
  8677. });
  8678. if (res.ok) {
  8679. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8680. loadPPPServers();
  8681. fetchData(false);
  8682. } else {
  8683. const err = await res.json();
  8684. showToast('Error', err.message, 'error');
  8685. }
  8686. } catch (err) {
  8687. showToast('Error', err.message, 'error');
  8688. }
  8689. }
  8690. async function savePPTPServerConfig(e) {
  8691. e.preventDefault();
  8692. const enabled = document.getElementById('pptp-server-enabled').checked;
  8693. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8694. const profile = document.getElementById('pptp-server-profile').value;
  8695. const mppe = document.getElementById('pptp-server-mppe').checked;
  8696. try {
  8697. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8698. method: 'POST',
  8699. headers: { 'Content-Type': 'application/json' },
  8700. body: JSON.stringify({
  8701. enabled,
  8702. port,
  8703. default_profile: profile,
  8704. require_mppe: mppe
  8705. })
  8706. });
  8707. if (res.ok) {
  8708. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8709. loadPPPServers();
  8710. fetchData(false);
  8711. } else {
  8712. const err = await res.json();
  8713. showToast('Error', err.message, 'error');
  8714. }
  8715. } catch (err) {
  8716. showToast('Error', err.message, 'error');
  8717. }
  8718. }
  8719. async function saveL2TPServerConfig(e) {
  8720. e.preventDefault();
  8721. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8722. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8723. const profile = document.getElementById('l2tp-server-profile').value;
  8724. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8725. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8726. try {
  8727. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8728. method: 'POST',
  8729. headers: { 'Content-Type': 'application/json' },
  8730. body: JSON.stringify({
  8731. enabled,
  8732. port,
  8733. default_profile: profile,
  8734. use_ipsec: useipsec,
  8735. ipsec_secret: psk
  8736. })
  8737. });
  8738. if (res.ok) {
  8739. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8740. loadPPPServers();
  8741. fetchData(false);
  8742. } else {
  8743. const err = await res.json();
  8744. showToast('Error', err.message, 'error');
  8745. }
  8746. } catch (err) {
  8747. showToast('Error', err.message, 'error');
  8748. }
  8749. }
  8750. // IPSec Server Modal
  8751. function openIPSecServerModal() {
  8752. loadPPPServers();
  8753. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8754. }
  8755. function closeIPSecServerModal() {
  8756. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8757. }
  8758. async function submitSaveIPSecServer(e) {
  8759. e.preventDefault();
  8760. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8761. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8762. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8763. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8764. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8765. try {
  8766. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8767. method: 'POST',
  8768. headers: { 'Content-Type': 'application/json' },
  8769. body: JSON.stringify({
  8770. enabled,
  8771. preshared_key: psk,
  8772. pool_address: pool,
  8773. dns_servers: dns,
  8774. local_subnet: subnet
  8775. })
  8776. });
  8777. if (res.ok) {
  8778. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8779. closeIPSecServerModal();
  8780. loadPPPServers();
  8781. fetchData(false);
  8782. } else {
  8783. const err = await res.json();
  8784. showToast('Error', err.message, 'error');
  8785. }
  8786. } catch (err) {
  8787. showToast('Error', err.message, 'error');
  8788. }
  8789. }
  8790. // WireGuard Client Config Viewer
  8791. let currentWGClientConf = '';
  8792. async function openWGClientConfModal(iface, clientIP) {
  8793. try {
  8794. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8795. method: 'POST',
  8796. headers: { 'Content-Type': 'application/json' },
  8797. body: JSON.stringify({
  8798. interface: iface,
  8799. address: clientIP || '10.10.0.2/32',
  8800. dns: '1.1.1.1, 8.8.8.8'
  8801. })
  8802. });
  8803. if (res.ok) {
  8804. const data = await res.json();
  8805. currentWGClientConf = data.config;
  8806. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8807. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8808. } else {
  8809. const err = await res.json();
  8810. showToast('Error', err.message, 'error');
  8811. }
  8812. } catch (err) {
  8813. showToast('Error', err.message, 'error');
  8814. }
  8815. }
  8816. function closeWGClientConfModal() {
  8817. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8818. }
  8819. function copyWGClientConf() {
  8820. if (!currentWGClientConf) return;
  8821. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8822. }
  8823. function downloadWGClientConf() {
  8824. if (!currentWGClientConf) return;
  8825. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8826. const a = document.createElement('a');
  8827. a.href = URL.createObjectURL(blob);
  8828. a.download = 'wireguard-client.conf';
  8829. document.body.appendChild(a);
  8830. a.click();
  8831. document.body.removeChild(a);
  8832. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8833. }
  8834. // =========================================================================
  8835. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8836. // =========================================================================
  8837. state.activeDynSubTab = 'bgp-peers';
  8838. state.activeBgpSubTab = 'bgp-peers';
  8839. state.activeOspfTab = 'instances';
  8840. state.bgpInstance = null;
  8841. state.bgpPeers = [];
  8842. state.bgpNets = [];
  8843. state.bgpRoutes = [];
  8844. state.ospfInstance = null;
  8845. state.ospfInstances = [];
  8846. state.ospfAreas = [];
  8847. state.ospfAreaRanges = [];
  8848. state.ospfTemplates = [];
  8849. state.ospfLiveInterfaces = [];
  8850. state.ospfStaticNbrs = [];
  8851. state.ospfNeighbors = [];
  8852. state.ospfLSA = [];
  8853. state.ospfRoutes = [];
  8854. state.selectedOspfRow = {
  8855. instances: null,
  8856. areas: null,
  8857. 'area-ranges': null,
  8858. templates: null,
  8859. interfaces: null,
  8860. 'static-nbrs': null,
  8861. neighbors: null,
  8862. lsa: null,
  8863. };
  8864. state.ospfSort = {
  8865. instances: { col: 'name', asc: true },
  8866. areas: { col: 'name', asc: true },
  8867. ranges: { col: 'area', asc: true },
  8868. templates: { col: 'interfaces', asc: true },
  8869. live_ifaces: { col: 'interface', asc: true },
  8870. snbrs: { col: 'address', asc: true },
  8871. neighbors: { col: 'address', asc: true },
  8872. lsa: { col: 'instance', asc: true },
  8873. };
  8874. function switchBgpSubTab(subTab) {
  8875. state.activeBgpSubTab = subTab;
  8876. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8877. tabs.forEach(t => {
  8878. const el = document.getElementById(`dyn-subtab-${t}`);
  8879. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8880. if (el) el.classList.toggle('hidden', t !== subTab);
  8881. if (btn) {
  8882. if (t === subTab) {
  8883. 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';
  8884. } else {
  8885. 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';
  8886. }
  8887. }
  8888. });
  8889. }
  8890. function switchOspfTab(tabName) {
  8891. state.activeOspfTab = tabName;
  8892. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8893. tabs.forEach(t => {
  8894. const pane = document.getElementById(`ospf-pane-${t}`);
  8895. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8896. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8897. if (btn) {
  8898. if (t === tabName) {
  8899. 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';
  8900. } else {
  8901. 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';
  8902. }
  8903. }
  8904. });
  8905. }
  8906. function switchOspfSubTab(tab) {
  8907. // Legacy alias
  8908. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8909. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8910. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8911. else switchOspfTab('instances');
  8912. }
  8913. function switchDynSubTab(subTab) {
  8914. if (subTab.startsWith('bgp')) {
  8915. if (state.activeTab !== 'bgp') navigate('bgp');
  8916. switchBgpSubTab(subTab);
  8917. } else if (subTab.startsWith('ospf')) {
  8918. if (state.activeTab !== 'ospf') navigate('ospf');
  8919. switchOspfTab('instances');
  8920. }
  8921. }
  8922. async function loadDynamicRouting(showToastMsg = false) {
  8923. try {
  8924. const fetchSafeJson = async (url) => {
  8925. try {
  8926. const r = await fetch(url);
  8927. return r.ok ? await r.json() : null;
  8928. } catch (e) {
  8929. return null;
  8930. }
  8931. };
  8932. const [
  8933. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8934. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8935. commLists, asLists,
  8936. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  8937. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  8938. babelInsts, babelIfaces, babelLiveIfaces, babelNbrs, babelRoutes,
  8939. radvInsts, radvIfaces,
  8940. eigrpInsts, eigrpIfaces, eigrpNets, eigrpNbrs, eigrpTopology
  8941. ] = await Promise.all([
  8942. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8943. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8944. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8945. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8946. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8947. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8948. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8949. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8950. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8951. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8952. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8953. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8954. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8955. fetchSafeJson(`${API_BASE}/routing/filters`),
  8956. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8957. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`),
  8958. fetchSafeJson(`${API_BASE}/routing/rip/instances`),
  8959. fetchSafeJson(`${API_BASE}/routing/rip/interfaces`),
  8960. fetchSafeJson(`${API_BASE}/routing/rip/neighbors-live`),
  8961. fetchSafeJson(`${API_BASE}/routing/rip/routes`),
  8962. fetchSafeJson(`${API_BASE}/routing/bfd/instance`),
  8963. fetchSafeJson(`${API_BASE}/routing/bfd/interfaces`),
  8964. fetchSafeJson(`${API_BASE}/routing/bfd/peers`),
  8965. fetchSafeJson(`${API_BASE}/routing/bfd/sessions`),
  8966. fetchSafeJson(`${API_BASE}/routing/babel/instances`),
  8967. fetchSafeJson(`${API_BASE}/routing/babel/interfaces`),
  8968. fetchSafeJson(`${API_BASE}/routing/babel/interfaces-live`),
  8969. fetchSafeJson(`${API_BASE}/routing/babel/neighbors`),
  8970. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  8971. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  8972. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`),
  8973. fetchSafeJson(`${API_BASE}/routing/eigrp/instances`),
  8974. fetchSafeJson(`${API_BASE}/routing/eigrp/interfaces`),
  8975. fetchSafeJson(`${API_BASE}/routing/eigrp/networks`),
  8976. fetchSafeJson(`${API_BASE}/routing/eigrp/neighbors`),
  8977. fetchSafeJson(`${API_BASE}/routing/eigrp/topology`)
  8978. ]);
  8979. if (sum) state.dynSummary = sum;
  8980. if (bgpInst) state.bgpInstance = bgpInst;
  8981. if (bgpPeers) state.bgpPeers = bgpPeers;
  8982. if (bgpNets) state.bgpNets = bgpNets;
  8983. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8984. if (ospfInsts) state.ospfInstances = ospfInsts;
  8985. if (ospfAreas) state.ospfAreas = ospfAreas;
  8986. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8987. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8988. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8989. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8990. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8991. if (ospfLsa) state.ospfLSA = ospfLsa;
  8992. if (filters) state.routingFilters = filters;
  8993. if (commLists) state.routingCommunityLists = commLists;
  8994. if (asLists) state.routingASLists = asLists;
  8995. if (ripInsts) state.ripInstances = ripInsts;
  8996. if (ripIfaces) state.ripInterfaces = ripIfaces;
  8997. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  8998. if (ripRoutes) state.ripRoutes = ripRoutes;
  8999. if (bfdInst) state.bfdInstance = bfdInst;
  9000. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  9001. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  9002. if (bfdSessions) state.bfdSessions = bfdSessions;
  9003. if (babelInsts) state.babelInstances = babelInsts;
  9004. if (babelIfaces) state.babelInterfaces = babelIfaces;
  9005. if (babelLiveIfaces) state.babelInterfacesLive = babelLiveIfaces;
  9006. if (babelNbrs) state.babelNeighbors = babelNbrs;
  9007. if (babelRoutes) state.babelRoutes = babelRoutes;
  9008. if (radvInsts) state.radvInstances = radvInsts;
  9009. if (radvIfaces) state.radvInterfaces = radvIfaces;
  9010. if (eigrpInsts) state.eigrpInstances = eigrpInsts;
  9011. if (eigrpIfaces) state.eigrpInterfaces = eigrpIfaces;
  9012. if (eigrpNets) state.eigrpNetworks = eigrpNets;
  9013. if (eigrpNbrs) state.eigrpNeighbors = eigrpNbrs;
  9014. if (eigrpTopology) state.eigrpTopology = eigrpTopology;
  9015. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  9016. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  9017. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  9018. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  9019. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  9020. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  9021. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  9022. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  9023. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  9024. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9025. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9026. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9027. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9028. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9029. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9030. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9031. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9032. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9033. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9034. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9035. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9036. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9037. try { renderBabelLiveInterfaces(); } catch(e) { console.error('renderBabelLiveInterfaces error:', e); }
  9038. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9039. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9040. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9041. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9042. try { renderEigrpInstances(); } catch(e) { console.error('renderEigrpInstances error:', e); }
  9043. try { renderEigrpNetworks(); } catch(e) { console.error('renderEigrpNetworks error:', e); }
  9044. try { renderEigrpInterfaces(); } catch(e) { console.error('renderEigrpInterfaces error:', e); }
  9045. try { renderEigrpNeighbors(); } catch(e) { console.error('renderEigrpNeighbors error:', e); }
  9046. try { renderEigrpTopology(); } catch(e) { console.error('renderEigrpTopology error:', e); }
  9047. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9048. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9049. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9050. } catch (err) {
  9051. console.error('Failed to load dynamic routing:', err);
  9052. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9053. }
  9054. }
  9055. async function loadOspfAll() {
  9056. await loadDynamicRouting(true);
  9057. }
  9058. function renderBgpStatusPill() {
  9059. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9060. pills.forEach(pill => {
  9061. const inst = state.bgpInstance;
  9062. if (!inst || !inst.enabled) {
  9063. 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';
  9064. pill.innerText = 'BGP DISABLED';
  9065. } else if (inst.running) {
  9066. 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';
  9067. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9068. } else {
  9069. 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';
  9070. pill.innerText = 'BGP STARTING...';
  9071. }
  9072. });
  9073. }
  9074. function renderBgpPeers() {
  9075. const tbody = document.getElementById('bgp-peers-table-body');
  9076. if (!tbody) return;
  9077. const empty = document.getElementById('bgp-peers-empty');
  9078. const countBadge = document.getElementById('bgp-peers-count-badge');
  9079. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9080. const peers = state.bgpPeers || [];
  9081. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9082. if (navBadge) navBadge.innerText = peers.length;
  9083. if (peers.length === 0) {
  9084. tbody.innerHTML = '';
  9085. if (empty) empty.classList.remove('hidden');
  9086. return;
  9087. }
  9088. if (empty) empty.classList.add('hidden');
  9089. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9090. if (tbody.dataset.sig === sig) return;
  9091. tbody.dataset.sig = sig;
  9092. tbody.innerHTML = peers.map(p => {
  9093. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9094. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9095. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9096. let stateBadge = '';
  9097. if (p.disabled) {
  9098. 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>';
  9099. } else if (p.state === 'Established') {
  9100. 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>';
  9101. } else if (p.state === 'Connect' || p.state === 'Active') {
  9102. 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>`;
  9103. } else {
  9104. 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>`;
  9105. }
  9106. return `
  9107. <tr class="hover:bg-slate-800/40 transition">
  9108. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9109. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9110. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9111. <td class="py-2.5 px-3">
  9112. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9113. ${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>`}
  9114. </td>
  9115. <td class="py-2.5 px-3">${stateBadge}</td>
  9116. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9117. <td class="py-2.5 px-3 text-slate-300">
  9118. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9119. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9120. </td>
  9121. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9122. ${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> ` : ''}
  9123. ${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>` : ''}
  9124. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9125. </td>
  9126. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9127. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9128. <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'}">
  9129. ${p.disabled ? 'Enable' : 'Disable'}
  9130. </button>
  9131. <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">
  9132. Edit
  9133. </button>
  9134. <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">
  9135. Delete
  9136. </button>
  9137. </td>
  9138. </tr>
  9139. `;
  9140. }).join('');
  9141. }
  9142. function renderBgpNetworks() {
  9143. const tbody = document.getElementById('bgp-nets-table-body');
  9144. if (!tbody) return;
  9145. const empty = document.getElementById('bgp-nets-empty');
  9146. const countBadge = document.getElementById('bgp-nets-count-badge');
  9147. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9148. const nets = state.bgpNets || [];
  9149. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9150. if (navBadge) navBadge.innerText = nets.length;
  9151. if (nets.length === 0) {
  9152. tbody.innerHTML = '';
  9153. if (empty) empty.classList.remove('hidden');
  9154. return;
  9155. }
  9156. if (empty) empty.classList.add('hidden');
  9157. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9158. if (tbody.dataset.sig === sig) return;
  9159. tbody.dataset.sig = sig;
  9160. tbody.innerHTML = nets.map(n => `
  9161. <tr class="hover:bg-slate-800/40 transition">
  9162. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9163. <td class="py-2.5 px-3">
  9164. ${n.disabled
  9165. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9166. : '<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>'}
  9167. </td>
  9168. <td class="py-2.5 px-3">
  9169. ${n.disabled
  9170. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9171. : '<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>'}
  9172. </td>
  9173. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9174. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9175. <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">
  9176. Delete
  9177. </button>
  9178. </td>
  9179. </tr>
  9180. `).join('');
  9181. }
  9182. function renderBgpRoutes() {
  9183. const tbody = document.getElementById('bgp-routes-table-body');
  9184. if (!tbody) return;
  9185. const empty = document.getElementById('bgp-routes-empty');
  9186. const countBadge = document.getElementById('bgp-routes-count-badge');
  9187. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9188. const routes = state.bgpRoutes || [];
  9189. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9190. if (navBadge) navBadge.innerText = routes.length;
  9191. if (routes.length === 0) {
  9192. tbody.innerHTML = '';
  9193. if (empty) empty.classList.remove('hidden');
  9194. return;
  9195. }
  9196. if (empty) empty.classList.add('hidden');
  9197. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9198. if (tbody.dataset.sig === sig) return;
  9199. tbody.dataset.sig = sig;
  9200. tbody.innerHTML = routes.map(r => `
  9201. <tr class="hover:bg-slate-800/40 transition">
  9202. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9203. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9204. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9205. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9206. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9207. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9208. </tr>
  9209. `).join('');
  9210. }
  9211. // =========================================================================
  9212. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9213. // =========================================================================
  9214. function sortOspfTable(tab, col) {
  9215. if (!state.ospfSort) state.ospfSort = {};
  9216. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9217. if (state.ospfSort[tab].col === col) {
  9218. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9219. } else {
  9220. state.ospfSort[tab].col = col;
  9221. state.ospfSort[tab].asc = true;
  9222. }
  9223. const asc = state.ospfSort[tab].asc;
  9224. let list = [];
  9225. if (tab === 'instances') list = state.ospfInstances || [];
  9226. else if (tab === 'areas') list = state.ospfAreas || [];
  9227. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9228. else if (tab === 'templates') list = state.ospfTemplates || [];
  9229. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9230. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9231. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9232. else if (tab === 'lsa') list = state.ospfLSA || [];
  9233. list.sort((a, b) => {
  9234. let valA = a[col] ?? '';
  9235. let valB = b[col] ?? '';
  9236. if (typeof valA === 'number' && typeof valB === 'number') {
  9237. return asc ? valA - valB : valB - valA;
  9238. }
  9239. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9240. });
  9241. if (tab === 'instances') renderOspfInstances();
  9242. else if (tab === 'areas') renderOspfAreas();
  9243. else if (tab === 'ranges') renderOspfAreaRanges();
  9244. else if (tab === 'templates') renderOspfTemplates();
  9245. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9246. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9247. else if (tab === 'neighbors') renderOspfNeighbors();
  9248. else if (tab === 'lsa') renderOspfLSA();
  9249. }
  9250. function selectOspfRow(tab, id) {
  9251. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9252. state.selectedOspfRow[tab] = id;
  9253. if (tab === 'instances') {
  9254. renderOspfInstances();
  9255. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9256. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9257. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9258. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9259. if (btnEn) btnEn.disabled = false;
  9260. if (btnDis) btnDis.disabled = false;
  9261. if (btnRem) btnRem.disabled = false;
  9262. if (btnCom) btnCom.disabled = false;
  9263. } else if (tab === 'areas') {
  9264. renderOspfAreas();
  9265. const btnEn = document.getElementById('btn-ospf-area-enable');
  9266. const btnDis = document.getElementById('btn-ospf-area-disable');
  9267. const btnRem = document.getElementById('btn-ospf-area-remove');
  9268. const btnCom = document.getElementById('btn-ospf-area-comment');
  9269. if (btnEn) btnEn.disabled = false;
  9270. if (btnDis) btnDis.disabled = false;
  9271. if (btnRem) btnRem.disabled = false;
  9272. if (btnCom) btnCom.disabled = false;
  9273. } else if (tab === 'ranges') {
  9274. renderOspfAreaRanges();
  9275. const btnEn = document.getElementById('btn-ospf-range-enable');
  9276. const btnDis = document.getElementById('btn-ospf-range-disable');
  9277. const btnRem = document.getElementById('btn-ospf-range-remove');
  9278. const btnCom = document.getElementById('btn-ospf-range-comment');
  9279. if (btnEn) btnEn.disabled = false;
  9280. if (btnDis) btnDis.disabled = false;
  9281. if (btnRem) btnRem.disabled = false;
  9282. if (btnCom) btnCom.disabled = false;
  9283. } else if (tab === 'templates') {
  9284. renderOspfTemplates();
  9285. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9286. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9287. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9288. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9289. if (btnEn) btnEn.disabled = false;
  9290. if (btnDis) btnDis.disabled = false;
  9291. if (btnRem) btnRem.disabled = false;
  9292. if (btnCom) btnCom.disabled = false;
  9293. } else if (tab === 'snbrs') {
  9294. renderOspfStaticNbrs();
  9295. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9296. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9297. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9298. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9299. if (btnEn) btnEn.disabled = false;
  9300. if (btnDis) btnDis.disabled = false;
  9301. if (btnRem) btnRem.disabled = false;
  9302. if (btnCom) btnCom.disabled = false;
  9303. }
  9304. }
  9305. // TAB 1: INSTANCES
  9306. function renderOspfInstances() {
  9307. const tbody = document.getElementById('ospf-instances-table-body');
  9308. if (!tbody) return;
  9309. const countEl = document.getElementById('ospf-instances-footer-count');
  9310. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9311. let list = state.ospfInstances || [];
  9312. if (filter) {
  9313. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9314. }
  9315. if (countEl) countEl.innerText = list.length;
  9316. const selId = state.selectedOspfRow?.instances;
  9317. tbody.innerHTML = list.map((inst, idx) => {
  9318. const isSel = inst.id === selId;
  9319. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9320. const flagD = inst.disabled
  9321. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  9322. : (inst.running
  9323. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  9324. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  9325. const redist = [];
  9326. if (inst.redistribute_connected) redist.push('conn');
  9327. if (inst.redistribute_static) redist.push('static');
  9328. if (inst.redistribute_bgp) redist.push('bgp');
  9329. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9330. redist.push('default');
  9331. }
  9332. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9333. const origBadge = origDef === 'always'
  9334. ? '<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>'
  9335. : (origDef === 'if-installed'
  9336. ? '<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>'
  9337. : '<span class="text-slate-500 text-[10px]">never</span>');
  9338. return `
  9339. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9340. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9341. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  9342. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9343. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9344. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9345. </td>
  9346. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9347. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9348. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9349. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9350. <td class="py-1.5 px-3">${origBadge}</td>
  9351. </tr>
  9352. `;
  9353. }).join('');
  9354. }
  9355. // TAB 2: AREAS
  9356. function renderOspfAreas() {
  9357. const tbody = document.getElementById('ospf-areas-table-body');
  9358. if (!tbody) return;
  9359. const countEl = document.getElementById('ospf-areas-footer-count');
  9360. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9361. let list = state.ospfAreas || [];
  9362. if (filter) {
  9363. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9364. }
  9365. if (countEl) countEl.innerText = list.length;
  9366. const selId = state.selectedOspfRow?.areas;
  9367. tbody.innerHTML = list.map((a, idx) => {
  9368. const isSel = a.id === selId;
  9369. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9370. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9371. return `
  9372. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9373. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9374. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9375. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9376. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9377. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9378. </td>
  9379. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9380. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9381. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9382. </tr>
  9383. `;
  9384. }).join('');
  9385. }
  9386. // TAB 3: AREA RANGES
  9387. function renderOspfAreaRanges() {
  9388. const tbody = document.getElementById('ospf-ranges-table-body');
  9389. if (!tbody) return;
  9390. const countEl = document.getElementById('ospf-ranges-footer-count');
  9391. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9392. let list = state.ospfAreaRanges || [];
  9393. if (filter) {
  9394. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9395. }
  9396. if (countEl) countEl.innerText = list.length;
  9397. const selId = state.selectedOspfRow?.['area-ranges'];
  9398. tbody.innerHTML = list.map((r, idx) => {
  9399. const isSel = r.id === selId;
  9400. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9401. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9402. return `
  9403. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9404. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9405. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9406. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9407. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9408. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9409. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9410. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9411. </tr>
  9412. `;
  9413. }).join('');
  9414. }
  9415. // TAB 4: INTERFACE TEMPLATES
  9416. function renderOspfTemplates() {
  9417. const tbody = document.getElementById('ospf-templates-table-body');
  9418. if (!tbody) return;
  9419. const countEl = document.getElementById('ospf-templates-footer-count');
  9420. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9421. let list = state.ospfTemplates || [];
  9422. if (filter) {
  9423. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9424. }
  9425. if (countEl) countEl.innerText = list.length;
  9426. const selId = state.selectedOspfRow?.templates;
  9427. tbody.innerHTML = list.map((t, idx) => {
  9428. const isSel = t.id === selId;
  9429. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9430. const ifaces = t.interfaces || t.interface || 'all';
  9431. const nets = t.networks || t.network || '';
  9432. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9433. return `
  9434. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9435. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9436. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9437. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9438. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9439. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9440. </td>
  9441. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9442. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9443. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9444. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9445. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9446. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9447. </tr>
  9448. `;
  9449. }).join('');
  9450. }
  9451. // TAB 5: LIVE INTERFACES
  9452. function renderOspfLiveInterfaces() {
  9453. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9454. if (!tbody) return;
  9455. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9456. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9457. let list = state.ospfLiveInterfaces || [];
  9458. if (filter) {
  9459. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9460. }
  9461. if (countEl) countEl.innerText = list.length;
  9462. tbody.innerHTML = list.map(i => `
  9463. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9464. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9465. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9466. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9467. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9468. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9469. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9470. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9471. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9472. </tr>
  9473. `).join('');
  9474. }
  9475. // TAB 6: STATIC NEIGHBORS
  9476. function renderOspfStaticNbrs() {
  9477. const tbody = document.getElementById('ospf-snbrs-table-body');
  9478. if (!tbody) return;
  9479. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9480. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9481. let list = state.ospfStaticNbrs || [];
  9482. if (filter) {
  9483. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9484. }
  9485. if (countEl) countEl.innerText = list.length;
  9486. const selId = state.selectedOspfRow?.['static-nbrs'];
  9487. tbody.innerHTML = list.map((n, idx) => {
  9488. const isSel = n.id === selId;
  9489. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9490. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9491. return `
  9492. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9493. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9494. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9495. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9496. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9497. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9498. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9499. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9500. </tr>
  9501. `;
  9502. }).join('');
  9503. }
  9504. // TAB 7: LIVE NEIGHBORS
  9505. function renderOspfNeighbors() {
  9506. const tbody = document.getElementById('ospf-neighbors-table-body');
  9507. if (!tbody) return;
  9508. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9509. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9510. let list = state.ospfNeighbors || [];
  9511. if (filter) {
  9512. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9513. }
  9514. if (countEl) countEl.innerText = list.length;
  9515. tbody.innerHTML = list.map(n => `
  9516. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9517. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9518. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9519. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9520. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9521. </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 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9524. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9525. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9526. </tr>
  9527. `).join('');
  9528. }
  9529. // TAB 8: LINK-STATE DATABASE (LSA)
  9530. function renderOspfLSA() {
  9531. const tbody = document.getElementById('ospf-lsa-table-body');
  9532. if (!tbody) return;
  9533. const countEl = document.getElementById('ospf-lsa-footer-count');
  9534. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9535. let list = state.ospfLSA || [];
  9536. if (filter) {
  9537. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9538. }
  9539. if (countEl) countEl.innerText = list.length;
  9540. tbody.innerHTML = list.map(l => `
  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(l.flags || 'D')}</td>
  9543. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9544. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9545. </td>
  9546. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9547. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9548. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9549. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9550. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9551. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9552. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9553. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9554. </tr>
  9555. `).join('');
  9556. }
  9557. function renderOspfStatusPill() {
  9558. // Maintained for backward compatibility
  9559. const pill = document.getElementById('ospf-live-status-pill');
  9560. if (!pill) return;
  9561. 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';
  9562. pill.innerText = 'OSPF ACTIVE';
  9563. }
  9564. function renderOspfInterfaces() {
  9565. renderOspfTemplates();
  9566. }
  9567. function renderOspfRoutes() {
  9568. // Routes retained in background
  9569. }
  9570. // BGP Modals & Actions
  9571. function openBgpInstanceModal() {
  9572. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9573. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9574. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9575. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9576. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9577. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9578. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9579. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9580. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9581. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9582. }
  9583. function closeBgpInstanceModal() {
  9584. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9585. }
  9586. async function submitBgpInstance(e) {
  9587. e.preventDefault();
  9588. const payload = {
  9589. enabled: document.getElementById('modal-bgp-enabled').checked,
  9590. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9591. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9592. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9593. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9594. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9595. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9596. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9597. };
  9598. try {
  9599. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9600. method: 'POST',
  9601. headers: { 'Content-Type': 'application/json' },
  9602. body: JSON.stringify(payload)
  9603. });
  9604. if (res.ok) {
  9605. closeBgpInstanceModal();
  9606. showToast('Success', 'BGP instance configuration updated', 'success');
  9607. loadDynamicRouting();
  9608. } else {
  9609. const err = await res.json();
  9610. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9611. }
  9612. } catch (err) {
  9613. showToast('Error', err.message, 'error');
  9614. }
  9615. }
  9616. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9617. function switchBgpPeerModalTab(tab) {
  9618. // Normalize legacy tab names
  9619. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9620. if (tab === 'attributes') tab = 'networks';
  9621. const tabs = ['general', 'filters', 'networks'];
  9622. tabs.forEach(t => {
  9623. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9624. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9625. if (t === tab) {
  9626. if (pane) pane.classList.remove('hidden');
  9627. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9628. } else {
  9629. if (pane) pane.classList.add('hidden');
  9630. 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';
  9631. }
  9632. });
  9633. }
  9634. function addOutputNetworkRow(val = '') {
  9635. const container = document.getElementById('modal-bgp-output-networks-container');
  9636. if (!container) return;
  9637. const row = document.createElement('div');
  9638. row.className = 'flex items-center gap-2 output-net-row';
  9639. row.innerHTML = `
  9640. <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">
  9641. <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>
  9642. `;
  9643. container.appendChild(row);
  9644. }
  9645. function parseBgpTime(val) {
  9646. if (!val) return 0;
  9647. val = String(val).trim();
  9648. if (val.includes(':')) {
  9649. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9650. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9651. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9652. }
  9653. return parseInt(val, 10) || 0;
  9654. }
  9655. function formatBgpTime(secs) {
  9656. if (!secs || secs <= 0) return '30';
  9657. return String(secs);
  9658. }
  9659. function populateBgpRoutingTables() {
  9660. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9661. if (!sel) return;
  9662. const cur = sel.value || 'main';
  9663. sel.innerHTML = '<option value="main">main</option>';
  9664. (state.routingTables || []).forEach(t => {
  9665. if (t.name !== 'main') {
  9666. const opt = document.createElement('option');
  9667. opt.value = t.name;
  9668. opt.innerText = t.name;
  9669. sel.appendChild(opt);
  9670. }
  9671. });
  9672. sel.value = cur;
  9673. }
  9674. function populateBgpLocalAddrDatalist() {
  9675. const dlBgp = document.getElementById('bgp-peer-local-addr-datalist');
  9676. if (!dlBgp) return;
  9677. const addrs = [];
  9678. (state.interfaces || []).forEach(iface => {
  9679. if (iface.ip) addrs.push(iface.ip.split('/')[0]);
  9680. (iface.addresses || []).forEach(a => addrs.push(a.split('/')[0]));
  9681. });
  9682. dlBgp.innerHTML = Array.from(new Set(addrs.filter(Boolean))).map(ip => `<option value="${escapeHtml(ip)}">`).join('');
  9683. }
  9684. function openAddBgpPeerModal() {
  9685. document.getElementById('bgp-peer-form').reset();
  9686. document.getElementById('modal-bgp-peer-id').value = '';
  9687. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9688. populateBgpLocalAddrDatalist();
  9689. // General Tab
  9690. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9691. document.getElementById('modal-bgp-peer-name').value = '';
  9692. document.getElementById('modal-bgp-peer-comment').value = '';
  9693. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9694. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9695. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9696. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9697. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9698. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9699. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9700. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9701. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9702. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9703. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9704. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9705. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9706. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9707. // Filters Tab
  9708. populateFilterChainsDatalist();
  9709. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9710. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9711. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9712. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9713. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9714. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9715. // Advertised Networks Tab
  9716. const container = document.getElementById('modal-bgp-output-networks-container');
  9717. if (container) {
  9718. container.innerHTML = '';
  9719. addOutputNetworkRow('');
  9720. }
  9721. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9722. if (removeBtn) removeBtn.classList.add('hidden');
  9723. switchBgpPeerModalTab('general');
  9724. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9725. }
  9726. function populateFilterChainsDatalist() {
  9727. const dl = document.getElementById('filter-chains-list');
  9728. if (!dl) return;
  9729. const chains = new Set();
  9730. (state.routingFilters || []).forEach(f => {
  9731. if (f.chain) chains.add(f.chain);
  9732. });
  9733. if (chains.size === 0) {
  9734. chains.add('awmn');
  9735. chains.add('Internal');
  9736. chains.add('bgp-in');
  9737. chains.add('bgp-out');
  9738. }
  9739. dl.innerHTML = '';
  9740. chains.forEach(c => {
  9741. const opt = document.createElement('option');
  9742. opt.value = c;
  9743. dl.appendChild(opt);
  9744. });
  9745. }
  9746. function openEditBgpPeerModal(id) {
  9747. const p = (state.bgpPeers || []).find(item => item.id === id);
  9748. if (!p) return;
  9749. populateFilterChainsDatalist();
  9750. populateBgpLocalAddrDatalist();
  9751. document.getElementById('modal-bgp-peer-id').value = p.id;
  9752. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9753. // General Tab
  9754. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9755. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9756. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9757. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9758. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9759. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9760. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9761. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9762. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9763. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9764. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9765. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9766. // Passive mode
  9767. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9768. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9769. // Next-hop self
  9770. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9771. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9772. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9773. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9774. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9775. // Filters Tab
  9776. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9777. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9778. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9779. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9780. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9781. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9782. // Advertised Networks Tab
  9783. const container = document.getElementById('modal-bgp-output-networks-container');
  9784. if (container) {
  9785. container.innerHTML = '';
  9786. if (p.output_networks && p.output_networks.length > 0) {
  9787. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9788. } else {
  9789. addOutputNetworkRow('');
  9790. }
  9791. }
  9792. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9793. if (removeBtn) removeBtn.classList.remove('hidden');
  9794. switchBgpPeerModalTab('general');
  9795. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9796. }
  9797. function copyCurrentBgpPeer() {
  9798. document.getElementById('modal-bgp-peer-id').value = '';
  9799. const nameEl = document.getElementById('modal-bgp-peer-name');
  9800. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9801. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9802. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9803. if (removeBtn) removeBtn.classList.add('hidden');
  9804. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9805. }
  9806. function removeCurrentBgpPeer() {
  9807. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9808. if (!id) return;
  9809. deleteBgpPeer(id);
  9810. closeBgpPeerModal();
  9811. }
  9812. function closeBgpPeerModal() {
  9813. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9814. }
  9815. function getBgpPeerFormData() {
  9816. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9817. const outputNetworks = [];
  9818. netInputs.forEach(inp => {
  9819. const v = inp.value.trim();
  9820. if (v) outputNetworks.push(v);
  9821. });
  9822. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9823. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9824. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9825. const useBfd = document.getElementById('modal-bgp-peer-use-bfd')?.checked || false;
  9826. return {
  9827. id: document.getElementById('modal-bgp-peer-id').value,
  9828. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9829. enabled: enabled,
  9830. disabled: !enabled,
  9831. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9832. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9833. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9834. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9835. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9836. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9837. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9838. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9839. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9840. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9841. use_bfd: useBfd,
  9842. passive: isPassive,
  9843. connect: !isPassive,
  9844. listen: true,
  9845. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9846. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9847. nexthop_self: isNexthopSelf,
  9848. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9849. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9850. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9851. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9852. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9853. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9854. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9855. output_networks: outputNetworks
  9856. };
  9857. }
  9858. async function submitBgpPeer(e) {
  9859. if (e) e.preventDefault();
  9860. const payload = getBgpPeerFormData();
  9861. try {
  9862. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9863. method: 'POST',
  9864. headers: { 'Content-Type': 'application/json' },
  9865. body: JSON.stringify(payload)
  9866. });
  9867. if (res.ok) {
  9868. closeBgpPeerModal();
  9869. showToast('Success', 'BGP Connection saved', 'success');
  9870. loadDynamicRouting();
  9871. } else {
  9872. const err = await res.json();
  9873. showToast('Error', err.error || 'Failed to save peer', 'error');
  9874. }
  9875. } catch (err) {
  9876. showToast('Error', err.message, 'error');
  9877. }
  9878. }
  9879. async function applyBgpPeerModal(e) {
  9880. if (e) e.preventDefault();
  9881. const payload = getBgpPeerFormData();
  9882. try {
  9883. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9884. method: 'POST',
  9885. headers: { 'Content-Type': 'application/json' },
  9886. body: JSON.stringify(payload)
  9887. });
  9888. if (res.ok) {
  9889. const data = await res.json();
  9890. if (data.peer && data.peer.id) {
  9891. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9892. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9893. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9894. }
  9895. showToast('Applied', 'BGP Connection applied', 'success');
  9896. loadDynamicRouting();
  9897. } else {
  9898. const err = await res.json();
  9899. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9900. }
  9901. } catch (err) {
  9902. showToast('Error', err.message, 'error');
  9903. }
  9904. }
  9905. async function deleteBgpPeer(id) {
  9906. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9907. try {
  9908. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9909. if (res.ok) {
  9910. showToast('Deleted', 'BGP peer removed', 'success');
  9911. loadDynamicRouting();
  9912. }
  9913. } catch (err) {
  9914. showToast('Error', err.message, 'error');
  9915. }
  9916. }
  9917. async function toggleBgpPeerState(id, disabled) {
  9918. try {
  9919. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9920. method: 'POST',
  9921. headers: { 'Content-Type': 'application/json' },
  9922. body: JSON.stringify({ disabled })
  9923. });
  9924. if (res.ok) {
  9925. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9926. loadDynamicRouting();
  9927. }
  9928. } catch (err) {
  9929. showToast('Error', err.message, 'error');
  9930. }
  9931. }
  9932. function openAddBgpNetworkModal() {
  9933. document.getElementById('bgp-network-form').reset();
  9934. document.getElementById('modal-bgp-net-id').value = '';
  9935. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9936. }
  9937. function closeBgpNetworkModal() {
  9938. document.getElementById('bgp-network-modal').classList.add('hidden');
  9939. }
  9940. async function submitBgpNetwork(e) {
  9941. e.preventDefault();
  9942. const payload = {
  9943. id: document.getElementById('modal-bgp-net-id').value,
  9944. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9945. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9946. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9947. };
  9948. try {
  9949. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9950. method: 'POST',
  9951. headers: { 'Content-Type': 'application/json' },
  9952. body: JSON.stringify(payload)
  9953. });
  9954. if (res.ok) {
  9955. closeBgpNetworkModal();
  9956. showToast('Success', 'BGP network advertisement saved', 'success');
  9957. loadDynamicRouting();
  9958. } else {
  9959. const err = await res.json();
  9960. showToast('Error', err.error || 'Failed to save network', 'error');
  9961. }
  9962. } catch (err) {
  9963. showToast('Error', err.message, 'error');
  9964. }
  9965. }
  9966. async function deleteBgpNetwork(id) {
  9967. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9968. try {
  9969. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9970. if (res.ok) {
  9971. showToast('Deleted', 'Network advertisement removed', 'success');
  9972. loadDynamicRouting();
  9973. }
  9974. } catch (err) {
  9975. showToast('Error', err.message, 'error');
  9976. }
  9977. }
  9978. // =========================================================================
  9979. // DEBTIK v7 OSPF MODALS & ACTIONS
  9980. // =========================================================================
  9981. // --- 1. OSPF INSTANCE ---
  9982. function openOspfInstanceModal(id = null) {
  9983. const isEdit = !!id;
  9984. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9985. id: '',
  9986. name: 'Default',
  9987. version: 2,
  9988. vrf: 'main',
  9989. router_id: '192.168.131.56',
  9990. routing_table: 'main',
  9991. enabled: true,
  9992. redistribute_connected: false,
  9993. redistribute_static: true,
  9994. redistribute_bgp: false,
  9995. comment: ''
  9996. };
  9997. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9998. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9999. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  10000. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  10001. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  10002. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  10003. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  10004. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  10005. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  10006. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  10007. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  10008. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  10009. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  10010. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  10011. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  10012. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  10013. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  10014. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  10015. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10016. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  10017. }
  10018. function toggleOspfDefaultModeUI() {
  10019. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  10020. const select = document.getElementById('modal-ospf-inst-originate-default');
  10021. if (!select) return;
  10022. if (isChecked) {
  10023. if (select.value === 'never') select.value = 'if-installed';
  10024. } else {
  10025. select.value = 'never';
  10026. }
  10027. }
  10028. function onOspfOriginateDefaultChange() {
  10029. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  10030. const chk = document.getElementById('modal-ospf-inst-redist-default');
  10031. if (chk) chk.checked = val !== 'never';
  10032. }
  10033. function openEditOspfInstanceModal(id) {
  10034. openOspfInstanceModal(id);
  10035. }
  10036. function closeOspfInstanceModal() {
  10037. document.getElementById('ospf-instance-modal').classList.add('hidden');
  10038. }
  10039. async function submitOspfInstance(e) {
  10040. if (e) e.preventDefault();
  10041. const payload = {
  10042. id: document.getElementById('modal-ospf-inst-id').value,
  10043. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  10044. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  10045. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  10046. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  10047. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10048. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10049. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10050. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10051. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10052. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10053. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10054. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10055. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10056. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0
  10057. };
  10058. try {
  10059. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10060. method: 'POST',
  10061. headers: { 'Content-Type': 'application/json' },
  10062. body: JSON.stringify(payload)
  10063. });
  10064. if (res.ok) {
  10065. closeOspfInstanceModal();
  10066. showToast('Saved', 'OSPF instance updated', 'success');
  10067. loadDynamicRouting();
  10068. } else {
  10069. const err = await res.json();
  10070. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10071. }
  10072. } catch (err) {
  10073. showToast('Error', err.message, 'error');
  10074. }
  10075. }
  10076. function applyOspfInstanceForm() {
  10077. submitOspfInstance(null);
  10078. }
  10079. function copyOspfInstance() {
  10080. document.getElementById('modal-ospf-inst-id').value = '';
  10081. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10082. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10083. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10084. }
  10085. async function deleteCurrentOspfInstance() {
  10086. const id = document.getElementById('modal-ospf-inst-id').value;
  10087. if (!id) return;
  10088. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10089. try {
  10090. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10091. if (res.ok) {
  10092. closeOspfInstanceModal();
  10093. showToast('Removed', 'OSPF instance deleted', 'success');
  10094. loadDynamicRouting();
  10095. }
  10096. } catch (err) {
  10097. showToast('Error', err.message, 'error');
  10098. }
  10099. }
  10100. async function enableSelectedOspfInstance() {
  10101. const id = state.selectedOspfRow?.instances;
  10102. if (!id) return;
  10103. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10104. method: 'POST',
  10105. headers: { 'Content-Type': 'application/json' },
  10106. body: JSON.stringify({ disabled: false })
  10107. });
  10108. loadDynamicRouting();
  10109. }
  10110. async function disableSelectedOspfInstance() {
  10111. const id = state.selectedOspfRow?.instances;
  10112. if (!id) return;
  10113. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10114. method: 'POST',
  10115. headers: { 'Content-Type': 'application/json' },
  10116. body: JSON.stringify({ disabled: true })
  10117. });
  10118. loadDynamicRouting();
  10119. }
  10120. async function removeSelectedOspfInstance() {
  10121. const id = state.selectedOspfRow?.instances;
  10122. if (!id) return;
  10123. if (!confirm('Delete selected OSPF instance?')) return;
  10124. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10125. loadDynamicRouting();
  10126. }
  10127. async function promptCommentOspfInstance() {
  10128. const id = state.selectedOspfRow?.instances;
  10129. if (!id) return;
  10130. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10131. if (!inst) return;
  10132. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10133. if (comment === null) return;
  10134. inst.comment = comment;
  10135. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10136. method: 'POST',
  10137. headers: { 'Content-Type': 'application/json' },
  10138. body: JSON.stringify(inst)
  10139. });
  10140. loadDynamicRouting();
  10141. }
  10142. // --- 2. OSPF AREA ---
  10143. function populateOspfAreaDropdowns() {
  10144. const instSelect = document.getElementById('modal-ospf-area-instance');
  10145. if (instSelect) {
  10146. const cur = instSelect.value;
  10147. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10148. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10149. if (cur) instSelect.value = cur;
  10150. }
  10151. }
  10152. function openOspfAreaModal(id = null) {
  10153. const isEdit = !!id;
  10154. populateOspfAreaDropdowns();
  10155. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10156. id: '',
  10157. name: 'Default',
  10158. instance: 'Default',
  10159. area_id: '0.0.0.0',
  10160. area_type: 'default',
  10161. default_cost: 1,
  10162. no_summaries: false,
  10163. disabled: false,
  10164. comment: ''
  10165. };
  10166. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10167. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10168. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10169. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10170. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10171. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10172. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10173. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10174. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10175. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10176. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10177. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10178. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10179. }
  10180. function openEditOspfAreaModal(id) {
  10181. openOspfAreaModal(id);
  10182. }
  10183. function closeOspfAreaModal() {
  10184. document.getElementById('ospf-area-modal').classList.add('hidden');
  10185. }
  10186. async function submitOspfArea(e) {
  10187. if (e) e.preventDefault();
  10188. const payload = {
  10189. id: document.getElementById('modal-ospf-area-id').value,
  10190. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10191. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10192. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10193. area_type: document.getElementById('modal-ospf-area-type').value,
  10194. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10195. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10196. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10197. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10198. };
  10199. try {
  10200. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10201. method: 'POST',
  10202. headers: { 'Content-Type': 'application/json' },
  10203. body: JSON.stringify(payload)
  10204. });
  10205. if (res.ok) {
  10206. closeOspfAreaModal();
  10207. showToast('Saved', 'OSPF area saved', 'success');
  10208. loadDynamicRouting();
  10209. } else {
  10210. const err = await res.json();
  10211. showToast('Error', err.error || 'Failed to save area', 'error');
  10212. }
  10213. } catch (err) {
  10214. showToast('Error', err.message, 'error');
  10215. }
  10216. }
  10217. function applyOspfAreaForm() {
  10218. submitOspfArea(null);
  10219. }
  10220. function copyOspfArea() {
  10221. document.getElementById('modal-ospf-area-id').value = '';
  10222. document.getElementById('modal-ospf-area-name').value += '-copy';
  10223. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10224. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10225. }
  10226. async function deleteCurrentOspfArea() {
  10227. const id = document.getElementById('modal-ospf-area-id').value;
  10228. if (!id) return;
  10229. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10230. try {
  10231. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10232. if (res.ok) {
  10233. closeOspfAreaModal();
  10234. showToast('Removed', 'OSPF area deleted', 'success');
  10235. loadDynamicRouting();
  10236. }
  10237. } catch (err) {
  10238. showToast('Error', err.message, 'error');
  10239. }
  10240. }
  10241. async function enableSelectedOspfArea() {
  10242. const id = state.selectedOspfRow?.areas;
  10243. if (!id) return;
  10244. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10245. method: 'POST',
  10246. headers: { 'Content-Type': 'application/json' },
  10247. body: JSON.stringify({ disabled: false })
  10248. });
  10249. loadDynamicRouting();
  10250. }
  10251. async function disableSelectedOspfArea() {
  10252. const id = state.selectedOspfRow?.areas;
  10253. if (!id) return;
  10254. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10255. method: 'POST',
  10256. headers: { 'Content-Type': 'application/json' },
  10257. body: JSON.stringify({ disabled: true })
  10258. });
  10259. loadDynamicRouting();
  10260. }
  10261. async function removeSelectedOspfArea() {
  10262. const id = state.selectedOspfRow?.areas;
  10263. if (!id) return;
  10264. if (!confirm('Delete selected OSPF area?')) return;
  10265. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10266. loadDynamicRouting();
  10267. }
  10268. async function promptCommentOspfArea() {
  10269. const id = state.selectedOspfRow?.areas;
  10270. if (!id) return;
  10271. const area = (state.ospfAreas || []).find(a => a.id === id);
  10272. if (!area) return;
  10273. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10274. if (comment === null) return;
  10275. area.comment = comment;
  10276. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10277. method: 'POST',
  10278. headers: { 'Content-Type': 'application/json' },
  10279. body: JSON.stringify(area)
  10280. });
  10281. loadDynamicRouting();
  10282. }
  10283. // --- 3. OSPF AREA RANGE ---
  10284. function populateAreaRangeDropdowns() {
  10285. const select = document.getElementById('modal-ospf-range-area');
  10286. if (select) {
  10287. const cur = select.value;
  10288. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10289. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10290. if (cur) select.value = cur;
  10291. }
  10292. }
  10293. function openOspfAreaRangeModal(id = null) {
  10294. const isEdit = !!id;
  10295. populateAreaRangeDropdowns();
  10296. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10297. id: '',
  10298. area: 'Default',
  10299. prefix: '',
  10300. cost: 1,
  10301. advertise: true,
  10302. disabled: false,
  10303. comment: ''
  10304. };
  10305. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10306. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10307. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10308. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10309. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10310. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10311. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10312. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10313. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10314. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10315. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10316. }
  10317. function openEditOspfAreaRangeModal(id) {
  10318. openOspfAreaRangeModal(id);
  10319. }
  10320. function closeOspfAreaRangeModal() {
  10321. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10322. }
  10323. async function submitOspfAreaRange(e) {
  10324. if (e) e.preventDefault();
  10325. const payload = {
  10326. id: document.getElementById('modal-ospf-range-id').value,
  10327. area: document.getElementById('modal-ospf-range-area').value,
  10328. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10329. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10330. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10331. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10332. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10333. };
  10334. try {
  10335. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10336. method: 'POST',
  10337. headers: { 'Content-Type': 'application/json' },
  10338. body: JSON.stringify(payload)
  10339. });
  10340. if (res.ok) {
  10341. closeOspfAreaRangeModal();
  10342. showToast('Saved', 'Area range saved', 'success');
  10343. loadDynamicRouting();
  10344. } else {
  10345. const err = await res.json();
  10346. showToast('Error', err.error || 'Failed to save area range', 'error');
  10347. }
  10348. } catch (err) {
  10349. showToast('Error', err.message, 'error');
  10350. }
  10351. }
  10352. function applyOspfAreaRangeForm() {
  10353. submitOspfAreaRange(null);
  10354. }
  10355. async function deleteCurrentOspfAreaRange() {
  10356. const id = document.getElementById('modal-ospf-range-id').value;
  10357. if (!id) return;
  10358. if (!confirm('Delete this area range?')) return;
  10359. try {
  10360. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10361. closeOspfAreaRangeModal();
  10362. showToast('Removed', 'Area range removed', 'success');
  10363. loadDynamicRouting();
  10364. } catch (err) {
  10365. showToast('Error', err.message, 'error');
  10366. }
  10367. }
  10368. async function enableSelectedOspfAreaRange() {
  10369. const id = state.selectedOspfRow?.['area-ranges'];
  10370. if (!id) return;
  10371. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10372. if (!r) return;
  10373. r.disabled = false;
  10374. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10375. loadDynamicRouting();
  10376. }
  10377. async function disableSelectedOspfAreaRange() {
  10378. const id = state.selectedOspfRow?.['area-ranges'];
  10379. if (!id) return;
  10380. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10381. if (!r) return;
  10382. r.disabled = true;
  10383. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10384. loadDynamicRouting();
  10385. }
  10386. async function removeSelectedOspfAreaRange() {
  10387. const id = state.selectedOspfRow?.['area-ranges'];
  10388. if (!id) return;
  10389. if (!confirm('Delete selected area range?')) return;
  10390. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10391. loadDynamicRouting();
  10392. }
  10393. async function promptCommentOspfAreaRange() {
  10394. const id = state.selectedOspfRow?.['area-ranges'];
  10395. if (!id) return;
  10396. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10397. if (!r) return;
  10398. const comment = prompt('Enter comment for area range:', r.comment || '');
  10399. if (comment === null) return;
  10400. r.comment = comment;
  10401. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10402. loadDynamicRouting();
  10403. }
  10404. // --- 4. OSPF INTERFACE TEMPLATE ---
  10405. function switchOspfTemplateTab(tab) {
  10406. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10407. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10408. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10409. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10410. if (tab === 'general') {
  10411. if (tabGen) tabGen.classList.remove('hidden');
  10412. if (tabAuth) tabAuth.classList.add('hidden');
  10413. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10414. 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';
  10415. } else {
  10416. if (tabGen) tabGen.classList.add('hidden');
  10417. if (tabAuth) tabAuth.classList.remove('hidden');
  10418. 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';
  10419. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10420. }
  10421. }
  10422. function populateTemplateAreaDropdowns() {
  10423. const select = document.getElementById('modal-ospf-tmpl-area');
  10424. if (select) {
  10425. const cur = select.value;
  10426. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10427. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10428. if (cur) select.value = cur;
  10429. }
  10430. }
  10431. function openOspfTemplateModal(id = null) {
  10432. const isEdit = !!id;
  10433. populateTemplateAreaDropdowns();
  10434. switchOspfTemplateTab('general');
  10435. const dl = document.getElementById('ospf-tmpl-iface-datalist');
  10436. if (dl) {
  10437. dl.innerHTML = '<option value="*"><option value="all">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  10438. }
  10439. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10440. id: '',
  10441. interfaces: '',
  10442. area: 'Default',
  10443. networks: '',
  10444. network_type: 'broadcast',
  10445. cost: 1,
  10446. priority: 128,
  10447. passive: false,
  10448. hello_interval: 10,
  10449. dead_interval: 40,
  10450. auth: 'none',
  10451. auth_key: '',
  10452. disabled: false,
  10453. comment: ''
  10454. };
  10455. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10456. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10457. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10458. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10459. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10460. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10461. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10462. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10463. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10464. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10465. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10466. if (document.getElementById('modal-ospf-tmpl-bfd')) document.getElementById('modal-ospf-tmpl-bfd').checked = !!tmpl.use_bfd;
  10467. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10468. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10469. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10470. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10471. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10472. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10473. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10474. }
  10475. function openEditOspfTemplateModal(id) {
  10476. openOspfTemplateModal(id);
  10477. }
  10478. function closeOspfTemplateModal() {
  10479. document.getElementById('ospf-template-modal').classList.add('hidden');
  10480. }
  10481. async function submitOspfTemplate(e) {
  10482. if (e) e.preventDefault();
  10483. const payload = {
  10484. id: document.getElementById('modal-ospf-tmpl-id').value,
  10485. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10486. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10487. area: document.getElementById('modal-ospf-tmpl-area').value,
  10488. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10489. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10490. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10491. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10492. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10493. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10494. use_bfd: document.getElementById('modal-ospf-tmpl-bfd')?.checked || false,
  10495. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10496. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10497. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10498. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10499. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10500. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10501. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10502. };
  10503. try {
  10504. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10505. method: 'POST',
  10506. headers: { 'Content-Type': 'application/json' },
  10507. body: JSON.stringify(payload)
  10508. });
  10509. if (res.ok) {
  10510. closeOspfTemplateModal();
  10511. showToast('Saved', 'Interface template saved', 'success');
  10512. loadDynamicRouting();
  10513. } else {
  10514. const err = await res.json();
  10515. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10516. }
  10517. } catch (err) {
  10518. showToast('Error', err.message, 'error');
  10519. }
  10520. }
  10521. function applyOspfTemplateForm() {
  10522. submitOspfTemplate(null);
  10523. }
  10524. function copyOspfTemplate() {
  10525. document.getElementById('modal-ospf-tmpl-id').value = '';
  10526. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10527. showToast('Copied', 'Duplicated as new template', 'info');
  10528. }
  10529. async function deleteCurrentOspfTemplate() {
  10530. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10531. if (!id) return;
  10532. if (!confirm('Delete this interface template?')) return;
  10533. try {
  10534. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10535. closeOspfTemplateModal();
  10536. showToast('Removed', 'Interface template deleted', 'success');
  10537. loadDynamicRouting();
  10538. } catch (err) {
  10539. showToast('Error', err.message, 'error');
  10540. }
  10541. }
  10542. async function enableSelectedOspfTemplate() {
  10543. const id = state.selectedOspfRow?.templates;
  10544. if (!id) return;
  10545. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10546. method: 'POST',
  10547. headers: { 'Content-Type': 'application/json' },
  10548. body: JSON.stringify({ disabled: false })
  10549. });
  10550. loadDynamicRouting();
  10551. }
  10552. async function disableSelectedOspfTemplate() {
  10553. const id = state.selectedOspfRow?.templates;
  10554. if (!id) return;
  10555. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10556. method: 'POST',
  10557. headers: { 'Content-Type': 'application/json' },
  10558. body: JSON.stringify({ disabled: true })
  10559. });
  10560. loadDynamicRouting();
  10561. }
  10562. async function removeSelectedOspfTemplate() {
  10563. const id = state.selectedOspfRow?.templates;
  10564. if (!id) return;
  10565. if (!confirm('Delete selected interface template?')) return;
  10566. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10567. loadDynamicRouting();
  10568. }
  10569. async function promptCommentOspfTemplate() {
  10570. const id = state.selectedOspfRow?.templates;
  10571. if (!id) return;
  10572. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10573. if (!tmpl) return;
  10574. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10575. if (comment === null) return;
  10576. tmpl.comment = comment;
  10577. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10578. method: 'POST',
  10579. headers: { 'Content-Type': 'application/json' },
  10580. body: JSON.stringify(tmpl)
  10581. });
  10582. loadDynamicRouting();
  10583. }
  10584. // --- 5. OSPF STATIC NEIGHBOR ---
  10585. function populateStaticNbrAreaDropdowns() {
  10586. const select = document.getElementById('modal-ospf-snbr-area');
  10587. if (select) {
  10588. const cur = select.value;
  10589. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10590. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10591. if (cur) select.value = cur;
  10592. }
  10593. }
  10594. function openOspfStaticNbrModal(id = null) {
  10595. const isEdit = !!id;
  10596. populateStaticNbrAreaDropdowns();
  10597. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10598. id: '',
  10599. address: '',
  10600. area: 'Default',
  10601. poll_interval: 120,
  10602. cost: 1,
  10603. disabled: false,
  10604. comment: ''
  10605. };
  10606. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10607. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10608. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10609. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10610. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10611. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10612. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10613. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10614. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10615. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10616. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10617. }
  10618. function openEditOspfStaticNbrModal(id) {
  10619. openOspfStaticNbrModal(id);
  10620. }
  10621. function closeOspfStaticNbrModal() {
  10622. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10623. }
  10624. async function submitOspfStaticNbr(e) {
  10625. if (e) e.preventDefault();
  10626. const payload = {
  10627. id: document.getElementById('modal-ospf-snbr-id').value,
  10628. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10629. area: document.getElementById('modal-ospf-snbr-area').value,
  10630. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10631. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10632. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10633. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10634. };
  10635. try {
  10636. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10637. method: 'POST',
  10638. headers: { 'Content-Type': 'application/json' },
  10639. body: JSON.stringify(payload)
  10640. });
  10641. if (res.ok) {
  10642. closeOspfStaticNbrModal();
  10643. showToast('Saved', 'Static neighbor saved', 'success');
  10644. loadDynamicRouting();
  10645. } else {
  10646. const err = await res.json();
  10647. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10648. }
  10649. } catch (err) {
  10650. showToast('Error', err.message, 'error');
  10651. }
  10652. }
  10653. function applyOspfStaticNbrForm() {
  10654. submitOspfStaticNbr(null);
  10655. }
  10656. async function deleteCurrentOspfStaticNbr() {
  10657. const id = document.getElementById('modal-ospf-snbr-id').value;
  10658. if (!id) return;
  10659. if (!confirm('Delete this static neighbor?')) return;
  10660. try {
  10661. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10662. closeOspfStaticNbrModal();
  10663. showToast('Removed', 'Static neighbor removed', 'success');
  10664. loadDynamicRouting();
  10665. } catch (err) {
  10666. showToast('Error', err.message, 'error');
  10667. }
  10668. }
  10669. async function enableSelectedOspfStaticNbr() {
  10670. const id = state.selectedOspfRow?.['static-nbrs'];
  10671. if (!id) return;
  10672. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10673. loadDynamicRouting();
  10674. }
  10675. async function disableSelectedOspfStaticNbr() {
  10676. const id = state.selectedOspfRow?.['static-nbrs'];
  10677. if (!id) return;
  10678. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10679. loadDynamicRouting();
  10680. }
  10681. async function removeSelectedOspfStaticNbr() {
  10682. const id = state.selectedOspfRow?.['static-nbrs'];
  10683. if (!id) return;
  10684. if (!confirm('Delete selected static neighbor?')) return;
  10685. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10686. loadDynamicRouting();
  10687. }
  10688. async function promptCommentOspfStaticNbr() {
  10689. const id = state.selectedOspfRow?.['static-nbrs'];
  10690. if (!id) return;
  10691. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10692. if (!n) return;
  10693. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10694. if (comment === null) return;
  10695. n.comment = comment;
  10696. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10697. loadDynamicRouting();
  10698. }
  10699. // Backward-compat aliases
  10700. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10701. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10702. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10703. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10704. function deleteOspfInterface(id) {
  10705. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10706. }
  10707. function toggleOspfInterfaceState(id, disabled) {
  10708. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10709. method: 'POST',
  10710. headers: { 'Content-Type': 'application/json' },
  10711. body: JSON.stringify({ disabled })
  10712. }).then(() => loadDynamicRouting());
  10713. }
  10714. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10715. function deleteOspfArea(id) {
  10716. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10717. }
  10718. // ============================================================================
  10719. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10720. // ============================================================================
  10721. function switchBridgeSubTab(tab) {
  10722. state.bridgeSubTab = tab;
  10723. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10724. tabs.forEach(t => {
  10725. const panel = document.getElementById(`bridge-subtab-${t}`);
  10726. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10727. if (panel) {
  10728. if (t === tab) panel.classList.remove('hidden');
  10729. else panel.classList.add('hidden');
  10730. }
  10731. if (btn) {
  10732. if (t === tab) {
  10733. 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';
  10734. } else {
  10735. 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';
  10736. }
  10737. }
  10738. });
  10739. const addBtn = document.getElementById('bridge-top-action-btn');
  10740. if (addBtn) {
  10741. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10742. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10743. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10744. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10745. }
  10746. if (tab === 'hosts') loadBridgeHosts();
  10747. setTimeout(initTableSorting, 50);
  10748. }
  10749. function openCurrentBridgeModal() {
  10750. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10751. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10752. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10753. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10754. }
  10755. async function loadBridge() {
  10756. try {
  10757. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10758. fetch(`${API_BASE}/bridge/bridges`),
  10759. fetch(`${API_BASE}/bridge/ports`),
  10760. fetch(`${API_BASE}/bridge/vlans`),
  10761. fetch(`${API_BASE}/bridge/summary`),
  10762. fetch(`${API_BASE}/vpn/eoip`),
  10763. fetch(`${API_BASE}/vpn/vxlan`),
  10764. fetch(`${API_BASE}/vlans`)
  10765. ]);
  10766. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10767. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10768. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10769. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10770. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10771. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10772. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10773. // Badges & Stats
  10774. const bBridges = document.getElementById('bridge-badge-bridges');
  10775. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10776. const bPorts = document.getElementById('bridge-badge-ports');
  10777. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10778. const bVlans = document.getElementById('bridge-badge-vlans');
  10779. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10780. const bHosts = document.getElementById('bridge-badge-hosts');
  10781. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10782. const sBr = document.getElementById('bridge-stat-bridges');
  10783. if (sBr) sBr.innerText = (state.bridges || []).length;
  10784. const sPorts = document.getElementById('bridge-stat-ports');
  10785. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10786. const sHosts = document.getElementById('bridge-stat-hosts');
  10787. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10788. renderBridges();
  10789. renderBridgePorts();
  10790. renderBridgeVLANs();
  10791. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10792. } catch (err) {
  10793. console.error('Failed to load bridge subsystem:', err);
  10794. }
  10795. }
  10796. // ----------------- Bridges -----------------
  10797. function renderBridges() {
  10798. const tbody = document.getElementById('bridge-table-body');
  10799. const empty = document.getElementById('bridge-empty-bridges');
  10800. const countBadge = document.getElementById('bridge-count-badge');
  10801. if (!tbody) return;
  10802. tbody.innerHTML = '';
  10803. const bridges = state.bridges || [];
  10804. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10805. if (bridges.length === 0) {
  10806. empty?.classList.remove('hidden');
  10807. return;
  10808. }
  10809. empty?.classList.add('hidden');
  10810. bridges.forEach((b, idx) => {
  10811. const tr = document.createElement('tr');
  10812. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10813. // Format IP addresses pill list
  10814. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10815. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10816. ipsHtml = b.ip_addresses.map(ip => `
  10817. <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">
  10818. <span>${ip}</span>
  10819. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10820. </span>
  10821. `).join(' ');
  10822. }
  10823. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10824. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10825. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10826. tr.innerHTML = `
  10827. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10828. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10829. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10830. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10831. </td>
  10832. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10833. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10834. <td class="py-2.5 px-3">
  10835. <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>
  10836. </td>
  10837. <td class="py-2.5 px-3 text-center">
  10838. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10839. </td>
  10840. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10841. <td class="py-2.5 px-3">
  10842. <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>
  10843. </td>
  10844. <td class="py-2.5 px-3">
  10845. <div class="flex items-center gap-1.5 flex-wrap">
  10846. ${ipsHtml}
  10847. <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>
  10848. </div>
  10849. </td>
  10850. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10851. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10852. </td>
  10853. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10854. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10855. <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>
  10856. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10857. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10858. </td>
  10859. `;
  10860. tbody.appendChild(tr);
  10861. });
  10862. }
  10863. function openAddBridgeModal() {
  10864. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10865. document.getElementById('bridge-modal-id').value = '';
  10866. document.getElementById('bridge-modal-name').value = 'bridge1';
  10867. document.getElementById('bridge-modal-name').disabled = false;
  10868. document.getElementById('bridge-modal-mtu').value = '1500';
  10869. document.getElementById('bridge-modal-mac').value = '';
  10870. document.getElementById('bridge-modal-stp').value = 'stp';
  10871. document.getElementById('bridge-modal-priority').value = '32768';
  10872. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10873. document.getElementById('bridge-modal-pvid').value = '1';
  10874. document.getElementById('bridge-modal-fastforward').checked = true;
  10875. document.getElementById('bridge-modal-comment').value = '';
  10876. document.getElementById('bridge-modal-disabled').checked = false;
  10877. toggleBridgeModalVlanFiltering();
  10878. document.getElementById('bridge-modal').classList.remove('hidden');
  10879. }
  10880. function openEditBridgeModal(id) {
  10881. const b = (state.bridges || []).find(x => x.id === id);
  10882. if (!b) return;
  10883. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10884. document.getElementById('bridge-modal-id').value = b.id;
  10885. document.getElementById('bridge-modal-name').value = b.name;
  10886. document.getElementById('bridge-modal-name').disabled = true;
  10887. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10888. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10889. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10890. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10891. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10892. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10893. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10894. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10895. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10896. toggleBridgeModalVlanFiltering();
  10897. document.getElementById('bridge-modal').classList.remove('hidden');
  10898. }
  10899. function closeBridgeModal() {
  10900. document.getElementById('bridge-modal').classList.add('hidden');
  10901. }
  10902. function toggleBridgeModalVlanFiltering() {
  10903. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10904. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10905. if (pvidBox) {
  10906. if (chk) pvidBox.classList.remove('opacity-40');
  10907. else pvidBox.classList.add('opacity-40');
  10908. }
  10909. }
  10910. async function submitSaveBridge(e) {
  10911. e.preventDefault();
  10912. const id = document.getElementById('bridge-modal-id').value;
  10913. const name = document.getElementById('bridge-modal-name').value.trim();
  10914. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10915. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10916. const stp = document.getElementById('bridge-modal-stp').value;
  10917. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10918. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10919. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10920. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10921. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10922. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10923. try {
  10924. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10925. method: 'POST',
  10926. headers: { 'Content-Type': 'application/json' },
  10927. body: JSON.stringify({
  10928. id,
  10929. name,
  10930. mtu,
  10931. mac_address: mac,
  10932. stp,
  10933. priority,
  10934. vlan_filtering: vlanFiltering,
  10935. pvid,
  10936. fast_forward: fastForward,
  10937. comment,
  10938. disabled
  10939. })
  10940. });
  10941. if (res.ok) {
  10942. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10943. closeBridgeModal();
  10944. loadBridge();
  10945. fetchData(false);
  10946. } else {
  10947. const err = await res.json();
  10948. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10949. }
  10950. } catch (err) {
  10951. showToast('Error', err.message, 'error');
  10952. }
  10953. }
  10954. async function toggleBridgeState(id, disabled) {
  10955. try {
  10956. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10957. method: 'POST',
  10958. headers: { 'Content-Type': 'application/json' },
  10959. body: JSON.stringify({ disabled })
  10960. });
  10961. if (res.ok) {
  10962. loadBridge();
  10963. fetchData(false);
  10964. }
  10965. } catch (err) {
  10966. showToast('Error', err.message, 'error');
  10967. }
  10968. }
  10969. async function deleteBridge(id) {
  10970. const b = (state.bridges || []).find(x => x.id === id);
  10971. const name = b ? b.name : id;
  10972. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10973. try {
  10974. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10975. if (res.ok) {
  10976. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10977. loadBridge();
  10978. fetchData(false);
  10979. } else {
  10980. const err = await res.json();
  10981. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10982. }
  10983. } catch (err) {
  10984. showToast('Error', err.message, 'error');
  10985. }
  10986. }
  10987. // ----------------- Bridge IP Assignments -----------------
  10988. function openAddBridgeIPModal(id, name) {
  10989. document.getElementById('bridge-ip-modal-id').value = id;
  10990. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10991. document.getElementById('bridge-ip-modal-cidr').value = '';
  10992. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10993. }
  10994. function closeBridgeIPModal() {
  10995. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10996. }
  10997. async function submitAddBridgeIP(e) {
  10998. e.preventDefault();
  10999. const id = document.getElementById('bridge-ip-modal-id').value;
  11000. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  11001. try {
  11002. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11003. method: 'POST',
  11004. headers: { 'Content-Type': 'application/json' },
  11005. body: JSON.stringify({ ip })
  11006. });
  11007. if (res.ok) {
  11008. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  11009. closeBridgeIPModal();
  11010. loadBridge();
  11011. fetchData(false);
  11012. } else {
  11013. const err = await res.json();
  11014. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  11015. }
  11016. } catch (err) {
  11017. showToast('Error', err.message, 'error');
  11018. }
  11019. }
  11020. async function deleteBridgeIP(id, ip) {
  11021. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  11022. try {
  11023. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11024. method: 'DELETE',
  11025. headers: { 'Content-Type': 'application/json' },
  11026. body: JSON.stringify({ ip })
  11027. });
  11028. if (res.ok) {
  11029. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  11030. loadBridge();
  11031. fetchData(false);
  11032. }
  11033. } catch (err) {
  11034. showToast('Error', err.message, 'error');
  11035. }
  11036. }
  11037. // ----------------- Bridge Ports -----------------
  11038. function renderBridgePorts() {
  11039. const tbody = document.getElementById('bridge-ports-table-body');
  11040. const empty = document.getElementById('bridge-empty-ports');
  11041. const countBadge = document.getElementById('bridge-ports-count-badge');
  11042. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  11043. if (!tbody) return;
  11044. tbody.innerHTML = '';
  11045. // Update filter select
  11046. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  11047. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  11048. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  11049. if (ports.length === 0) {
  11050. empty?.classList.remove('hidden');
  11051. return;
  11052. }
  11053. empty?.classList.add('hidden');
  11054. ports.forEach((p, idx) => {
  11055. const tr = document.createElement('tr');
  11056. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11057. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11058. tr.innerHTML = `
  11059. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11060. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11061. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11062. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11063. </td>
  11064. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11065. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11066. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11067. <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>
  11068. <td class="py-2.5 px-3">
  11069. ${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>'}
  11070. </td>
  11071. <td class="py-2.5 px-3">
  11072. <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>
  11073. </td>
  11074. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11075. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11076. <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>
  11077. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11078. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11079. </td>
  11080. `;
  11081. tbody.appendChild(tr);
  11082. });
  11083. }
  11084. function openAddBridgePortModal() {
  11085. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11086. document.getElementById('bridge-port-modal-id').value = '';
  11087. populateBridgeSelect('bridge-port-modal-bridge');
  11088. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11089. document.getElementById('bridge-port-modal-pvid').value = '1';
  11090. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11091. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11092. document.getElementById('bridge-port-modal-horizon').value = '0';
  11093. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11094. document.getElementById('bridge-port-modal-priority').value = '128';
  11095. document.getElementById('bridge-port-modal-learn').checked = true;
  11096. document.getElementById('bridge-port-modal-comment').value = '';
  11097. document.getElementById('bridge-port-modal-disabled').checked = false;
  11098. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11099. }
  11100. function openEditBridgePortModal(id) {
  11101. const p = (state.bridgePorts || []).find(x => x.id === id);
  11102. if (!p) return;
  11103. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11104. document.getElementById('bridge-port-modal-id').value = p.id;
  11105. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11106. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11107. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11108. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11109. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11110. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11111. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11112. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11113. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11114. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11115. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11116. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11117. }
  11118. function closeBridgePortModal() {
  11119. document.getElementById('bridge-port-modal').classList.add('hidden');
  11120. }
  11121. async function submitSaveBridgePort(e) {
  11122. e.preventDefault();
  11123. const id = document.getElementById('bridge-port-modal-id').value;
  11124. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11125. const iface = document.getElementById('bridge-port-modal-interface').value;
  11126. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11127. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11128. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11129. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11130. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11131. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11132. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11133. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11134. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11135. try {
  11136. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11137. method: 'POST',
  11138. headers: { 'Content-Type': 'application/json' },
  11139. body: JSON.stringify({
  11140. id,
  11141. bridge,
  11142. interface: iface,
  11143. pvid,
  11144. frame_types: frameTypes,
  11145. ingress_filtering: ingressFiltering,
  11146. horizon,
  11147. path_cost: pathCost,
  11148. priority,
  11149. learn,
  11150. comment,
  11151. disabled
  11152. })
  11153. });
  11154. if (res.ok) {
  11155. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11156. closeBridgePortModal();
  11157. loadBridge();
  11158. fetchData(false);
  11159. } else {
  11160. const err = await res.json();
  11161. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11162. }
  11163. } catch (err) {
  11164. showToast('Error', err.message, 'error');
  11165. }
  11166. }
  11167. async function toggleBridgePortState(id, disabled) {
  11168. try {
  11169. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11170. method: 'POST',
  11171. headers: { 'Content-Type': 'application/json' },
  11172. body: JSON.stringify({ disabled })
  11173. });
  11174. if (res.ok) {
  11175. loadBridge();
  11176. fetchData(false);
  11177. }
  11178. } catch (err) {
  11179. showToast('Error', err.message, 'error');
  11180. }
  11181. }
  11182. async function deleteBridgePort(id) {
  11183. const p = (state.bridgePorts || []).find(x => x.id === id);
  11184. const iface = p ? p.interface : id;
  11185. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11186. try {
  11187. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11188. if (res.ok) {
  11189. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11190. loadBridge();
  11191. fetchData(false);
  11192. }
  11193. } catch (err) {
  11194. showToast('Error', err.message, 'error');
  11195. }
  11196. }
  11197. // ----------------- Bridge VLANs -----------------
  11198. function renderBridgeVLANs() {
  11199. const tbody = document.getElementById('bridge-vlans-table-body');
  11200. const empty = document.getElementById('bridge-empty-vlans');
  11201. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11202. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11203. if (!tbody) return;
  11204. tbody.innerHTML = '';
  11205. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11206. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11207. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11208. if (vlans.length === 0) {
  11209. empty?.classList.remove('hidden');
  11210. return;
  11211. }
  11212. empty?.classList.add('hidden');
  11213. vlans.forEach((v, idx) => {
  11214. const tr = document.createElement('tr');
  11215. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11216. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11217. ? 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(' ')
  11218. : '<span class="text-slate-600">none</span>';
  11219. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11220. ? 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(' ')
  11221. : '<span class="text-slate-600">none</span>';
  11222. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11223. tr.innerHTML = `
  11224. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11225. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11226. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11227. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11228. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11229. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11230. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11231. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11232. <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>
  11233. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11234. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11235. </td>
  11236. `;
  11237. tbody.appendChild(tr);
  11238. });
  11239. }
  11240. function openAddBridgeVLANModal() {
  11241. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11242. document.getElementById('bridge-vlan-modal-id').value = '';
  11243. populateBridgeSelect('bridge-vlan-modal-bridge');
  11244. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11245. document.getElementById('bridge-vlan-modal-comment').value = '';
  11246. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11247. updateBridgeVlanPortCheckboxes();
  11248. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11249. }
  11250. function openEditBridgeVLANModal(id) {
  11251. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11252. if (!v) return;
  11253. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11254. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11255. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11256. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11257. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11258. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11259. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11260. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11261. }
  11262. function closeBridgeVlanModal() {
  11263. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11264. }
  11265. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11266. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11267. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11268. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11269. if (!taggedBox || !untaggedBox) return;
  11270. // Ports belonging to the selected bridge
  11271. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11272. if (memberPorts.length === 0) {
  11273. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11274. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11275. return;
  11276. }
  11277. taggedBox.innerHTML = memberPorts.map(p => `
  11278. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11279. <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">
  11280. <span>${p.interface}</span>
  11281. </label>
  11282. `).join('');
  11283. untaggedBox.innerHTML = memberPorts.map(p => `
  11284. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11285. <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">
  11286. <span>${p.interface}</span>
  11287. </label>
  11288. `).join('');
  11289. }
  11290. async function submitSaveBridgeVLAN(e) {
  11291. e.preventDefault();
  11292. const id = document.getElementById('bridge-vlan-modal-id').value;
  11293. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11294. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11295. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11296. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11297. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11298. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11299. try {
  11300. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11301. method: 'POST',
  11302. headers: { 'Content-Type': 'application/json' },
  11303. body: JSON.stringify({
  11304. id,
  11305. bridge,
  11306. vlan_ids: vlanIDs,
  11307. tagged,
  11308. untagged,
  11309. comment,
  11310. disabled
  11311. })
  11312. });
  11313. if (res.ok) {
  11314. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11315. closeBridgeVlanModal();
  11316. loadBridge();
  11317. } else {
  11318. const err = await res.json();
  11319. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11320. }
  11321. } catch (err) {
  11322. showToast('Error', err.message, 'error');
  11323. }
  11324. }
  11325. async function toggleBridgeVLANState(id, disabled) {
  11326. try {
  11327. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11328. method: 'POST',
  11329. headers: { 'Content-Type': 'application/json' },
  11330. body: JSON.stringify({ disabled })
  11331. });
  11332. if (res.ok) loadBridge();
  11333. } catch (err) {
  11334. showToast('Error', err.message, 'error');
  11335. }
  11336. }
  11337. async function deleteBridgeVLAN(id) {
  11338. if (!confirm('Delete this bridge VLAN entry?')) return;
  11339. try {
  11340. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11341. if (res.ok) {
  11342. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11343. loadBridge();
  11344. }
  11345. } catch (err) {
  11346. showToast('Error', err.message, 'error');
  11347. }
  11348. }
  11349. // ----------------- Hosts / MAC Table -----------------
  11350. async function loadBridgeHosts() {
  11351. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11352. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11353. try {
  11354. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11355. const res = await fetch(url);
  11356. if (res.ok) {
  11357. state.bridgeHosts = await res.json();
  11358. renderBridgeHosts();
  11359. }
  11360. } catch (err) {
  11361. console.error('Failed to load bridge hosts:', err);
  11362. }
  11363. }
  11364. function renderBridgeHosts() {
  11365. const tbody = document.getElementById('bridge-hosts-table-body');
  11366. const empty = document.getElementById('bridge-empty-hosts');
  11367. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11368. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11369. if (!tbody) return;
  11370. tbody.innerHTML = '';
  11371. const hosts = (state.bridgeHosts || []).filter(h => {
  11372. if (!search) return true;
  11373. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11374. });
  11375. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11376. if (hosts.length === 0) {
  11377. empty?.classList.remove('hidden');
  11378. return;
  11379. }
  11380. empty?.classList.add('hidden');
  11381. hosts.forEach(h => {
  11382. const tr = document.createElement('tr');
  11383. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11384. let flagBadges = '';
  11385. 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>';
  11386. 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>';
  11387. 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>';
  11388. tr.innerHTML = `
  11389. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11390. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11391. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11392. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11393. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11394. <td class="py-2.5 px-3">${flagBadges}</td>
  11395. `;
  11396. tbody.appendChild(tr);
  11397. });
  11398. }
  11399. async function flushBridgeHosts() {
  11400. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11401. if (!selBridge) {
  11402. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11403. return;
  11404. }
  11405. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11406. try {
  11407. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11408. method: 'POST',
  11409. headers: { 'Content-Type': 'application/json' },
  11410. body: JSON.stringify({ bridge: selBridge })
  11411. });
  11412. if (res.ok) {
  11413. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11414. loadBridgeHosts();
  11415. }
  11416. } catch (err) {
  11417. showToast('Error', err.message, 'error');
  11418. }
  11419. }
  11420. // ----------------- Helpers -----------------
  11421. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11422. const sel = document.getElementById(selectId);
  11423. if (!sel) return;
  11424. const prevVal = currentVal || sel.value;
  11425. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11426. (state.bridges || []).forEach(b => {
  11427. const opt = document.createElement('option');
  11428. opt.value = b.name;
  11429. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11430. if (b.name === prevVal) opt.selected = true;
  11431. sel.appendChild(opt);
  11432. });
  11433. }
  11434. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11435. const sel = document.getElementById(selectId);
  11436. if (!sel) return;
  11437. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11438. // 1. Physical Interfaces
  11439. const grpPhys = document.createElement('optgroup');
  11440. grpPhys.label = 'Physical Interfaces';
  11441. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11442. const opt = document.createElement('option');
  11443. opt.value = i.name;
  11444. opt.innerText = `${i.name} (${i.role || i.type})`;
  11445. if (i.name === currentVal) opt.selected = true;
  11446. grpPhys.appendChild(opt);
  11447. });
  11448. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11449. // 2. VLAN Sub-interfaces
  11450. const grpVlans = document.createElement('optgroup');
  11451. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11452. (state.vlans || []).forEach(v => {
  11453. const opt = document.createElement('option');
  11454. opt.value = v.name;
  11455. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11456. if (v.name === currentVal) opt.selected = true;
  11457. grpVlans.appendChild(opt);
  11458. });
  11459. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11460. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11461. const grpEoip = document.createElement('optgroup');
  11462. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11463. (state.eoipTunnels || []).forEach(t => {
  11464. const opt = document.createElement('option');
  11465. opt.value = t.name;
  11466. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11467. if (t.name === currentVal) opt.selected = true;
  11468. grpEoip.appendChild(opt);
  11469. });
  11470. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11471. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11472. const grpVxlan = document.createElement('optgroup');
  11473. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11474. (state.vxlanTunnels || []).forEach(t => {
  11475. const opt = document.createElement('option');
  11476. opt.value = t.name;
  11477. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11478. if (t.name === currentVal) opt.selected = true;
  11479. grpVxlan.appendChild(opt);
  11480. });
  11481. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11482. }
  11483. // -------------------------------------------------------------
  11484. // DebTik Routing Filters Management (/routing filter)
  11485. // -------------------------------------------------------------
  11486. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11487. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11488. if (!state.rfSort) state.rfSort = {};
  11489. function switchRoutingFilterTab(tab) {
  11490. state.activeRoutingFilterTab = tab;
  11491. const tabs = ['rules', 'community-lists', 'as-lists'];
  11492. tabs.forEach(t => {
  11493. const btn = document.getElementById(`tab-rf-${t}`);
  11494. const content = document.getElementById(`tab-content-rf-${t}`);
  11495. if (btn) {
  11496. if (t === tab) {
  11497. 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';
  11498. } else {
  11499. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11500. }
  11501. }
  11502. if (content) {
  11503. if (t === tab) content.classList.remove('hidden');
  11504. else content.classList.add('hidden');
  11505. }
  11506. });
  11507. const chainContainer = document.getElementById('rf-chain-filter-container');
  11508. if (chainContainer) {
  11509. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11510. else chainContainer.classList.add('hidden');
  11511. }
  11512. renderRoutingFilters();
  11513. }
  11514. function selectFilterRow(tab, id) {
  11515. if (state.selectedFilterRow[tab] === id) {
  11516. delete state.selectedFilterRow[tab];
  11517. } else {
  11518. state.selectedFilterRow[tab] = id;
  11519. }
  11520. if (tab === 'rules') renderRoutingFilterRules();
  11521. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11522. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11523. }
  11524. function openRoutingFilterNewModal() {
  11525. const tab = state.activeRoutingFilterTab || 'rules';
  11526. if (tab === 'rules') openAddRoutingFilterModal();
  11527. else if (tab === 'community-lists') openAddCommunityListModal();
  11528. else if (tab === 'as-lists') openAddASListModal();
  11529. }
  11530. function toggleSelectedRoutingFilter(disabled) {
  11531. const tab = state.activeRoutingFilterTab || 'rules';
  11532. const id = state.selectedFilterRow[tab];
  11533. if (!id) {
  11534. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11535. return;
  11536. }
  11537. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11538. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11539. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11540. }
  11541. function removeSelectedRoutingFilter() {
  11542. const tab = state.activeRoutingFilterTab || 'rules';
  11543. const id = state.selectedFilterRow[tab];
  11544. if (!id) {
  11545. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11546. return;
  11547. }
  11548. if (tab === 'rules') deleteRoutingFilter(id);
  11549. else if (tab === 'community-lists') deleteCommunityList(id);
  11550. else if (tab === 'as-lists') deleteASList(id);
  11551. }
  11552. function searchRoutingFilters(q) {
  11553. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11554. renderRoutingFilters();
  11555. }
  11556. function sortFilterTable(tab, col) {
  11557. if (!state.rfSort) state.rfSort = {};
  11558. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11559. if (state.rfSort[tab].col === col) {
  11560. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11561. } else {
  11562. state.rfSort[tab].col = col;
  11563. state.rfSort[tab].asc = true;
  11564. }
  11565. const asc = state.rfSort[tab].asc;
  11566. let list = [];
  11567. if (tab === 'rules') list = state.routingFilters || [];
  11568. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11569. else if (tab === 'as-lists') list = state.routingASLists || [];
  11570. list.sort((a, b) => {
  11571. let valA = a[col] ?? '';
  11572. let valB = b[col] ?? '';
  11573. if (col === 'flags') {
  11574. valA = a.disabled ? 'X' : 'A';
  11575. valB = b.disabled ? 'X' : 'A';
  11576. }
  11577. if (typeof valA === 'number' && typeof valB === 'number') {
  11578. return asc ? valA - valB : valB - valA;
  11579. }
  11580. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11581. });
  11582. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11583. allCols.forEach(c => {
  11584. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11585. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11586. });
  11587. if (tab === 'rules') renderRoutingFilterRules();
  11588. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11589. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11590. }
  11591. function renderRoutingFilters() {
  11592. const navBadge = document.getElementById('badge-filters-count');
  11593. const allRules = state.routingFilters || [];
  11594. if (navBadge) navBadge.innerText = allRules.length;
  11595. // Populate chain filter select options and datalist
  11596. const chainSelect = document.getElementById('routing-filter-chain-select');
  11597. const chainDatalist = document.getElementById('dl-routing-chains');
  11598. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11599. if (chainSelect) {
  11600. const currentVal = state.filterChainSelected || 'all';
  11601. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11602. uniqueChains.map(ch => {
  11603. const count = allRules.filter(r => r.chain === ch).length;
  11604. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11605. }).join('');
  11606. chainSelect.value = currentVal;
  11607. }
  11608. if (chainDatalist) {
  11609. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11610. }
  11611. renderRoutingFilterRules();
  11612. renderRoutingFilterCommunityLists();
  11613. renderRoutingFilterASLists();
  11614. }
  11615. function filterRoutingFiltersByChain(chain) {
  11616. state.filterChainSelected = chain;
  11617. renderRoutingFilters();
  11618. }
  11619. // -------------------------------------------------------------
  11620. // TAB 1: RULES (/routing filter rule)
  11621. // -------------------------------------------------------------
  11622. function renderRoutingFilterRules() {
  11623. const tbody = document.getElementById('routing-filter-rules-tbody');
  11624. if (!tbody) return;
  11625. const empty = document.getElementById('rf-rules-empty');
  11626. const statusCount = document.getElementById('rf-status-count');
  11627. let list = (state.routingFilters || []).slice();
  11628. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11629. list = list.filter(r => r.chain === state.filterChainSelected);
  11630. }
  11631. const q = state.rfSearchQuery;
  11632. if (q) {
  11633. list = list.filter(r =>
  11634. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11635. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11636. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11637. (r.comment && r.comment.toLowerCase().includes(q))
  11638. );
  11639. }
  11640. if (!state.rfSort?.['rules']) {
  11641. list.sort((a, b) => {
  11642. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11643. return (a.rule_order || 0) - (b.rule_order || 0);
  11644. });
  11645. }
  11646. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11647. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11648. }
  11649. if (list.length === 0) {
  11650. tbody.innerHTML = '';
  11651. if (empty) empty.classList.remove('hidden');
  11652. return;
  11653. }
  11654. if (empty) empty.classList.add('hidden');
  11655. tbody.innerHTML = list.map(r => {
  11656. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11657. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11658. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11659. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11660. let ruleDisplay = '';
  11661. if (r.rule && r.rule.trim() !== '') {
  11662. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11663. } else {
  11664. let conds = [];
  11665. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11666. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11667. let act = r.action || 'accept';
  11668. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11669. }
  11670. return `
  11671. <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'}">
  11672. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11673. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11674. <td class="py-2 px-3">
  11675. <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>
  11676. </td>
  11677. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11678. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11679. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11680. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  11681. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  11682. <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'}">
  11683. ${r.disabled ? 'Enable' : 'Disable'}
  11684. </button>
  11685. <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">
  11686. Edit
  11687. </button>
  11688. <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">
  11689. ✕
  11690. </button>
  11691. </td>
  11692. </tr>
  11693. `;
  11694. }).join('');
  11695. }
  11696. // -------------------------------------------------------------
  11697. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11698. // -------------------------------------------------------------
  11699. function renderRoutingFilterCommunityLists() {
  11700. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11701. if (!tbody) return;
  11702. const empty = document.getElementById('rf-comm-lists-empty');
  11703. const statusCount = document.getElementById('rf-status-count');
  11704. let list = (state.routingCommunityLists || []).slice();
  11705. const q = state.rfSearchQuery;
  11706. if (q) {
  11707. list = list.filter(cl =>
  11708. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11709. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11710. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11711. );
  11712. }
  11713. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11714. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11715. }
  11716. if (list.length === 0) {
  11717. tbody.innerHTML = '';
  11718. if (empty) empty.classList.remove('hidden');
  11719. return;
  11720. }
  11721. if (empty) empty.classList.add('hidden');
  11722. tbody.innerHTML = list.map(cl => {
  11723. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11724. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11725. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11726. const commBadges = (cl.communities || []).map(c =>
  11727. `<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>`
  11728. ).join(' ');
  11729. return `
  11730. <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'}">
  11731. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11732. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11733. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11734. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11735. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11736. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11737. <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'}">
  11738. ${cl.disabled ? 'Enable' : 'Disable'}
  11739. </button>
  11740. <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">
  11741. Edit
  11742. </button>
  11743. <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">
  11744. ✕
  11745. </button>
  11746. </td>
  11747. </tr>
  11748. `;
  11749. }).join('');
  11750. }
  11751. // -------------------------------------------------------------
  11752. // TAB 4: AS LISTS (/routing filter num-list)
  11753. // -------------------------------------------------------------
  11754. function renderRoutingFilterASLists() {
  11755. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11756. if (!tbody) return;
  11757. const empty = document.getElementById('rf-as-lists-empty');
  11758. const statusCount = document.getElementById('rf-status-count');
  11759. let list = (state.routingASLists || []).slice();
  11760. const q = state.rfSearchQuery;
  11761. if (q) {
  11762. list = list.filter(al =>
  11763. (al.name && al.name.toLowerCase().includes(q)) ||
  11764. (al.range && al.range.toLowerCase().includes(q)) ||
  11765. (al.comment && al.comment.toLowerCase().includes(q))
  11766. );
  11767. }
  11768. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11769. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11770. }
  11771. if (list.length === 0) {
  11772. tbody.innerHTML = '';
  11773. if (empty) empty.classList.remove('hidden');
  11774. return;
  11775. }
  11776. if (empty) empty.classList.add('hidden');
  11777. tbody.innerHTML = list.map(al => {
  11778. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11779. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11780. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11781. return `
  11782. <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'}">
  11783. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11784. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11785. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11786. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11787. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11788. <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'}">
  11789. ${al.disabled ? 'Enable' : 'Disable'}
  11790. </button>
  11791. <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">
  11792. Edit
  11793. </button>
  11794. <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">
  11795. ✕
  11796. </button>
  11797. </td>
  11798. </tr>
  11799. `;
  11800. }).join('');
  11801. }
  11802. // -------------------------------------------------------------
  11803. // SNIPPETS & WIZARD HELPERS
  11804. // -------------------------------------------------------------
  11805. function insertRuleSnippet(type) {
  11806. const textarea = document.getElementById('modal-rf-rule');
  11807. if (!textarea) return;
  11808. let snippet = '';
  11809. switch (type) {
  11810. case 'accept-default':
  11811. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11812. break;
  11813. case 'drop-rfc1918':
  11814. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11815. break;
  11816. case 'len-24':
  11817. snippet = 'if (dst-len > 24) { reject; }';
  11818. break;
  11819. case 'local-pref-150':
  11820. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11821. break;
  11822. case 'as-prepend-2':
  11823. snippet = 'set bgp-path-prepend 2; accept;';
  11824. break;
  11825. case 'set-comm':
  11826. snippet = 'set bgp-communities.add 65000:100; accept;';
  11827. break;
  11828. case 'match-comm':
  11829. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11830. break;
  11831. case 'reject-all':
  11832. snippet = 'reject;';
  11833. break;
  11834. }
  11835. if (!snippet) return;
  11836. if (!textarea.value.trim()) {
  11837. textarea.value = snippet;
  11838. } else {
  11839. textarea.value = textarea.value.trim() + '\n' + snippet;
  11840. }
  11841. }
  11842. function generateScriptFromWizard() {
  11843. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11844. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11845. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11846. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11847. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11848. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11849. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11850. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11851. const conds = [];
  11852. if (pfx) {
  11853. if (pfxLen) {
  11854. if (pfxLen.includes('-')) {
  11855. const parts = pfxLen.split('-');
  11856. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11857. } else {
  11858. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11859. }
  11860. } else {
  11861. conds.push(`dst in ${pfx}`);
  11862. }
  11863. }
  11864. if (proto && proto !== 'any') {
  11865. conds.push(`protocol ${proto}`);
  11866. }
  11867. if (asp) {
  11868. conds.push(`bgp-as-path "${asp}"`);
  11869. }
  11870. if (comm) {
  11871. conds.push(`bgp-communities includes ${comm}`);
  11872. }
  11873. const actions = [];
  11874. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11875. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11876. if (act && act !== 'passthrough') {
  11877. actions.push(`${act};`);
  11878. }
  11879. let code = '';
  11880. if (conds.length > 0) {
  11881. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11882. } else {
  11883. code = actions.join(' ');
  11884. }
  11885. const textarea = document.getElementById('modal-rf-rule');
  11886. if (textarea) textarea.value = code;
  11887. }
  11888. // -------------------------------------------------------------
  11889. // MODAL CRUD: RULES (/routing filter rule)
  11890. // -------------------------------------------------------------
  11891. function openAddRoutingFilterModal(defaultChain = '') {
  11892. const form = document.getElementById('routing-filter-form');
  11893. if (form) form.reset();
  11894. const idEl = document.getElementById('modal-rf-id');
  11895. if (idEl) idEl.value = '';
  11896. const titleEl = document.getElementById('modal-rf-title');
  11897. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11898. const chainEl = document.getElementById('modal-rf-chain');
  11899. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11900. const orderEl = document.getElementById('modal-rf-order');
  11901. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11902. const ruleEl = document.getElementById('modal-rf-rule');
  11903. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11904. const disEl = document.getElementById('modal-rf-disabled');
  11905. if (disEl) disEl.checked = false;
  11906. const modal = document.getElementById('modal-routing-filter');
  11907. if (modal) modal.classList.remove('hidden');
  11908. }
  11909. function openEditRoutingFilterModal(id) {
  11910. const r = (state.routingFilters || []).find(item => item.id === id);
  11911. if (!r) return;
  11912. const idEl = document.getElementById('modal-rf-id');
  11913. if (idEl) idEl.value = r.id;
  11914. const titleEl = document.getElementById('modal-rf-title');
  11915. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11916. const chainEl = document.getElementById('modal-rf-chain');
  11917. if (chainEl) chainEl.value = r.chain || '';
  11918. const orderEl = document.getElementById('modal-rf-order');
  11919. if (orderEl) orderEl.value = r.rule_order || 10;
  11920. const ruleEl = document.getElementById('modal-rf-rule');
  11921. if (ruleEl) {
  11922. if (r.rule) {
  11923. ruleEl.value = r.rule;
  11924. } else {
  11925. let conds = [];
  11926. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11927. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11928. let act = r.action || 'accept';
  11929. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11930. }
  11931. }
  11932. const comEl = document.getElementById('modal-rf-comment');
  11933. if (comEl) comEl.value = r.comment || '';
  11934. const disEl = document.getElementById('modal-rf-disabled');
  11935. if (disEl) disEl.checked = !!r.disabled;
  11936. const modal = document.getElementById('modal-routing-filter');
  11937. if (modal) modal.classList.remove('hidden');
  11938. }
  11939. function closeRoutingFilterModal() {
  11940. const modal = document.getElementById('modal-routing-filter');
  11941. if (modal) modal.classList.add('hidden');
  11942. }
  11943. async function submitRoutingFilter(e) {
  11944. if (e) e.preventDefault();
  11945. const payload = {
  11946. id: document.getElementById('modal-rf-id').value,
  11947. chain: document.getElementById('modal-rf-chain').value.trim(),
  11948. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11949. rule: document.getElementById('modal-rf-rule').value.trim(),
  11950. comment: document.getElementById('modal-rf-comment').value.trim(),
  11951. disabled: document.getElementById('modal-rf-disabled').checked
  11952. };
  11953. try {
  11954. const res = await fetch(`${API_BASE}/routing/filters`, {
  11955. method: 'POST',
  11956. headers: { 'Content-Type': 'application/json' },
  11957. body: JSON.stringify(payload)
  11958. });
  11959. if (res.ok) {
  11960. closeRoutingFilterModal();
  11961. showToast('Success', 'Routing filter rule saved', 'success');
  11962. loadDynamicRouting();
  11963. } else {
  11964. const err = await res.json();
  11965. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11966. }
  11967. } catch (err) {
  11968. showToast('Error', err.message, 'error');
  11969. }
  11970. }
  11971. async function applyRoutingFilterForm() {
  11972. const payload = {
  11973. id: document.getElementById('modal-rf-id').value,
  11974. chain: document.getElementById('modal-rf-chain').value.trim(),
  11975. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11976. rule: document.getElementById('modal-rf-rule').value.trim(),
  11977. comment: document.getElementById('modal-rf-comment').value.trim(),
  11978. disabled: document.getElementById('modal-rf-disabled').checked
  11979. };
  11980. try {
  11981. const res = await fetch(`${API_BASE}/routing/filters`, {
  11982. method: 'POST',
  11983. headers: { 'Content-Type': 'application/json' },
  11984. body: JSON.stringify(payload)
  11985. });
  11986. if (res.ok) {
  11987. const data = await res.json();
  11988. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11989. showToast('Applied', 'Routing filter configuration applied', 'success');
  11990. loadDynamicRouting();
  11991. } else {
  11992. const err = await res.json();
  11993. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11994. }
  11995. } catch (err) {
  11996. showToast('Error', err.message, 'error');
  11997. }
  11998. }
  11999. async function moveRoutingFilterOrder(id, delta) {
  12000. const list = state.routingFilters || [];
  12001. const idx = list.findIndex(r => r.id === id);
  12002. if (idx < 0) return;
  12003. const targetIdx = idx + delta;
  12004. if (targetIdx < 0 || targetIdx >= list.length) return;
  12005. const currentOrder = list[idx].rule_order || 10;
  12006. const targetOrder = list[targetIdx].rule_order || 20;
  12007. list[idx].rule_order = targetOrder;
  12008. list[targetIdx].rule_order = currentOrder;
  12009. try {
  12010. await fetch(`${API_BASE}/routing/filters`, {
  12011. method: 'POST',
  12012. headers: { 'Content-Type': 'application/json' },
  12013. body: JSON.stringify(list[idx])
  12014. });
  12015. await fetch(`${API_BASE}/routing/filters`, {
  12016. method: 'POST',
  12017. headers: { 'Content-Type': 'application/json' },
  12018. body: JSON.stringify(list[targetIdx])
  12019. });
  12020. loadDynamicRouting();
  12021. } catch (e) {
  12022. console.error('Reorder error:', e);
  12023. }
  12024. }
  12025. async function deleteRoutingFilter(id) {
  12026. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  12027. try {
  12028. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12029. if (res.ok) {
  12030. showToast('Deleted', 'Routing filter rule removed', 'info');
  12031. loadDynamicRouting();
  12032. } else {
  12033. const err = await res.json();
  12034. showToast('Error', err.error || 'Failed to delete rule', 'error');
  12035. }
  12036. } catch (err) {
  12037. showToast('Error', err.message, 'error');
  12038. }
  12039. }
  12040. async function toggleRoutingFilterState(id, disabled) {
  12041. try {
  12042. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  12043. method: 'POST',
  12044. headers: { 'Content-Type': 'application/json' },
  12045. body: JSON.stringify({ disabled })
  12046. });
  12047. if (res.ok) {
  12048. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12049. loadDynamicRouting();
  12050. } else {
  12051. const err = await res.json();
  12052. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  12053. }
  12054. } catch (err) {
  12055. showToast('Error', err.message, 'error');
  12056. }
  12057. }
  12058. // -------------------------------------------------------------
  12059. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12060. // -------------------------------------------------------------
  12061. function openAddCommunityListModal() {
  12062. document.getElementById('modal-rf-cl-id').value = '';
  12063. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12064. document.getElementById('modal-rf-cl-name').value = '';
  12065. document.getElementById('modal-rf-cl-communities').value = '';
  12066. document.getElementById('modal-rf-cl-regexp').value = '';
  12067. document.getElementById('modal-rf-cl-comment').value = '';
  12068. document.getElementById('modal-rf-cl-disabled').checked = false;
  12069. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12070. }
  12071. function openEditCommunityListModal(id) {
  12072. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12073. if (!cl) return;
  12074. document.getElementById('modal-rf-cl-id').value = cl.id;
  12075. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12076. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12077. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12078. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12079. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12080. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12081. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12082. }
  12083. function closeCommunityListModal() {
  12084. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12085. }
  12086. async function submitCommunityList(e) {
  12087. e.preventDefault();
  12088. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12089. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12090. const payload = {
  12091. id: document.getElementById('modal-rf-cl-id').value,
  12092. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12093. communities: comms,
  12094. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12095. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12096. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12097. };
  12098. try {
  12099. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12100. method: 'POST',
  12101. headers: { 'Content-Type': 'application/json' },
  12102. body: JSON.stringify(payload)
  12103. });
  12104. if (res.ok) {
  12105. closeCommunityListModal();
  12106. showToast('Success', 'Community list saved', 'success');
  12107. loadDynamicRouting();
  12108. } else {
  12109. const err = await res.json();
  12110. showToast('Error', err.error || 'Failed to save community list', 'error');
  12111. }
  12112. } catch (err) {
  12113. showToast('Error', err.message, 'error');
  12114. }
  12115. }
  12116. async function deleteCommunityList(id) {
  12117. if (!confirm('Are you sure you want to delete this community list?')) return;
  12118. try {
  12119. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12120. if (res.ok) {
  12121. showToast('Deleted', 'Community list removed', 'info');
  12122. loadDynamicRouting();
  12123. } else {
  12124. const err = await res.json();
  12125. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12126. }
  12127. } catch (err) {
  12128. showToast('Error', err.message, 'error');
  12129. }
  12130. }
  12131. async function toggleCommunityListState(id, disabled) {
  12132. try {
  12133. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12134. method: 'POST',
  12135. headers: { 'Content-Type': 'application/json' },
  12136. body: JSON.stringify({ disabled })
  12137. });
  12138. if (res.ok) {
  12139. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12140. loadDynamicRouting();
  12141. } else {
  12142. const err = await res.json();
  12143. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12144. }
  12145. } catch (err) {
  12146. showToast('Error', err.message, 'error');
  12147. }
  12148. }
  12149. // -------------------------------------------------------------
  12150. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12151. // -------------------------------------------------------------
  12152. function openAddASListModal() {
  12153. document.getElementById('modal-rf-al-id').value = '';
  12154. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12155. document.getElementById('modal-rf-al-name').value = '';
  12156. document.getElementById('modal-rf-al-range').value = '';
  12157. document.getElementById('modal-rf-al-comment').value = '';
  12158. document.getElementById('modal-rf-al-disabled').checked = false;
  12159. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12160. }
  12161. function openEditASListModal(id) {
  12162. const al = (state.routingASLists || []).find(item => item.id === id);
  12163. if (!al) return;
  12164. document.getElementById('modal-rf-al-id').value = al.id;
  12165. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12166. document.getElementById('modal-rf-al-name').value = al.name || '';
  12167. document.getElementById('modal-rf-al-range').value = al.range || '';
  12168. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12169. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12170. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12171. }
  12172. function closeASListModal() {
  12173. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12174. }
  12175. async function submitASList(e) {
  12176. e.preventDefault();
  12177. const payload = {
  12178. id: document.getElementById('modal-rf-al-id').value,
  12179. name: document.getElementById('modal-rf-al-name').value.trim(),
  12180. range: document.getElementById('modal-rf-al-range').value.trim(),
  12181. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12182. disabled: document.getElementById('modal-rf-al-disabled').checked
  12183. };
  12184. try {
  12185. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12186. method: 'POST',
  12187. headers: { 'Content-Type': 'application/json' },
  12188. body: JSON.stringify(payload)
  12189. });
  12190. if (res.ok) {
  12191. closeASListModal();
  12192. showToast('Success', 'AS number list saved', 'success');
  12193. loadDynamicRouting();
  12194. } else {
  12195. const err = await res.json();
  12196. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12197. }
  12198. } catch (err) {
  12199. showToast('Error', err.message, 'error');
  12200. }
  12201. }
  12202. async function deleteASList(id) {
  12203. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12204. try {
  12205. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12206. if (res.ok) {
  12207. showToast('Deleted', 'AS list removed', 'info');
  12208. loadDynamicRouting();
  12209. } else {
  12210. const err = await res.json();
  12211. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12212. }
  12213. } catch (err) {
  12214. showToast('Error', err.message, 'error');
  12215. }
  12216. }
  12217. async function toggleASListState(id, disabled) {
  12218. try {
  12219. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12220. method: 'POST',
  12221. headers: { 'Content-Type': 'application/json' },
  12222. body: JSON.stringify({ disabled })
  12223. });
  12224. if (res.ok) {
  12225. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12226. loadDynamicRouting();
  12227. } else {
  12228. const err = await res.json();
  12229. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12230. }
  12231. } catch (err) {
  12232. showToast('Error', err.message, 'error');
  12233. }
  12234. }
  12235. // ==========================================
  12236. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12237. // ==========================================
  12238. function loadToolsView() {
  12239. populateToolsInterfaces();
  12240. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12241. }
  12242. function populateToolsInterfaces() {
  12243. const pingSel = document.getElementById('tools-ping-iface');
  12244. const traceSel = document.getElementById('tools-tr-iface');
  12245. let opts = '<option value="">Auto (Default Route)</option>';
  12246. if (Array.isArray(state.interfaces)) {
  12247. state.interfaces.forEach(iface => {
  12248. if (iface.name) {
  12249. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12250. }
  12251. });
  12252. }
  12253. if (pingSel) {
  12254. const cur = pingSel.value;
  12255. pingSel.innerHTML = opts;
  12256. if (cur) pingSel.value = cur;
  12257. }
  12258. if (traceSel) {
  12259. const cur = traceSel.value;
  12260. traceSel.innerHTML = opts;
  12261. if (cur) traceSel.value = cur;
  12262. }
  12263. }
  12264. function switchToolsSubTab(subTab) {
  12265. state.activeToolsSubTab = subTab;
  12266. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12267. tabs.forEach(t => {
  12268. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12269. const view = document.getElementById(`tools-view-${t}`);
  12270. if (btn) {
  12271. if (t === subTab) {
  12272. 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';
  12273. } else {
  12274. 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';
  12275. }
  12276. }
  12277. if (view) {
  12278. if (t === subTab) {
  12279. view.classList.remove('hidden');
  12280. } else {
  12281. view.classList.add('hidden');
  12282. }
  12283. }
  12284. });
  12285. }
  12286. function setPortPreset(port) {
  12287. const input = document.getElementById('tools-port-num');
  12288. if (input) input.value = port;
  12289. }
  12290. let pingAbortController = null;
  12291. let tracerouteAbortController = null;
  12292. function clearPingTable() {
  12293. const tbody = document.getElementById('tools-ping-tbody');
  12294. if (tbody) tbody.innerHTML = '';
  12295. const rawEl = document.getElementById('tools-ping-raw');
  12296. if (rawEl) rawEl.innerText = '';
  12297. const sentEl = document.getElementById('tools-ping-stat-sent');
  12298. if (sentEl) sentEl.innerText = '0';
  12299. const recvEl = document.getElementById('tools-ping-stat-recv');
  12300. if (recvEl) recvEl.innerText = '0';
  12301. const lossEl = document.getElementById('tools-ping-stat-loss');
  12302. if (lossEl) lossEl.innerText = '0%';
  12303. const avgEl = document.getElementById('tools-ping-stat-avg');
  12304. if (avgEl) avgEl.innerText = '0 ms';
  12305. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12306. if (minMaxEl) minMaxEl.innerText = '-';
  12307. const badge = document.getElementById('tools-ping-status-badge');
  12308. if (badge) {
  12309. badge.className = '';
  12310. badge.innerText = '';
  12311. }
  12312. }
  12313. function clearTracerouteTable() {
  12314. const tbody = document.getElementById('tools-tr-tbody');
  12315. if (tbody) tbody.innerHTML = '';
  12316. const rawEl = document.getElementById('tools-tr-raw');
  12317. if (rawEl) rawEl.innerText = '';
  12318. const statHops = document.getElementById('tools-tr-hops-count');
  12319. if (statHops) statHops.innerText = '0 Hops';
  12320. }
  12321. function resetPingButton() {
  12322. const btn = document.getElementById('tools-ping-btn');
  12323. const btnText = document.getElementById('tools-ping-btn-text');
  12324. const spinner = document.getElementById('tools-ping-spinner');
  12325. if (btn) {
  12326. btn.disabled = false;
  12327. 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';
  12328. }
  12329. if (btnText) btnText.innerText = 'Start Ping';
  12330. if (spinner) spinner.classList.add('hidden');
  12331. }
  12332. function setPingRunningButton() {
  12333. const btn = document.getElementById('tools-ping-btn');
  12334. const btnText = document.getElementById('tools-ping-btn-text');
  12335. const spinner = document.getElementById('tools-ping-spinner');
  12336. if (btn) {
  12337. btn.disabled = false;
  12338. 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';
  12339. }
  12340. if (btnText) btnText.innerText = 'Stop Ping';
  12341. if (spinner) spinner.classList.remove('hidden');
  12342. }
  12343. function resetTracerouteButton() {
  12344. const btn = document.getElementById('tools-tr-btn');
  12345. const btnText = document.getElementById('tools-tr-btn-text');
  12346. const spinner = document.getElementById('tools-tr-spinner');
  12347. if (btn) {
  12348. btn.disabled = false;
  12349. 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';
  12350. }
  12351. if (btnText) btnText.innerText = 'Start Traceroute';
  12352. if (spinner) spinner.classList.add('hidden');
  12353. }
  12354. function setTracerouteRunningButton() {
  12355. const btn = document.getElementById('tools-tr-btn');
  12356. const btnText = document.getElementById('tools-tr-btn-text');
  12357. const spinner = document.getElementById('tools-tr-spinner');
  12358. if (btn) {
  12359. btn.disabled = false;
  12360. 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';
  12361. }
  12362. if (btnText) btnText.innerText = 'Stop Traceroute';
  12363. if (spinner) spinner.classList.remove('hidden');
  12364. }
  12365. async function executePing(e) {
  12366. if (e) e.preventDefault();
  12367. // If already running, clicking the button stops the stream!
  12368. if (pingAbortController) {
  12369. pingAbortController.abort();
  12370. pingAbortController = null;
  12371. resetPingButton();
  12372. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12373. return;
  12374. }
  12375. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12376. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12377. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12378. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12379. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12380. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12381. if (!target) {
  12382. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12383. return;
  12384. }
  12385. clearPingTable();
  12386. const resCard = document.getElementById('tools-ping-results');
  12387. if (resCard) resCard.classList.remove('hidden');
  12388. pingAbortController = new AbortController();
  12389. setPingRunningButton();
  12390. try {
  12391. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12392. method: 'POST',
  12393. headers: { 'Content-Type': 'application/json' },
  12394. body: JSON.stringify({
  12395. target,
  12396. count,
  12397. size,
  12398. timeout,
  12399. interface: iface,
  12400. dont_frag: dontFrag
  12401. }),
  12402. signal: pingAbortController.signal
  12403. });
  12404. if (!res.ok) {
  12405. const errText = await res.text();
  12406. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12407. resetPingButton();
  12408. pingAbortController = null;
  12409. return;
  12410. }
  12411. const reader = res.body.getReader();
  12412. const decoder = new TextDecoder('utf-8');
  12413. let buffer = '';
  12414. while (true) {
  12415. const { done, value } = await reader.read();
  12416. if (done) break;
  12417. buffer += decoder.decode(value, { stream: true });
  12418. const blocks = buffer.split('\n\n');
  12419. buffer = blocks.pop() || '';
  12420. for (const block of blocks) {
  12421. const trimmed = block.trim();
  12422. if (!trimmed) continue;
  12423. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12424. try {
  12425. const evt = JSON.parse(line);
  12426. handleLivePingEvent(evt);
  12427. } catch (parseErr) {
  12428. console.warn('Ping SSE parse error:', parseErr, line);
  12429. }
  12430. }
  12431. }
  12432. } catch (err) {
  12433. if (err.name === 'AbortError') {
  12434. // User aborted normally
  12435. } else {
  12436. showToast('Ping Error', err.message, 'error');
  12437. }
  12438. } finally {
  12439. pingAbortController = null;
  12440. resetPingButton();
  12441. }
  12442. }
  12443. function handleLivePingEvent(evt) {
  12444. const sentEl = document.getElementById('tools-ping-stat-sent');
  12445. const recvEl = document.getElementById('tools-ping-stat-recv');
  12446. const lossEl = document.getElementById('tools-ping-stat-loss');
  12447. const avgEl = document.getElementById('tools-ping-stat-avg');
  12448. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12449. const badge = document.getElementById('tools-ping-status-badge');
  12450. const tbody = document.getElementById('tools-ping-tbody');
  12451. const rawEl = document.getElementById('tools-ping-raw');
  12452. if (evt.raw && rawEl) {
  12453. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12454. rawEl.scrollTop = rawEl.scrollHeight;
  12455. }
  12456. if (evt.type === 'reply') {
  12457. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12458. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12459. if (lossEl && evt.packet_loss_pct !== undefined) {
  12460. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12461. lossEl.className = evt.packet_loss_pct === 0
  12462. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12463. : (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');
  12464. }
  12465. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12466. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12467. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12468. }
  12469. if (badge) {
  12470. if (evt.packet_loss_pct === 0) {
  12471. 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';
  12472. badge.innerText = '100% OK';
  12473. } else {
  12474. 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';
  12475. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12476. }
  12477. }
  12478. if (tbody) {
  12479. const tr = document.createElement('tr');
  12480. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12481. tr.innerHTML = `
  12482. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12483. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12484. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12485. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12486. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12487. <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>
  12488. `;
  12489. tbody.appendChild(tr);
  12490. }
  12491. } else if (evt.type === 'timeout') {
  12492. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12493. if (lossEl && evt.packet_loss_pct !== undefined) {
  12494. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12495. 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';
  12496. }
  12497. if (badge) {
  12498. 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';
  12499. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12500. }
  12501. if (tbody) {
  12502. const tr = document.createElement('tr');
  12503. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12504. tr.innerHTML = `
  12505. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12506. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12507. <td class="py-2 px-3 text-slate-600">--</td>
  12508. <td class="py-2 px-3 text-slate-600">--</td>
  12509. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12510. <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>
  12511. `;
  12512. tbody.appendChild(tr);
  12513. }
  12514. } else if (evt.type === 'unreach') {
  12515. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12516. if (lossEl && evt.packet_loss_pct !== undefined) {
  12517. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12518. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12519. }
  12520. if (badge) {
  12521. 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';
  12522. badge.innerText = 'UNREACHABLE';
  12523. }
  12524. if (tbody) {
  12525. const tr = document.createElement('tr');
  12526. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12527. tr.innerHTML = `
  12528. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12529. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12530. <td class="py-2 px-3 text-slate-600">--</td>
  12531. <td class="py-2 px-3 text-slate-600">--</td>
  12532. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12533. <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>
  12534. `;
  12535. tbody.appendChild(tr);
  12536. }
  12537. } else if (evt.type === 'stats') {
  12538. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12539. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12540. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12541. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12542. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12543. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12544. }
  12545. } else if (evt.type === 'done') {
  12546. 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');
  12547. }
  12548. }
  12549. async function executeTraceroute(e) {
  12550. if (e) e.preventDefault();
  12551. if (tracerouteAbortController) {
  12552. tracerouteAbortController.abort();
  12553. tracerouteAbortController = null;
  12554. resetTracerouteButton();
  12555. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12556. return;
  12557. }
  12558. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12559. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12560. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12561. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12562. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12563. if (!target) {
  12564. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12565. return;
  12566. }
  12567. clearTracerouteTable();
  12568. const resCard = document.getElementById('tools-tr-results');
  12569. if (resCard) resCard.classList.remove('hidden');
  12570. tracerouteAbortController = new AbortController();
  12571. setTracerouteRunningButton();
  12572. try {
  12573. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12574. method: 'POST',
  12575. headers: { 'Content-Type': 'application/json' },
  12576. body: JSON.stringify({
  12577. target,
  12578. max_hops: maxHops,
  12579. protocol,
  12580. interface: iface,
  12581. resolve
  12582. }),
  12583. signal: tracerouteAbortController.signal
  12584. });
  12585. if (!res.ok) {
  12586. const errText = await res.text();
  12587. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12588. resetTracerouteButton();
  12589. tracerouteAbortController = null;
  12590. return;
  12591. }
  12592. const reader = res.body.getReader();
  12593. const decoder = new TextDecoder('utf-8');
  12594. let buffer = '';
  12595. while (true) {
  12596. const { done, value } = await reader.read();
  12597. if (done) break;
  12598. buffer += decoder.decode(value, { stream: true });
  12599. const blocks = buffer.split('\n\n');
  12600. buffer = blocks.pop() || '';
  12601. for (const block of blocks) {
  12602. const trimmed = block.trim();
  12603. if (!trimmed) continue;
  12604. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12605. try {
  12606. const evt = JSON.parse(line);
  12607. handleLiveTracerouteEvent(evt);
  12608. } catch (parseErr) {
  12609. console.warn('Traceroute SSE parse error:', parseErr, line);
  12610. }
  12611. }
  12612. }
  12613. } catch (err) {
  12614. if (err.name === 'AbortError') {
  12615. // User aborted normally
  12616. } else {
  12617. showToast('Traceroute Error', err.message, 'error');
  12618. }
  12619. } finally {
  12620. tracerouteAbortController = null;
  12621. resetTracerouteButton();
  12622. }
  12623. }
  12624. function handleLiveTracerouteEvent(evt) {
  12625. const statHops = document.getElementById('tools-tr-hops-count');
  12626. const tbody = document.getElementById('tools-tr-tbody');
  12627. const rawEl = document.getElementById('tools-tr-raw');
  12628. if (evt.raw && rawEl) {
  12629. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12630. rawEl.scrollTop = rawEl.scrollHeight;
  12631. }
  12632. if (evt.hops_count !== undefined && statHops) {
  12633. statHops.innerText = `${evt.hops_count} Hops`;
  12634. }
  12635. if (evt.type === 'hop' && evt.hop && tbody) {
  12636. const h = evt.hop;
  12637. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12638. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12639. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12640. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12641. const tr = document.createElement('tr');
  12642. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12643. tr.innerHTML = `
  12644. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12645. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12646. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12647. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12648. <td class="py-2.5 px-3 text-right">
  12649. ${isTimeout
  12650. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12651. : '<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>'}
  12652. </td>
  12653. `;
  12654. tbody.appendChild(tr);
  12655. } else if (evt.type === 'done') {
  12656. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12657. }
  12658. }
  12659. async function executeMTR(e) {
  12660. if (e) e.preventDefault();
  12661. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12662. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12663. if (!target) {
  12664. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12665. return;
  12666. }
  12667. const btn = document.getElementById('tools-mtr-btn');
  12668. const spinner = document.getElementById('tools-mtr-spinner');
  12669. if (btn) btn.disabled = true;
  12670. if (spinner) spinner.classList.remove('hidden');
  12671. try {
  12672. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12673. method: 'POST',
  12674. headers: { 'Content-Type': 'application/json' },
  12675. body: JSON.stringify({ target, count: cycles })
  12676. });
  12677. const data = await res.json();
  12678. if (!res.ok) {
  12679. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12680. return;
  12681. }
  12682. const resCard = document.getElementById('tools-mtr-results');
  12683. if (resCard) resCard.classList.remove('hidden');
  12684. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12685. const statHops = document.getElementById('tools-mtr-hops-count');
  12686. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12687. const tbody = document.getElementById('tools-mtr-tbody');
  12688. if (tbody) {
  12689. if (hopsCount > 0) {
  12690. tbody.innerHTML = data.hops.map(h => {
  12691. 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');
  12692. return `
  12693. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12694. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12695. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12696. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12697. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12698. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12699. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12700. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12701. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12702. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12703. </tr>
  12704. `;
  12705. }).join('');
  12706. } else {
  12707. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12708. }
  12709. }
  12710. const rawEl = document.getElementById('tools-mtr-raw');
  12711. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12712. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12713. } catch (err) {
  12714. showToast('MTR Error', err.message, 'error');
  12715. } finally {
  12716. if (btn) btn.disabled = false;
  12717. if (spinner) spinner.classList.add('hidden');
  12718. }
  12719. }
  12720. async function executeDNS(e) {
  12721. if (e) e.preventDefault();
  12722. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12723. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12724. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12725. if (!domain) {
  12726. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12727. return;
  12728. }
  12729. const btn = document.getElementById('tools-dns-btn');
  12730. const spinner = document.getElementById('tools-dns-spinner');
  12731. if (btn) btn.disabled = true;
  12732. if (spinner) spinner.classList.remove('hidden');
  12733. try {
  12734. const res = await fetch(`${API_BASE}/tools/dns`, {
  12735. method: 'POST',
  12736. headers: { 'Content-Type': 'application/json' },
  12737. body: JSON.stringify({ domain, type, server })
  12738. });
  12739. const data = await res.json();
  12740. if (!res.ok) {
  12741. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12742. return;
  12743. }
  12744. const resCard = document.getElementById('tools-dns-results');
  12745. if (resCard) resCard.classList.remove('hidden');
  12746. const metaEl = document.getElementById('tools-dns-meta');
  12747. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12748. const tbody = document.getElementById('tools-dns-tbody');
  12749. if (tbody) {
  12750. if (Array.isArray(data.records) && data.records.length > 0) {
  12751. tbody.innerHTML = data.records.map(r => `
  12752. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12753. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12754. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12755. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12756. <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>
  12757. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12758. </tr>
  12759. `).join('');
  12760. } else {
  12761. 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>`;
  12762. }
  12763. }
  12764. const rawEl = document.getElementById('tools-dns-raw');
  12765. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12766. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12767. } catch (err) {
  12768. showToast('DNS Error', err.message, 'error');
  12769. } finally {
  12770. if (btn) btn.disabled = false;
  12771. if (spinner) spinner.classList.add('hidden');
  12772. }
  12773. }
  12774. async function executePortProbe(e) {
  12775. if (e) e.preventDefault();
  12776. const target = document.getElementById('tools-port-target')?.value?.trim();
  12777. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12778. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12779. if (!target || !port) {
  12780. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12781. return;
  12782. }
  12783. const btn = document.getElementById('tools-port-btn');
  12784. const spinner = document.getElementById('tools-port-spinner');
  12785. if (btn) btn.disabled = true;
  12786. if (spinner) spinner.classList.remove('hidden');
  12787. try {
  12788. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12789. method: 'POST',
  12790. headers: { 'Content-Type': 'application/json' },
  12791. body: JSON.stringify({ target, port, timeout })
  12792. });
  12793. const data = await res.json();
  12794. if (!res.ok) {
  12795. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12796. return;
  12797. }
  12798. const resCard = document.getElementById('tools-port-results');
  12799. if (resCard) resCard.classList.remove('hidden');
  12800. const banner = document.getElementById('tools-port-banner');
  12801. const icon = document.getElementById('tools-port-icon');
  12802. const title = document.getElementById('tools-port-title');
  12803. const sub = document.getElementById('tools-port-sub');
  12804. const latency = document.getElementById('tools-port-latency');
  12805. if (data.open) {
  12806. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12807. if (icon) {
  12808. 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';
  12809. icon.innerText = '✓';
  12810. }
  12811. if (title) {
  12812. title.className = 'text-sm font-bold text-emerald-300';
  12813. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12814. }
  12815. if (sub) {
  12816. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12817. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12818. }
  12819. if (latency) {
  12820. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12821. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12822. }
  12823. } else {
  12824. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12825. if (icon) {
  12826. 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';
  12827. icon.innerText = '✕';
  12828. }
  12829. if (title) {
  12830. title.className = 'text-sm font-bold text-rose-300';
  12831. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12832. }
  12833. if (sub) {
  12834. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12835. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12836. }
  12837. if (latency) {
  12838. latency.className = 'text-base font-bold font-mono text-slate-500';
  12839. latency.innerText = '--';
  12840. }
  12841. }
  12842. const rawEl = document.getElementById('tools-port-raw');
  12843. 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'}`);
  12844. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12845. } catch (err) {
  12846. showToast('Probe Error', err.message, 'error');
  12847. } finally {
  12848. if (btn) btn.disabled = false;
  12849. if (spinner) spinner.classList.add('hidden');
  12850. }
  12851. }
  12852. // ==========================================
  12853. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12854. // ==========================================
  12855. async function loadDHCPClients(showToastMsg = false) {
  12856. try {
  12857. const [clientsRes, sumRes] = await Promise.all([
  12858. fetch(`${API_BASE}/dhcp/clients`),
  12859. fetch(`${API_BASE}/dhcp/clients/summary`)
  12860. ]);
  12861. if (clientsRes.ok) {
  12862. state.dhcpClients = await clientsRes.json();
  12863. }
  12864. if (sumRes.ok) {
  12865. state.dhcpSummary = await sumRes.json();
  12866. }
  12867. renderDHCPClients();
  12868. updateDHCPSummaryCards();
  12869. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12870. if (bDhcp && state.dhcpSummary) {
  12871. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12872. }
  12873. if (showToastMsg) {
  12874. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12875. }
  12876. } catch (err) {
  12877. console.error('Failed to load DHCP clients:', err);
  12878. if (showToastMsg) {
  12879. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12880. }
  12881. }
  12882. }
  12883. function updateDHCPSummaryCards() {
  12884. const sum = state.dhcpSummary || {
  12885. total_clients: (state.dhcpClients || []).length,
  12886. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12887. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12888. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12889. };
  12890. const totalEl = document.getElementById('dhcp-stat-total');
  12891. const boundEl = document.getElementById('dhcp-stat-bound');
  12892. const searchEl = document.getElementById('dhcp-stat-searching');
  12893. const disEl = document.getElementById('dhcp-stat-disabled');
  12894. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12895. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12896. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12897. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12898. }
  12899. function renderDHCPClients() {
  12900. const tbody = document.getElementById('dhcp-clients-tbody');
  12901. const emptyState = document.getElementById('dhcp-clients-empty');
  12902. if (!tbody) return;
  12903. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12904. if (clients.length === 0) {
  12905. tbody.innerHTML = '';
  12906. if (emptyState) emptyState.classList.remove('hidden');
  12907. return;
  12908. }
  12909. if (emptyState) emptyState.classList.add('hidden');
  12910. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12911. if (tbody.dataset.sig === sig) return;
  12912. tbody.dataset.sig = sig;
  12913. tbody.innerHTML = clients.map(c => {
  12914. let statusBadge = '';
  12915. if (!c.enabled) {
  12916. 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>';
  12917. } else if (c.status === 'bound') {
  12918. 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>';
  12919. } else if (c.status === 'searching') {
  12920. 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>';
  12921. } else if (c.status === 'stopped') {
  12922. 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>';
  12923. } else {
  12924. 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>`;
  12925. }
  12926. 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>';
  12927. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12928. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12929. 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>';
  12930. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12931. // Option flags
  12932. const flags = [];
  12933. 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>');
  12934. 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>');
  12935. 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>');
  12936. 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>`);
  12937. return `
  12938. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12939. <td class="py-3 px-4">
  12940. <div class="flex items-center gap-2">
  12941. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12942. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12943. </div>
  12944. </td>
  12945. <td class="py-3 px-4">${statusBadge}</td>
  12946. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12947. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12948. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12949. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12950. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12951. <td class="py-3 px-4">
  12952. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12953. </td>
  12954. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12955. ${c.enabled ? `
  12956. <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>
  12957. <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>
  12958. <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>
  12959. ` : `
  12960. <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>
  12961. `}
  12962. <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>
  12963. <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>
  12964. </td>
  12965. </tr>
  12966. `;
  12967. }).join('');
  12968. }
  12969. function openDHCPClientModal(clientId = null) {
  12970. const modal = document.getElementById('modal-dhcp-client');
  12971. if (!modal) return;
  12972. const title = document.getElementById('modal-dhcp-title');
  12973. const idInput = document.getElementById('modal-dhcp-id');
  12974. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12975. const distInput = document.getElementById('modal-dhcp-distance');
  12976. const commentInput = document.getElementById('modal-dhcp-comment');
  12977. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12978. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12979. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12980. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12981. // Populate interfaces
  12982. if (ifaceSelect) {
  12983. let opts = '<option value="">Select interface...</option>';
  12984. const allIfaces = state.interfaces || [];
  12985. const allVlans = state.vlans || [];
  12986. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12987. // Group 1: Physical & Bridge Interfaces
  12988. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12989. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12990. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12991. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12992. });
  12993. opts += '</optgroup>';
  12994. // Group 2: VLAN Interfaces
  12995. if (allVlans.length > 0) {
  12996. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12997. allVlans.forEach(v => {
  12998. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12999. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  13000. });
  13001. opts += '</optgroup>';
  13002. }
  13003. ifaceSelect.innerHTML = opts;
  13004. }
  13005. if (clientId) {
  13006. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  13007. if (client) {
  13008. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  13009. if (idInput) idInput.value = client.id;
  13010. if (ifaceSelect) {
  13011. ifaceSelect.value = client.interface;
  13012. ifaceSelect.disabled = true; // interface cannot be changed on edit
  13013. }
  13014. if (distInput) distInput.value = client.default_route_distance || 1;
  13015. if (commentInput) commentInput.value = client.comment || '';
  13016. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  13017. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  13018. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  13019. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  13020. }
  13021. } else {
  13022. if (title) title.innerText = 'Add DHCP Client';
  13023. if (idInput) idInput.value = '';
  13024. if (ifaceSelect) {
  13025. ifaceSelect.value = '';
  13026. ifaceSelect.disabled = false;
  13027. }
  13028. if (distInput) distInput.value = 1;
  13029. if (commentInput) commentInput.value = '';
  13030. if (defRouteCheck) defRouteCheck.checked = true;
  13031. if (peerDnsCheck) peerDnsCheck.checked = true;
  13032. if (peerNtpCheck) peerNtpCheck.checked = true;
  13033. if (enabledCheck) enabledCheck.checked = true;
  13034. }
  13035. modal.classList.remove('hidden');
  13036. }
  13037. function openDHCPClientModalForIface(ifaceName) {
  13038. openDHCPClientModal();
  13039. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13040. if (ifaceSelect && ifaceName) {
  13041. ifaceSelect.value = ifaceName;
  13042. }
  13043. }
  13044. function closeDHCPClientModal() {
  13045. const modal = document.getElementById('modal-dhcp-client');
  13046. if (modal) modal.classList.add('hidden');
  13047. }
  13048. async function submitSaveDHCPClient(e) {
  13049. if (e) e.preventDefault();
  13050. const id = document.getElementById('modal-dhcp-id')?.value;
  13051. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  13052. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  13053. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13054. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13055. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13056. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13057. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13058. if (!id && !iface) {
  13059. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13060. return;
  13061. }
  13062. try {
  13063. let res;
  13064. if (id) {
  13065. // PUT update
  13066. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13067. method: 'PUT',
  13068. headers: { 'Content-Type': 'application/json' },
  13069. body: JSON.stringify({
  13070. enabled,
  13071. add_default_route: defRoute,
  13072. default_route_distance: distance,
  13073. use_peer_dns: peerDns,
  13074. use_peer_ntp: peerNtp,
  13075. comment
  13076. })
  13077. });
  13078. } else {
  13079. // POST create
  13080. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13081. method: 'POST',
  13082. headers: { 'Content-Type': 'application/json' },
  13083. body: JSON.stringify({
  13084. interface: iface,
  13085. enabled,
  13086. add_default_route: defRoute,
  13087. default_route_distance: distance,
  13088. use_peer_dns: peerDns,
  13089. use_peer_ntp: peerNtp,
  13090. comment
  13091. })
  13092. });
  13093. }
  13094. const data = await res.json();
  13095. if (!res.ok) {
  13096. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13097. return;
  13098. }
  13099. closeDHCPClientModal();
  13100. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13101. await loadDHCPClients();
  13102. fetchData(); // refresh interfaces list with new lease/status
  13103. } catch (err) {
  13104. showToast('Error', err.message, 'error');
  13105. }
  13106. }
  13107. async function toggleDHCPClientState(id, enabled) {
  13108. try {
  13109. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13110. method: 'POST',
  13111. headers: { 'Content-Type': 'application/json' },
  13112. body: JSON.stringify({ enabled })
  13113. });
  13114. const data = await res.json();
  13115. if (!res.ok) {
  13116. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13117. return;
  13118. }
  13119. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13120. await loadDHCPClients();
  13121. fetchData();
  13122. } catch (err) {
  13123. showToast('Error', err.message, 'error');
  13124. }
  13125. }
  13126. async function renewDHCPClient(id) {
  13127. try {
  13128. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13129. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13130. method: 'POST'
  13131. });
  13132. const data = await res.json();
  13133. if (!res.ok) {
  13134. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13135. return;
  13136. }
  13137. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13138. setTimeout(() => {
  13139. loadDHCPClients();
  13140. fetchData();
  13141. }, 1500);
  13142. } catch (err) {
  13143. showToast('Error', err.message, 'error');
  13144. }
  13145. }
  13146. async function releaseDHCPClient(id) {
  13147. try {
  13148. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13149. method: 'POST'
  13150. });
  13151. const data = await res.json();
  13152. if (!res.ok) {
  13153. showToast('Error', data.error || 'Failed to release lease', 'error');
  13154. return;
  13155. }
  13156. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13157. await loadDHCPClients();
  13158. fetchData();
  13159. } catch (err) {
  13160. showToast('Error', err.message, 'error');
  13161. }
  13162. }
  13163. async function deleteDHCPClient(id, ifaceName) {
  13164. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13165. return;
  13166. }
  13167. try {
  13168. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13169. method: 'DELETE'
  13170. });
  13171. const data = await res.json();
  13172. if (!res.ok) {
  13173. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13174. return;
  13175. }
  13176. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13177. await loadDHCPClients();
  13178. fetchData();
  13179. } catch (err) {
  13180. showToast('Error', err.message, 'error');
  13181. }
  13182. }
  13183. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13184. async function loadDHCPServer(populate = true) {
  13185. try {
  13186. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13187. fetch(`${API_BASE}/dhcp-server/summary`),
  13188. fetch(`${API_BASE}/dhcp-server/servers`),
  13189. fetch(`${API_BASE}/dhcp-server/networks`),
  13190. fetch(`${API_BASE}/dhcp-server/leases`),
  13191. fetch(`${API_BASE}/dhcp-server/options`)
  13192. ]);
  13193. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13194. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13195. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13196. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13197. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13198. const sum = state.dhcpServerSummary || {};
  13199. const srvs = state.dhcpServers || [];
  13200. const nets = state.dhcpNetworks || [];
  13201. const leases = state.dhcpLeases || [];
  13202. const opts = state.dhcpOptions || [];
  13203. // KPI Cards
  13204. const statActive = document.getElementById('dhcp-server-stat-active');
  13205. if (statActive) {
  13206. const activeCount = srvs.filter(s => s.running).length;
  13207. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13208. }
  13209. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13210. if (statLeases) {
  13211. statLeases.innerText = leases.length;
  13212. }
  13213. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13214. if (statLeasesSub) {
  13215. const dyn = leases.filter(l => l.dynamic).length;
  13216. const st = leases.filter(l => !l.dynamic).length;
  13217. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13218. }
  13219. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13220. if (statNetworks) {
  13221. statNetworks.innerText = nets.length;
  13222. }
  13223. // Subtab Badges
  13224. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13225. if (bSrv) bSrv.innerText = srvs.length;
  13226. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13227. if (bNet) bNet.innerText = nets.length;
  13228. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13229. if (bLease) bLease.innerText = leases.length;
  13230. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13231. if (bOpt) bOpt.innerText = opts.length;
  13232. // Sidebar Badge
  13233. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13234. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13235. renderCurrentDHCPServerTab();
  13236. } catch (err) {
  13237. console.error('Failed to load DHCP Server:', err);
  13238. }
  13239. }
  13240. function switchDHCPServerTab(tab) {
  13241. state.dhcpServerTab = tab;
  13242. const tabs = ['servers', 'networks', 'leases', 'options'];
  13243. tabs.forEach(t => {
  13244. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13245. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13246. if (panel) {
  13247. if (t === tab) panel.classList.remove('hidden');
  13248. else panel.classList.add('hidden');
  13249. }
  13250. if (btn) {
  13251. if (t === tab) {
  13252. 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';
  13253. } else {
  13254. 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';
  13255. }
  13256. }
  13257. });
  13258. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13259. if (addBtn) {
  13260. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13261. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13262. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13263. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13264. }
  13265. renderCurrentDHCPServerTab();
  13266. }
  13267. function handleDHCPServerPrimaryAdd() {
  13268. const tab = state.dhcpServerTab || 'servers';
  13269. if (tab === 'servers') openAddDHCPServerModal();
  13270. else if (tab === 'networks') openAddDHCPNetworkModal();
  13271. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13272. else if (tab === 'options') openAddDHCPOptionModal();
  13273. }
  13274. function renderCurrentDHCPServerTab() {
  13275. const tab = state.dhcpServerTab || 'servers';
  13276. if (tab === 'servers') renderDHCPServers();
  13277. else if (tab === 'networks') renderDHCPNetworks();
  13278. else if (tab === 'leases') renderDHCPLeases();
  13279. else if (tab === 'options') renderDHCPOptions();
  13280. }
  13281. function renderDHCPServers() {
  13282. const tbody = document.getElementById('dhcp-server-tbody');
  13283. const empty = document.getElementById('dhcp-server-empty');
  13284. if (!tbody) return;
  13285. const servers = state.dhcpServers || [];
  13286. if (servers.length === 0) {
  13287. tbody.innerHTML = '';
  13288. empty?.classList.remove('hidden');
  13289. return;
  13290. }
  13291. empty?.classList.add('hidden');
  13292. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13293. if (tbody.dataset.sig === sig) return;
  13294. tbody.dataset.sig = sig;
  13295. tbody.innerHTML = '';
  13296. servers.forEach(s => {
  13297. const tr = document.createElement('tr');
  13298. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13299. tr.innerHTML = `
  13300. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13301. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13302. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13303. <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>
  13304. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13305. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13306. <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>
  13307. <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>
  13308. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13309. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13310. <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>
  13311. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13312. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13313. </td>
  13314. `;
  13315. tbody.appendChild(tr);
  13316. });
  13317. }
  13318. function renderDHCPNetworks() {
  13319. const tbody = document.getElementById('dhcp-networks-tbody');
  13320. const empty = document.getElementById('dhcp-networks-empty');
  13321. if (!tbody) return;
  13322. tbody.innerHTML = '';
  13323. const networks = state.dhcpNetworks || [];
  13324. if (networks.length === 0) {
  13325. empty?.classList.remove('hidden');
  13326. return;
  13327. }
  13328. empty?.classList.add('hidden');
  13329. networks.forEach(n => {
  13330. const tr = document.createElement('tr');
  13331. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13332. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13333. const optionsChips = (n.dhcp_options || []).map(optId => {
  13334. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13335. if (!opt) return '';
  13336. 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>`;
  13337. }).filter(Boolean).join('');
  13338. tr.innerHTML = `
  13339. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13340. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13341. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13342. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13343. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13344. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13345. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13346. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13347. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13348. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13349. </td>
  13350. `;
  13351. tbody.appendChild(tr);
  13352. });
  13353. }
  13354. function renderDHCPLeases() {
  13355. const tbody = document.getElementById('dhcp-leases-tbody');
  13356. const empty = document.getElementById('dhcp-leases-empty');
  13357. if (!tbody) return;
  13358. tbody.innerHTML = '';
  13359. const leases = state.dhcpLeases || [];
  13360. if (leases.length === 0) {
  13361. empty?.classList.remove('hidden');
  13362. return;
  13363. }
  13364. empty?.classList.add('hidden');
  13365. leases.forEach(l => {
  13366. const tr = document.createElement('tr');
  13367. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13368. 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>';
  13369. const statusBadge = l.status === 'bound'
  13370. ? '<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>'
  13371. : l.status === 'static'
  13372. ? '<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>'
  13373. : '<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>';
  13374. const makeStaticBtn = l.dynamic
  13375. ? `<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>`
  13376. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13377. tr.innerHTML = `
  13378. <td class="py-2.5 px-3 text-center">${flag}</td>
  13379. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13380. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13381. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13382. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13383. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13384. <td class="py-2.5 px-3">${statusBadge}</td>
  13385. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13386. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13387. ${makeStaticBtn}
  13388. </td>
  13389. `;
  13390. tbody.appendChild(tr);
  13391. });
  13392. }
  13393. function renderDHCPOptions() {
  13394. const tbody = document.getElementById('dhcp-options-tbody');
  13395. const empty = document.getElementById('dhcp-options-empty');
  13396. if (!tbody) return;
  13397. tbody.innerHTML = '';
  13398. const options = state.dhcpOptions || [];
  13399. if (options.length === 0) {
  13400. empty?.classList.remove('hidden');
  13401. return;
  13402. }
  13403. empty?.classList.add('hidden');
  13404. options.forEach(o => {
  13405. const tr = document.createElement('tr');
  13406. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13407. tr.innerHTML = `
  13408. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13409. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13410. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13411. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13412. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13413. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13414. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13415. </td>
  13416. `;
  13417. tbody.appendChild(tr);
  13418. });
  13419. }
  13420. // ==================== MODALS & ACTIONS: SERVER ====================
  13421. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13422. const sel = document.getElementById(elemId);
  13423. if (!sel) return;
  13424. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13425. const networks = state.dhcpNetworks || [];
  13426. networks.forEach(n => {
  13427. const opt = document.createElement('option');
  13428. opt.value = n.address;
  13429. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13430. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13431. opt.selected = true;
  13432. }
  13433. sel.appendChild(opt);
  13434. });
  13435. }
  13436. function onDHCPServerNetworkChange() {
  13437. const netSel = document.getElementById('dhcp-server-modal-network');
  13438. if (!netSel) return;
  13439. const netVal = netSel.value;
  13440. if (!netVal) return;
  13441. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13442. if (!poolInput) return;
  13443. // Auto-calculate suggested address pool based on subnet CIDR
  13444. const parts = netVal.split('/');
  13445. const ip = parts[0];
  13446. const cidr = parseInt(parts[1] || '24', 10);
  13447. if (cidr === 24) {
  13448. const octets = ip.split('.');
  13449. if (octets.length === 4) {
  13450. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13451. poolInput.value = `${base}.10-${base}.254`;
  13452. }
  13453. }
  13454. }
  13455. function openAddDHCPServerModal() {
  13456. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13457. document.getElementById('dhcp-server-modal-id').value = '';
  13458. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13459. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13460. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13461. document.getElementById('dhcp-server-modal-comment').value = '';
  13462. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13463. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13464. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13465. const networks = state.dhcpNetworks || [];
  13466. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13467. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13468. if (defaultNet) {
  13469. onDHCPServerNetworkChange();
  13470. }
  13471. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13472. }
  13473. function openEditDHCPServerModal(id) {
  13474. const s = (state.dhcpServers || []).find(item => item.id === id);
  13475. if (!s) return;
  13476. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13477. document.getElementById('dhcp-server-modal-id').value = s.id;
  13478. document.getElementById('dhcp-server-modal-name').value = s.name;
  13479. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13480. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13481. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13482. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13483. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13484. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13485. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13486. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13487. }
  13488. function closeDHCPServerModal() {
  13489. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13490. }
  13491. async function submitSaveDHCPServer(e) {
  13492. e.preventDefault();
  13493. const id = document.getElementById('dhcp-server-modal-id').value;
  13494. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13495. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13496. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13497. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13498. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13499. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13500. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13501. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13502. try {
  13503. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13504. method: 'POST',
  13505. headers: { 'Content-Type': 'application/json' },
  13506. body: JSON.stringify({
  13507. id,
  13508. name,
  13509. interface: iface,
  13510. network,
  13511. address_pool: pool,
  13512. lease_time: leaseTime,
  13513. authoritative,
  13514. disabled,
  13515. comment
  13516. })
  13517. });
  13518. if (res.ok) {
  13519. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13520. closeDHCPServerModal();
  13521. loadDHCPServer(false);
  13522. fetchData(false);
  13523. } else {
  13524. const err = await res.text();
  13525. showToast('Error', err, 'error');
  13526. }
  13527. } catch (err) {
  13528. showToast('Error', err.message, 'error');
  13529. }
  13530. }
  13531. async function toggleDHCPServerState(id, disabled) {
  13532. try {
  13533. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13534. method: 'POST',
  13535. headers: { 'Content-Type': 'application/json' },
  13536. body: JSON.stringify({ disabled })
  13537. });
  13538. if (res.ok) {
  13539. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13540. loadDHCPServer(false);
  13541. fetchData(false);
  13542. }
  13543. } catch (err) {
  13544. showToast('Error', err.message, 'error');
  13545. }
  13546. }
  13547. async function deleteDHCPServer(id, name) {
  13548. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13549. try {
  13550. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13551. if (res.ok) {
  13552. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13553. loadDHCPServer(false);
  13554. fetchData(false);
  13555. }
  13556. } catch (err) {
  13557. showToast('Error', err.message, 'error');
  13558. }
  13559. }
  13560. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13561. function openAddDHCPNetworkModal() {
  13562. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13563. document.getElementById('dhcp-network-modal-id').value = '';
  13564. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13565. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13566. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13567. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13568. document.getElementById('dhcp-network-modal-netmask').value = '';
  13569. document.getElementById('dhcp-network-modal-comment').value = '';
  13570. renderDHCPNetworkOptionsCheckboxes([]);
  13571. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13572. }
  13573. function openEditDHCPNetworkModal(id) {
  13574. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13575. if (!n) return;
  13576. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13577. document.getElementById('dhcp-network-modal-id').value = n.id;
  13578. document.getElementById('dhcp-network-modal-address').value = n.address;
  13579. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13580. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13581. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13582. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13583. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13584. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13585. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13586. }
  13587. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13588. const container = document.getElementById('dhcp-network-modal-options-list');
  13589. if (!container) return;
  13590. container.innerHTML = '';
  13591. const opts = state.dhcpOptions || [];
  13592. if (opts.length === 0) {
  13593. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13594. return;
  13595. }
  13596. opts.forEach(o => {
  13597. const isChecked = selectedIds.includes(o.id);
  13598. const label = document.createElement('label');
  13599. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13600. label.innerHTML = `
  13601. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13602. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13603. `;
  13604. container.appendChild(label);
  13605. });
  13606. }
  13607. function closeDHCPNetworkModal() {
  13608. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13609. }
  13610. async function submitSaveDHCPNetwork(e) {
  13611. e.preventDefault();
  13612. const id = document.getElementById('dhcp-network-modal-id').value;
  13613. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13614. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13615. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13616. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13617. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13618. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13619. const selectedOpts = [];
  13620. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13621. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13622. try {
  13623. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13624. method: 'POST',
  13625. headers: { 'Content-Type': 'application/json' },
  13626. body: JSON.stringify({
  13627. id,
  13628. address,
  13629. gateway,
  13630. netmask,
  13631. dns_servers: dnsServers,
  13632. domain,
  13633. dhcp_options: selectedOpts,
  13634. comment
  13635. })
  13636. });
  13637. if (res.ok) {
  13638. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13639. closeDHCPNetworkModal();
  13640. loadDHCPServer(false);
  13641. fetchData(false);
  13642. } else {
  13643. const err = await res.text();
  13644. showToast('Error', err, 'error');
  13645. }
  13646. } catch (err) {
  13647. showToast('Error', err.message, 'error');
  13648. }
  13649. }
  13650. async function deleteDHCPNetwork(id, addr) {
  13651. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13652. try {
  13653. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13654. if (res.ok) {
  13655. showToast('Deleted', `Network ${addr} removed`, 'success');
  13656. loadDHCPServer(false);
  13657. fetchData(false);
  13658. }
  13659. } catch (err) {
  13660. showToast('Error', err.message, 'error');
  13661. }
  13662. }
  13663. // ==================== MODALS & ACTIONS: LEASES ====================
  13664. function openAddDHCPStaticLeaseModal() {
  13665. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13666. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13667. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13668. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13669. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13670. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13671. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13672. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13673. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13674. }
  13675. function closeDHCPStaticLeaseModal() {
  13676. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13677. }
  13678. async function submitSaveDHCPStaticLease(e) {
  13679. e.preventDefault();
  13680. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13681. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13682. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13683. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13684. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13685. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13686. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13687. try {
  13688. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13689. method: 'POST',
  13690. headers: { 'Content-Type': 'application/json' },
  13691. body: JSON.stringify({
  13692. id,
  13693. mac_address: mac,
  13694. address: ip,
  13695. hostname,
  13696. server,
  13697. comment,
  13698. disabled
  13699. })
  13700. });
  13701. if (res.ok) {
  13702. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13703. closeDHCPStaticLeaseModal();
  13704. loadDHCPServer(false);
  13705. fetchData(false);
  13706. } else {
  13707. const err = await res.text();
  13708. showToast('Error', err, 'error');
  13709. }
  13710. } catch (err) {
  13711. showToast('Error', err.message, 'error');
  13712. }
  13713. }
  13714. async function deleteDHCPStaticLease(id) {
  13715. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13716. try {
  13717. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13718. if (res.ok) {
  13719. showToast('Deleted', 'Static lease removed', 'success');
  13720. loadDHCPServer(false);
  13721. fetchData(false);
  13722. }
  13723. } catch (err) {
  13724. showToast('Error', err.message, 'error');
  13725. }
  13726. }
  13727. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13728. try {
  13729. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13730. method: 'POST',
  13731. headers: { 'Content-Type': 'application/json' },
  13732. body: JSON.stringify({
  13733. mac_address: mac,
  13734. address: ip,
  13735. hostname,
  13736. comment: comment || 'Converted to static'
  13737. })
  13738. });
  13739. if (res.ok) {
  13740. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13741. loadDHCPServer(false);
  13742. fetchData(false);
  13743. } else {
  13744. const err = await res.text();
  13745. showToast('Error', err, 'error');
  13746. }
  13747. } catch (err) {
  13748. showToast('Error', err.message, 'error');
  13749. }
  13750. }
  13751. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13752. function openAddDHCPOptionModal() {
  13753. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13754. document.getElementById('dhcp-option-modal-id').value = '';
  13755. document.getElementById('dhcp-option-modal-name').value = '';
  13756. document.getElementById('dhcp-option-modal-code').value = '';
  13757. document.getElementById('dhcp-option-modal-value').value = '';
  13758. document.getElementById('dhcp-option-modal-comment').value = '';
  13759. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13760. }
  13761. function openEditDHCPOptionModal(id) {
  13762. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13763. if (!o) return;
  13764. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13765. document.getElementById('dhcp-option-modal-id').value = o.id;
  13766. document.getElementById('dhcp-option-modal-name').value = o.name;
  13767. document.getElementById('dhcp-option-modal-code').value = o.code;
  13768. document.getElementById('dhcp-option-modal-value').value = o.value;
  13769. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13770. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13771. }
  13772. function closeDHCPOptionModal() {
  13773. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13774. }
  13775. async function submitSaveDHCPOption(e) {
  13776. e.preventDefault();
  13777. const id = document.getElementById('dhcp-option-modal-id').value;
  13778. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13779. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13780. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13781. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13782. try {
  13783. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13784. method: 'POST',
  13785. headers: { 'Content-Type': 'application/json' },
  13786. body: JSON.stringify({ id, name, code, value, comment })
  13787. });
  13788. if (res.ok) {
  13789. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13790. closeDHCPOptionModal();
  13791. loadDHCPServer(false);
  13792. fetchData(false);
  13793. } else {
  13794. const err = await res.text();
  13795. showToast('Error', err, 'error');
  13796. }
  13797. } catch (err) {
  13798. showToast('Error', err.message, 'error');
  13799. }
  13800. }
  13801. async function deleteDHCPOption(id, name) {
  13802. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13803. try {
  13804. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13805. if (res.ok) {
  13806. showToast('Deleted', `Option ${name} removed`, 'success');
  13807. loadDHCPServer(false);
  13808. fetchData(false);
  13809. }
  13810. } catch (err) {
  13811. showToast('Error', err.message, 'error');
  13812. }
  13813. }
  13814. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13815. function openDHCPServerSetupModal() {
  13816. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13817. onDHCPWizardIfaceChange();
  13818. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13819. }
  13820. function closeDHCPServerSetupModal() {
  13821. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13822. }
  13823. function onDHCPWizardIfaceChange() {
  13824. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13825. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13826. let ip = '192.168.88.1';
  13827. let prefix = '24';
  13828. if (iface && iface.ip_address) {
  13829. const parts = iface.ip_address.split('/');
  13830. ip = parts[0];
  13831. if (parts.length > 1) prefix = parts[1];
  13832. }
  13833. // Calculate subnet base (e.g. 192.168.88.0/24)
  13834. const ipParts = ip.split('.');
  13835. if (ipParts.length === 4) {
  13836. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13837. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13838. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13839. document.getElementById('dhcp-wizard-gateway').value = ip;
  13840. document.getElementById('dhcp-wizard-pool').value = pool;
  13841. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13842. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13843. }
  13844. }
  13845. async function submitDHCPServerSetupWizard(e) {
  13846. e.preventDefault();
  13847. const iface = document.getElementById('dhcp-wizard-iface').value;
  13848. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13849. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13850. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13851. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13852. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13853. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13854. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13855. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13856. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13857. try {
  13858. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13859. method: 'POST',
  13860. headers: { 'Content-Type': 'application/json' },
  13861. body: JSON.stringify({
  13862. interface: iface,
  13863. address_space: space,
  13864. gateway: gw,
  13865. address_pool: pool,
  13866. dns_servers: dnsServers,
  13867. lease_time: leaseTime,
  13868. ntp_servers: ntpServers,
  13869. next_server: tftp
  13870. })
  13871. });
  13872. if (res.ok) {
  13873. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13874. closeDHCPServerSetupModal();
  13875. loadDHCPServer(false);
  13876. fetchData(false);
  13877. } else {
  13878. const err = await res.text();
  13879. showToast('Error', err, 'error');
  13880. }
  13881. } catch (err) {
  13882. showToast('Error', err.message, 'error');
  13883. }
  13884. }
  13885. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13886. const sel = document.getElementById(elemId);
  13887. if (!sel) return;
  13888. sel.innerHTML = '<option value="">Select interface...</option>';
  13889. const ifaces = state.interfaces || [];
  13890. ifaces.forEach(i => {
  13891. if (i.name === 'lo') return;
  13892. const opt = document.createElement('option');
  13893. opt.value = i.name;
  13894. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13895. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13896. if (i.name === selectedVal) opt.selected = true;
  13897. sel.appendChild(opt);
  13898. });
  13899. }
  13900. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13901. function initTableSorting() {
  13902. document.querySelectorAll('table').forEach(setupSortableTable);
  13903. }
  13904. function setupSortableTable(table) {
  13905. const thead = table.querySelector('thead');
  13906. const tbody = table.querySelector('tbody');
  13907. if (!thead || !tbody) return;
  13908. const headerRows = thead.querySelectorAll('tr');
  13909. if (headerRows.length === 0) return;
  13910. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13911. ths.forEach((th, colIdx) => {
  13912. if (th._sortBound) return;
  13913. th._sortBound = true;
  13914. const rawText = th.innerText.trim().toLowerCase();
  13915. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13916. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13917. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13918. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13919. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13920. return;
  13921. }
  13922. th.classList.add('table-sortable', 'group');
  13923. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13924. let icon = th.querySelector('.table-sort-icon');
  13925. if (!icon) {
  13926. icon = document.createElement('span');
  13927. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13928. icon.innerHTML = '⇅';
  13929. th.appendChild(icon);
  13930. }
  13931. th.addEventListener('click', (e) => {
  13932. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13933. handleHeaderClick(table, th, colIdx);
  13934. });
  13935. });
  13936. if (!tbody._sortObserved) {
  13937. tbody._sortObserved = true;
  13938. let sortDebounceTimer = null;
  13939. const observer = new MutationObserver((mutations) => {
  13940. if (tbody._isSorting) return;
  13941. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13942. if (!hasChildChanges) return;
  13943. clearTimeout(sortDebounceTimer);
  13944. sortDebounceTimer = setTimeout(() => {
  13945. if (tbody._isSorting) return;
  13946. if (table._activeSort && table._activeSort.dir !== 'none') {
  13947. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13948. } else {
  13949. tagOriginalRowOrder(tbody);
  13950. }
  13951. }, 50);
  13952. });
  13953. tbody._sortObserver = observer;
  13954. observer.observe(tbody, { childList: true });
  13955. }
  13956. tagOriginalRowOrder(tbody);
  13957. }
  13958. function tagOriginalRowOrder(tbody) {
  13959. let idx = 0;
  13960. Array.from(tbody.children).forEach(tr => {
  13961. if (!tr.querySelector('td[colspan]')) {
  13962. if (!tr.hasAttribute('data-orig-idx')) {
  13963. tr.setAttribute('data-orig-idx', idx++);
  13964. }
  13965. }
  13966. });
  13967. }
  13968. function handleHeaderClick(table, th, colIdx) {
  13969. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13970. let newDir = 'asc';
  13971. if (currentSort.colIdx === colIdx) {
  13972. if (currentSort.dir === 'asc') newDir = 'desc';
  13973. else if (currentSort.dir === 'desc') newDir = 'none';
  13974. else newDir = 'asc';
  13975. } else {
  13976. newDir = 'asc';
  13977. }
  13978. table._activeSort = { colIdx, dir: newDir };
  13979. updateHeaderIcons(table, colIdx, newDir);
  13980. applyTableSort(table, colIdx, newDir, true);
  13981. }
  13982. function updateHeaderIcons(table, activeColIdx, dir) {
  13983. const thead = table.querySelector('thead');
  13984. if (!thead) return;
  13985. const ths = thead.querySelectorAll('th');
  13986. ths.forEach((th, idx) => {
  13987. const icon = th.querySelector('.table-sort-icon');
  13988. if (!icon) return;
  13989. if (idx === activeColIdx && dir !== 'none') {
  13990. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13991. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13992. th.classList.add('table-sorted-active');
  13993. } else {
  13994. icon.innerHTML = '⇅';
  13995. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13996. th.classList.remove('table-sorted-active');
  13997. }
  13998. });
  13999. }
  14000. function applyTableSort(table, colIdx, dir, userInitiated) {
  14001. const tbody = table.querySelector('tbody');
  14002. if (!tbody || tbody.children.length <= 1) return;
  14003. tbody._isSorting = true;
  14004. tagOriginalRowOrder(tbody);
  14005. // Group parent rows and any attached drawer/sub-rows
  14006. const groups = [];
  14007. let currentGroup = null;
  14008. Array.from(tbody.children).forEach(tr => {
  14009. if (tr.querySelector('td[colspan]')) {
  14010. if (currentGroup) {
  14011. currentGroup.subRows.push(tr);
  14012. } else {
  14013. groups.push({ mainRow: tr, subRows: [] });
  14014. }
  14015. } else {
  14016. currentGroup = { mainRow: tr, subRows: [] };
  14017. groups.push(currentGroup);
  14018. }
  14019. });
  14020. if (dir === 'none') {
  14021. groups.sort((a, b) => {
  14022. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14023. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14024. return idxA - idxB;
  14025. });
  14026. } else {
  14027. groups.sort((a, b) => {
  14028. const cellA = a.mainRow.children[colIdx];
  14029. const cellB = b.mainRow.children[colIdx];
  14030. const res = compareTableCells(cellA, cellB);
  14031. return dir === 'asc' ? res : -res;
  14032. });
  14033. }
  14034. // Check if rows are already in correct order to avoid modifying DOM
  14035. let alreadyOrdered = true;
  14036. let childIdx = 0;
  14037. for (const g of groups) {
  14038. if (tbody.children[childIdx] !== g.mainRow) {
  14039. alreadyOrdered = false;
  14040. break;
  14041. }
  14042. childIdx++;
  14043. for (const sub of g.subRows) {
  14044. if (tbody.children[childIdx] !== sub) {
  14045. alreadyOrdered = false;
  14046. break;
  14047. }
  14048. childIdx++;
  14049. }
  14050. }
  14051. if (alreadyOrdered) {
  14052. tbody._isSorting = false;
  14053. return;
  14054. }
  14055. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14056. if (tbody._sortObserver) {
  14057. tbody._sortObserver.disconnect();
  14058. }
  14059. // Re-append rows in sorted order
  14060. groups.forEach(g => {
  14061. tbody.appendChild(g.mainRow);
  14062. g.subRows.forEach(sub => tbody.appendChild(sub));
  14063. });
  14064. // Drain any queued mutations and re-connect observer
  14065. if (tbody._sortObserver) {
  14066. tbody._sortObserver.takeRecords();
  14067. tbody._sortObserver.observe(tbody, { childList: true });
  14068. }
  14069. tbody._isSorting = false;
  14070. }
  14071. function getCellRawText(cell) {
  14072. if (!cell) return '';
  14073. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14074. const input = cell.querySelector('input, select');
  14075. if (input) {
  14076. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14077. return input.value;
  14078. }
  14079. return cell.innerText.trim();
  14080. }
  14081. function parseTrafficToNumber(str) {
  14082. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14083. if (!m) return null;
  14084. const num = parseFloat(m[1].replace(/,/g, ''));
  14085. if (isNaN(num)) return null;
  14086. const unit = m[2].toUpperCase();
  14087. let mult = 1;
  14088. if (unit.startsWith('K')) mult = 1024;
  14089. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14090. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14091. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14092. return num * mult;
  14093. }
  14094. function parseIpToNumber(str) {
  14095. const clean = str.replace(/^[!~]/, '').trim();
  14096. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14097. if (!m) return null;
  14098. const o1 = parseInt(m[1], 10);
  14099. const o2 = parseInt(m[2], 10);
  14100. const o3 = parseInt(m[3], 10);
  14101. const o4 = parseInt(m[4], 10);
  14102. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14103. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14104. }
  14105. function parseCompoundPackets(str) {
  14106. const m = str.match(/^([\d,]+)p/);
  14107. if (!m) return null;
  14108. return parseInt(m[1].replace(/,/g, ''), 10);
  14109. }
  14110. function compareTableCells(cellA, cellB) {
  14111. const a = getCellRawText(cellA);
  14112. const b = getCellRawText(cellB);
  14113. if (a === '' && b !== '') return 1;
  14114. if (b === '' && a !== '') return -1;
  14115. if (a === b) return 0;
  14116. // 1. IP Addresses / CIDR
  14117. const ipA = parseIpToNumber(a);
  14118. const ipB = parseIpToNumber(b);
  14119. if (ipA !== null && ipB !== null) return ipA - ipB;
  14120. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14121. const pktA = parseCompoundPackets(a);
  14122. const pktB = parseCompoundPackets(b);
  14123. if (pktA !== null && pktB !== null) return pktA - pktB;
  14124. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14125. const trafA = parseTrafficToNumber(a);
  14126. const trafB = parseTrafficToNumber(b);
  14127. if (trafA !== null && trafB !== null) return trafA - trafB;
  14128. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14129. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14130. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14131. const numA = Number(cleanNumA);
  14132. const numB = Number(cleanNumB);
  14133. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14134. return numA - numB;
  14135. }
  14136. // 5. Natural case-insensitive string compare
  14137. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14138. }
  14139. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14140. async function loadVRRP(showToastNotification = false) {
  14141. try {
  14142. const [instRes, sumRes] = await Promise.all([
  14143. fetch(`${API_BASE}/vrrp/instances`),
  14144. fetch(`${API_BASE}/vrrp/summary`)
  14145. ]);
  14146. if (instRes.ok) {
  14147. state.vrrpInstances = await instRes.json();
  14148. renderVRRP();
  14149. }
  14150. if (sumRes.ok) {
  14151. state.vrrpSummary = await sumRes.json();
  14152. renderVRRPSummary();
  14153. }
  14154. if (showToastNotification) {
  14155. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14156. }
  14157. } catch (err) {
  14158. console.error('Failed to load VRRP:', err);
  14159. }
  14160. }
  14161. function renderVRRPSummary() {
  14162. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14163. const elTotal = document.getElementById('vrrp-stat-total');
  14164. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14165. const elMaster = document.getElementById('vrrp-stat-master');
  14166. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14167. const elBackup = document.getElementById('vrrp-stat-backup');
  14168. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14169. const bCount = document.getElementById('badge-vrrp-count');
  14170. if (bCount) bCount.innerText = s.total_instances || 0;
  14171. const dot = document.getElementById('badge-vrrp-dot');
  14172. if (dot) {
  14173. if (s.master_instances > 0) {
  14174. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14175. } else if (s.backup_instances > 0) {
  14176. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14177. } else {
  14178. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14179. }
  14180. }
  14181. }
  14182. function renderVRRP() {
  14183. const tbody = document.getElementById('vrrp-table-tbody');
  14184. const empty = document.getElementById('vrrp-table-empty');
  14185. if (!tbody) return;
  14186. tbody.innerHTML = '';
  14187. const instances = state.vrrpInstances || [];
  14188. if (instances.length === 0) {
  14189. empty?.classList.remove('hidden');
  14190. return;
  14191. }
  14192. empty?.classList.add('hidden');
  14193. instances.forEach(inst => {
  14194. const tr = document.createElement('tr');
  14195. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14196. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14197. 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>`;
  14198. if (inst.disabled) {
  14199. 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>`;
  14200. } else if (inst.state === 'MASTER') {
  14201. 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>`;
  14202. } else if (inst.state === 'BACKUP') {
  14203. 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>`;
  14204. } else if (inst.state === 'FAULT') {
  14205. 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>`;
  14206. }
  14207. // Render State Badge
  14208. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14209. if (!inst.disabled) {
  14210. if (inst.state === 'MASTER') {
  14211. 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>`;
  14212. } else if (inst.state === 'BACKUP') {
  14213. 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>`;
  14214. } else if (inst.state === 'FAULT') {
  14215. 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>`;
  14216. }
  14217. }
  14218. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14219. tr.innerHTML = `
  14220. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14221. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14222. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14223. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14224. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14225. <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>
  14226. <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>
  14227. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14228. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14229. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14230. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14231. <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>
  14232. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14233. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14234. </td>
  14235. `;
  14236. tbody.appendChild(tr);
  14237. });
  14238. }
  14239. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14240. const sel = document.getElementById(elemId);
  14241. if (!sel) return;
  14242. sel.innerHTML = '<option value="">Select interface...</option>';
  14243. const ifaces = state.interfaces || [];
  14244. ifaces.forEach(i => {
  14245. const opt = document.createElement('option');
  14246. opt.value = i.name;
  14247. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14248. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14249. sel.appendChild(opt);
  14250. });
  14251. }
  14252. function openAddVRRPModal() {
  14253. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14254. document.getElementById('modal-vrrp-id').value = '';
  14255. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14256. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14257. document.getElementById('modal-vrrp-priority').value = 100;
  14258. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14259. document.getElementById('modal-vrrp-version').value = '3';
  14260. document.getElementById('modal-vrrp-interval').value = 1;
  14261. document.getElementById('modal-vrrp-authtype').value = 'none';
  14262. document.getElementById('modal-vrrp-authpass').value = '';
  14263. document.getElementById('modal-vrrp-comment').value = '';
  14264. document.getElementById('modal-vrrp-preempt').checked = true;
  14265. document.getElementById('modal-vrrp-disabled').checked = false;
  14266. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14267. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14268. }
  14269. function openEditVRRPModal(id) {
  14270. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14271. if (!inst) return;
  14272. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14273. document.getElementById('modal-vrrp-id').value = inst.id;
  14274. document.getElementById('modal-vrrp-name').value = inst.name;
  14275. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14276. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14277. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14278. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14279. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14280. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14281. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14282. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14283. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14284. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14285. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14286. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14287. }
  14288. function closeVRRPModal() {
  14289. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14290. }
  14291. async function submitSaveVRRP(e) {
  14292. e.preventDefault();
  14293. const id = document.getElementById('modal-vrrp-id').value;
  14294. const name = document.getElementById('modal-vrrp-name').value.trim();
  14295. const iface = document.getElementById('modal-vrrp-iface').value;
  14296. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14297. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14298. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14299. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14300. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14301. const authType = document.getElementById('modal-vrrp-authtype').value;
  14302. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14303. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14304. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14305. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14306. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14307. try {
  14308. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14309. method: 'POST',
  14310. headers: { 'Content-Type': 'application/json' },
  14311. body: JSON.stringify({
  14312. id,
  14313. name,
  14314. interface: iface,
  14315. vrid,
  14316. priority,
  14317. virtual_ips: vips,
  14318. version,
  14319. interval,
  14320. auth_type: authType,
  14321. auth_password: authPass,
  14322. comment,
  14323. preempt,
  14324. disabled
  14325. })
  14326. });
  14327. if (res.ok) {
  14328. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14329. closeVRRPModal();
  14330. loadVRRP(false);
  14331. fetchData(false);
  14332. } else {
  14333. const err = await res.text();
  14334. showToast('Error', err, 'error');
  14335. }
  14336. } catch (err) {
  14337. showToast('Error', err.message, 'error');
  14338. }
  14339. }
  14340. async function deleteVRRP(id, name) {
  14341. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14342. try {
  14343. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14344. if (res.ok) {
  14345. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14346. loadVRRP(false);
  14347. fetchData(false);
  14348. } else {
  14349. const err = await res.text();
  14350. showToast('Error', err, 'error');
  14351. }
  14352. } catch (err) {
  14353. showToast('Error', err.message, 'error');
  14354. }
  14355. }
  14356. async function toggleVRRPState(id, disabled) {
  14357. try {
  14358. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14359. method: 'POST',
  14360. headers: { 'Content-Type': 'application/json' },
  14361. body: JSON.stringify({ disabled })
  14362. });
  14363. if (res.ok) {
  14364. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14365. loadVRRP(false);
  14366. fetchData(false);
  14367. } else {
  14368. const err = await res.text();
  14369. showToast('Error', err, 'error');
  14370. }
  14371. } catch (err) {
  14372. showToast('Error', err.message, 'error');
  14373. }
  14374. }
  14375. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14376. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14377. let docSortDebounce = null;
  14378. const docTableObserver = new MutationObserver((mutations) => {
  14379. let needsInit = false;
  14380. for (const m of mutations) {
  14381. for (const node of m.addedNodes) {
  14382. if (node.nodeType === 1) {
  14383. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14384. needsInit = true;
  14385. break;
  14386. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14387. needsInit = true;
  14388. break;
  14389. }
  14390. }
  14391. }
  14392. if (needsInit) break;
  14393. }
  14394. if (needsInit) {
  14395. clearTimeout(docSortDebounce);
  14396. docSortDebounce = setTimeout(initTableSorting, 100);
  14397. }
  14398. });
  14399. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14400. }
  14401. // =========================================================================
  14402. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14403. // =========================================================================
  14404. const bwtestState = {
  14405. running: false,
  14406. pollTimer: null,
  14407. eventSource: null,
  14408. chartPoints: [],
  14409. maxChartPoints: 60,
  14410. serverConfig: null,
  14411. peakTx: 0,
  14412. peakRx: 0,
  14413. targetDuration: 10,
  14414. lastSampleElapsed: -1,
  14415. sessionID: null
  14416. };
  14417. async function loadBwTestView() {
  14418. resizeBwTestCanvas();
  14419. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14420. }
  14421. async function fetchBwTestServerStatus() {
  14422. try {
  14423. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14424. if (!res.ok) return;
  14425. const s = await res.json();
  14426. bwtestState.serverConfig = s;
  14427. // Update indicator and badges
  14428. const indicator = document.getElementById('bwtest-server-indicator');
  14429. const badge = document.getElementById('bwtest-server-badge');
  14430. const sideBadge = document.getElementById('badge-bwtest-server');
  14431. if (s.enabled && s.running) {
  14432. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14433. if (badge) {
  14434. badge.innerText = `Port ${s.port} (Active)`;
  14435. badge.className = 'text-emerald-400 font-bold';
  14436. }
  14437. if (sideBadge) {
  14438. sideBadge.innerText = s.port;
  14439. 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';
  14440. }
  14441. } else {
  14442. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14443. if (badge) {
  14444. badge.innerText = `Disabled`;
  14445. badge.className = 'text-slate-500 font-bold';
  14446. }
  14447. if (sideBadge) {
  14448. sideBadge.innerText = 'Off';
  14449. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14450. }
  14451. }
  14452. // Modal fields
  14453. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14454. const serverModal = document.getElementById('modal-bwtest-server');
  14455. const editing = serverModal && !serverModal.classList.contains('hidden');
  14456. if (toggle && !editing) toggle.checked = !!s.enabled;
  14457. const portInp = document.getElementById('bwtest-server-port-input');
  14458. if (portInp && !editing) portInp.value = s.port || 2000;
  14459. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14460. if (actSess) actSess.innerText = s.active_sessions || 0;
  14461. const totServ = document.getElementById('bwtest-modal-total-served');
  14462. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14463. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14464. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14465. } catch (err) {
  14466. console.error('Failed to fetch BwTest server status:', err);
  14467. }
  14468. }
  14469. function openBwTestServerModal() {
  14470. const cfg = bwtestState.serverConfig;
  14471. if (cfg) {
  14472. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14473. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14474. }
  14475. fetchBwTestServerStatus();
  14476. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14477. }
  14478. function closeBwTestServerModal() {
  14479. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14480. }
  14481. async function submitBwTestServerSettings(e) {
  14482. e.preventDefault();
  14483. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14484. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14485. try {
  14486. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14487. method: 'POST',
  14488. headers: { 'Content-Type': 'application/json' },
  14489. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14490. });
  14491. if (!res.ok) {
  14492. const err = await res.json();
  14493. throw new Error(err.error || 'Failed to update server configuration');
  14494. }
  14495. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14496. closeBwTestServerModal();
  14497. fetchBwTestServerStatus();
  14498. } catch (err) {
  14499. showToast('Server Configuration Error', err.message, 'error');
  14500. }
  14501. }
  14502. function setBwTestTarget(target) {
  14503. const inp = document.getElementById('bwtest-input-target');
  14504. if (inp) inp.value = target;
  14505. }
  14506. function setBwTestProtocol(proto) {
  14507. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14508. if (hiddenInp) hiddenInp.value = proto;
  14509. const btnUdp = document.getElementById('bwtest-proto-udp');
  14510. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14511. const badge = document.getElementById('bwtest-proto-badge');
  14512. const pktField = document.getElementById('bwtest-field-pktsize');
  14513. 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';
  14514. 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';
  14515. 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';
  14516. if (proto === 'udp') {
  14517. if (btnUdp) {
  14518. btnUdp.className = activeUdpCls;
  14519. const dot = btnUdp.querySelector('span');
  14520. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14521. }
  14522. if (btnTcp) {
  14523. btnTcp.className = inactiveCls;
  14524. const dot = btnTcp.querySelector('span');
  14525. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14526. }
  14527. if (badge) {
  14528. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14529. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14530. }
  14531. if (pktField) pktField.classList.remove('opacity-40');
  14532. } else {
  14533. if (btnUdp) {
  14534. btnUdp.className = inactiveCls;
  14535. const dot = btnUdp.querySelector('span');
  14536. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14537. }
  14538. if (btnTcp) {
  14539. btnTcp.className = activeTcpCls;
  14540. const dot = btnTcp.querySelector('span');
  14541. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14542. }
  14543. if (badge) {
  14544. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14545. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14546. }
  14547. if (pktField) pktField.classList.add('opacity-40');
  14548. }
  14549. }
  14550. function setBwTestDirection(dir) {
  14551. const hiddenInp = document.getElementById('bwtest-input-direction');
  14552. if (hiddenInp) hiddenInp.value = dir;
  14553. const btnBoth = document.getElementById('bwtest-dir-both');
  14554. const btnTx = document.getElementById('bwtest-dir-tx');
  14555. const btnRx = document.getElementById('bwtest-dir-rx');
  14556. 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';
  14557. 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';
  14558. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14559. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14560. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14561. }
  14562. function setBwTestLimit(bps) {
  14563. const sel = document.getElementById('bwtest-input-limit');
  14564. if (sel) sel.value = String(bps);
  14565. }
  14566. async function checkActiveBwTest() {
  14567. try {
  14568. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14569. if (!res.ok) return;
  14570. const st = await res.json();
  14571. if (st.running) {
  14572. setBwTestRunningUI(true);
  14573. processBwTestStatus(st);
  14574. startBwTestTelemetry();
  14575. }
  14576. } catch (err) {
  14577. console.error('Failed to check active BwTest:', err);
  14578. }
  14579. }
  14580. async function startBwTest(e) {
  14581. if (e && e.preventDefault) e.preventDefault();
  14582. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14583. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14584. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14585. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14586. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14587. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14588. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14589. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14590. bwtestState.targetDuration = duration;
  14591. bwtestState.chartPoints = [];
  14592. bwtestState.peakTx = 0;
  14593. bwtestState.peakRx = 0;
  14594. bwtestState.lastSampleElapsed = -1;
  14595. bwtestState.sessionID = null;
  14596. // Clear UI elements
  14597. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14598. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14599. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14600. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14601. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14602. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14603. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14604. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14605. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14606. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14607. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14608. const tbody = document.getElementById('bwtest-samples-tbody');
  14609. if (tbody) tbody.innerHTML = '';
  14610. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14611. setBwTestRunningUI(true);
  14612. try {
  14613. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14614. method: 'POST',
  14615. headers: { 'Content-Type': 'application/json' },
  14616. body: JSON.stringify({
  14617. target,
  14618. port,
  14619. direction,
  14620. protocol,
  14621. bandwidth_limit,
  14622. packet_size,
  14623. streams,
  14624. duration
  14625. })
  14626. });
  14627. if (!res.ok) {
  14628. const err = await res.json();
  14629. throw new Error(err.error || 'Failed to start bandwidth test');
  14630. }
  14631. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14632. startBwTestTelemetry();
  14633. } catch (err) {
  14634. setBwTestRunningUI(false);
  14635. showToast('Start Failed', err.message, 'error');
  14636. }
  14637. }
  14638. function setBwTestRunningUI(running) {
  14639. bwtestState.running = running;
  14640. const startBtn = document.getElementById('bwtest-btn-start');
  14641. const stopBtn = document.getElementById('bwtest-btn-stop');
  14642. const badge = document.getElementById('bwtest-run-status-badge');
  14643. const ph = document.getElementById('bwtest-chart-placeholder');
  14644. if (running) {
  14645. if (startBtn) {
  14646. startBtn.disabled = true;
  14647. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14648. }
  14649. if (stopBtn) {
  14650. stopBtn.disabled = false;
  14651. stopBtn.classList.remove('opacity-40');
  14652. }
  14653. if (badge) {
  14654. badge.innerText = 'TESTING...';
  14655. 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';
  14656. }
  14657. if (ph) ph.style.display = 'none';
  14658. } else {
  14659. if (startBtn) {
  14660. startBtn.disabled = false;
  14661. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14662. }
  14663. if (stopBtn) {
  14664. stopBtn.disabled = true;
  14665. stopBtn.classList.add('opacity-40');
  14666. }
  14667. if (badge) {
  14668. badge.innerText = 'IDLE';
  14669. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14670. }
  14671. }
  14672. }
  14673. async function stopBwTest() {
  14674. try {
  14675. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14676. if (!res.ok) throw new Error(await responseError(res));
  14677. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14678. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14679. } catch (err) {
  14680. showToast('Stop Failed', err.message, 'error');
  14681. }
  14682. }
  14683. async function responseError(res) {
  14684. const text = await res.text();
  14685. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14686. catch { return text || `HTTP ${res.status}`; }
  14687. }
  14688. function processBwTestStatus(st) {
  14689. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14690. bwtestState.sessionID = st.session_id;
  14691. bwtestState.lastSampleElapsed = -1;
  14692. }
  14693. for (const sample of st.recent_samples || []) {
  14694. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14695. handleBwTestSample(sample);
  14696. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14697. }
  14698. }
  14699. if (!st.running) {
  14700. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14701. bwtestState.pollTimer = null;
  14702. setBwTestRunningUI(false);
  14703. handleBwTestFinish(st.summary, st.error);
  14704. }
  14705. }
  14706. function startBwTestTelemetry() {
  14707. if (!state.currentUser) return;
  14708. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14709. let busy = false;
  14710. const poll = async () => {
  14711. if (busy || !state.currentUser || document.hidden) return;
  14712. busy = true;
  14713. try {
  14714. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14715. if (!res.ok) throw new Error(await responseError(res));
  14716. processBwTestStatus(await res.json());
  14717. } catch (err) {
  14718. console.error('BwTest polling error:', err);
  14719. } finally { busy = false; }
  14720. };
  14721. bwtestState.pollTimer = setInterval(poll, 400);
  14722. poll();
  14723. }
  14724. function handleBwTestSample(s) {
  14725. if (!s) return;
  14726. const payloadHint = document.getElementById('bwtest-effective-payload');
  14727. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14728. const txMbps = s.tx_mbps || 0;
  14729. const rxMbps = s.rx_mbps || 0;
  14730. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14731. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14732. // KPI updates
  14733. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14734. if (elTx) {
  14735. elTx.innerText = txMbps.toFixed(2);
  14736. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14737. }
  14738. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14739. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14740. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14741. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14742. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14743. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14744. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14745. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14746. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14747. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14748. const elLoss = document.getElementById('bwtest-stat-loss');
  14749. if (elLoss) {
  14750. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14751. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14752. }
  14753. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14754. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14755. const elJitter = document.getElementById('bwtest-stat-jitter');
  14756. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14757. const elTime = document.getElementById('bwtest-stat-time');
  14758. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14759. const elData = document.getElementById('bwtest-stat-data');
  14760. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14761. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14762. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14763. // Append point to chart buffer
  14764. bwtestState.chartPoints.push({
  14765. elapsed: s.elapsed_sec || 0,
  14766. tx: txMbps,
  14767. rx: rxMbps
  14768. });
  14769. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14770. bwtestState.chartPoints.shift();
  14771. }
  14772. drawBwTestChart();
  14773. // Add row to breakdown table
  14774. const tbody = document.getElementById('bwtest-samples-tbody');
  14775. if (tbody) {
  14776. const tr = document.createElement('tr');
  14777. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14778. tr.innerHTML = `
  14779. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14780. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14781. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14782. <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>
  14783. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14784. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14785. `;
  14786. tbody.insertBefore(tr, tbody.firstChild);
  14787. const countEl = document.getElementById('bwtest-sample-count');
  14788. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14789. }
  14790. }
  14791. function handleBwTestFinish(summary, error) {
  14792. const badge = document.getElementById('bwtest-run-status-badge');
  14793. if (error) {
  14794. showToast('Benchmark Error', error, 'error');
  14795. if (badge) {
  14796. badge.innerText = 'ERROR';
  14797. 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';
  14798. }
  14799. } else if (summary) {
  14800. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14801. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14802. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14803. if (badge) {
  14804. badge.innerText = 'COMPLETED';
  14805. 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';
  14806. }
  14807. }
  14808. loadBwTestHistory();
  14809. fetchBwTestServerStatus();
  14810. }
  14811. function resizeBwTestCanvas() {
  14812. const canvas = document.getElementById('bwtest-chart');
  14813. if (!canvas || !canvas.parentElement) return;
  14814. const rect = canvas.parentElement.getBoundingClientRect();
  14815. const dpr = window.devicePixelRatio || 1;
  14816. canvas.width = rect.width * dpr;
  14817. canvas.height = rect.height * dpr;
  14818. const ctx = canvas.getContext('2d');
  14819. ctx.scale(dpr, dpr);
  14820. drawBwTestChart();
  14821. }
  14822. window.addEventListener('resize', () => {
  14823. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14824. });
  14825. function drawBwTestChart() {
  14826. const canvas = document.getElementById('bwtest-chart');
  14827. if (!canvas) return;
  14828. const ctx = canvas.getContext('2d');
  14829. const dpr = window.devicePixelRatio || 1;
  14830. const width = canvas.width / dpr;
  14831. const height = canvas.height / dpr;
  14832. ctx.clearRect(0, 0, width, height);
  14833. const points = bwtestState.chartPoints;
  14834. if (!points || points.length === 0) return;
  14835. // Determine scale ceiling
  14836. let maxRate = 10;
  14837. for (const p of points) {
  14838. if (p.tx > maxRate) maxRate = p.tx;
  14839. if (p.rx > maxRate) maxRate = p.rx;
  14840. }
  14841. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14842. const paddingLeft = 55;
  14843. const paddingBottom = 24;
  14844. const paddingTop = 12;
  14845. const paddingRight = 16;
  14846. const chartW = width - paddingLeft - paddingRight;
  14847. const chartH = height - paddingTop - paddingBottom;
  14848. // Grid Lines and Y-Axis labels
  14849. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14850. ctx.lineWidth = 1;
  14851. ctx.fillStyle = '#94a3b8';
  14852. ctx.font = '10px monospace';
  14853. ctx.textAlign = 'right';
  14854. const gridSteps = 4;
  14855. for (let i = 0; i <= gridSteps; i++) {
  14856. const val = (maxRate / gridSteps) * i;
  14857. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14858. ctx.beginPath();
  14859. ctx.moveTo(paddingLeft, y);
  14860. ctx.lineTo(width - paddingRight, y);
  14861. ctx.stroke();
  14862. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14863. }
  14864. // Draw TX Line (Cyan #22d3ee)
  14865. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14866. // Draw RX Line (Purple #a855f7)
  14867. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14868. }
  14869. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14870. if (points.length < 2) return;
  14871. const stepX = w / Math.max(points.length - 1, 1);
  14872. // Gradient area fill
  14873. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14874. grad.addColorStop(0, fillColor);
  14875. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14876. ctx.beginPath();
  14877. points.forEach((p, idx) => {
  14878. const x = left + idx * stepX;
  14879. const val = valFn(p);
  14880. const y = top + h - (val / maxVal) * h;
  14881. if (idx === 0) {
  14882. ctx.moveTo(x, y);
  14883. } else {
  14884. ctx.lineTo(x, y);
  14885. }
  14886. });
  14887. // Complete path for fill
  14888. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14889. ctx.lineTo(left, top + h);
  14890. ctx.closePath();
  14891. ctx.fillStyle = grad;
  14892. ctx.fill();
  14893. // Draw line stroke
  14894. ctx.beginPath();
  14895. ctx.lineWidth = 2.5;
  14896. ctx.strokeStyle = strokeColor;
  14897. points.forEach((p, idx) => {
  14898. const x = left + idx * stepX;
  14899. const val = valFn(p);
  14900. const y = top + h - (val / maxVal) * h;
  14901. if (idx === 0) {
  14902. ctx.moveTo(x, y);
  14903. } else {
  14904. ctx.lineTo(x, y);
  14905. }
  14906. });
  14907. ctx.stroke();
  14908. // Draw end point halo
  14909. const lastP = points[points.length - 1];
  14910. const lastX = left + (points.length - 1) * stepX;
  14911. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14912. ctx.fillStyle = strokeColor;
  14913. ctx.beginPath();
  14914. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14915. ctx.fill();
  14916. }
  14917. async function loadBwTestHistory() {
  14918. try {
  14919. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14920. if (!res.ok) return;
  14921. const list = await res.json();
  14922. renderBwTestHistory(Array.isArray(list) ? list : []);
  14923. } catch (err) {
  14924. console.error('Failed to load BwTest history:', err);
  14925. }
  14926. }
  14927. function renderBwTestHistory(list) {
  14928. const tbody = document.getElementById('bwtest-history-tbody');
  14929. if (!tbody) return;
  14930. if (list.length === 0) {
  14931. 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>`;
  14932. return;
  14933. }
  14934. tbody.innerHTML = '';
  14935. list.forEach(item => {
  14936. const s = item.summary || {};
  14937. const tr = document.createElement('tr');
  14938. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14939. const dirBadge = item.direction === 'both'
  14940. ? `<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>`
  14941. : item.direction === 'tx'
  14942. ? `<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>`
  14943. : `<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>`;
  14944. const protoBadge = item.protocol === 'tcp'
  14945. ? `<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>`
  14946. : `<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>`;
  14947. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14948. tr.innerHTML = `
  14949. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14950. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14951. <td class="py-2.5 px-4">${protoBadge}</td>
  14952. <td class="py-2.5 px-4">${dirBadge}</td>
  14953. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14954. <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>
  14955. <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>
  14956. <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>
  14957. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14958. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14959. `;
  14960. tbody.appendChild(tr);
  14961. });
  14962. }
  14963. // ======================== SETTINGS & ROUTER DNS ========================
  14964. state.settingsSubTab = 'dns';
  14965. state.dnsSettings = null;
  14966. state.dnsStaticRecords = [];
  14967. state.dnsStatus = null;
  14968. function switchSettingsSubTab(sub) {
  14969. state.settingsSubTab = sub;
  14970. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14971. const btnSys = document.getElementById('btn-settings-subtab-system');
  14972. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14973. const tabDns = document.getElementById('settings-subtab-dns');
  14974. const tabSys = document.getElementById('settings-subtab-system');
  14975. const tabBak = document.getElementById('settings-subtab-backup');
  14976. 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';
  14977. 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';
  14978. if (btnDns) btnDns.className = inactiveClass;
  14979. if (btnSys) btnSys.className = inactiveClass;
  14980. if (btnBak) btnBak.className = inactiveClass;
  14981. tabDns?.classList.add('hidden');
  14982. tabSys?.classList.add('hidden');
  14983. tabBak?.classList.add('hidden');
  14984. if (sub === 'dns') {
  14985. if (btnDns) btnDns.className = activeClass;
  14986. tabDns?.classList.remove('hidden');
  14987. loadDNSSettings();
  14988. } else if (sub === 'system') {
  14989. if (btnSys) btnSys.className = activeClass;
  14990. tabSys?.classList.remove('hidden');
  14991. loadSystemSettings();
  14992. } else if (sub === 'backup') {
  14993. if (btnBak) btnBak.className = activeClass;
  14994. tabBak?.classList.remove('hidden');
  14995. loadBackupList();
  14996. }
  14997. }
  14998. async function loadSettingsData(showLoading = false) {
  14999. if (state.settingsSubTab === 'system') {
  15000. await loadSystemSettings();
  15001. } else if (state.settingsSubTab === 'backup') {
  15002. await loadBackupList();
  15003. } else {
  15004. await loadDNSSettings();
  15005. }
  15006. }
  15007. async function loadDNSSettings() {
  15008. try {
  15009. const [settingsRes, staticRes, statusRes] = await Promise.all([
  15010. fetch(`${API_BASE}/dns/settings`),
  15011. fetch(`${API_BASE}/dns/static`),
  15012. fetch(`${API_BASE}/dns/status`)
  15013. ]);
  15014. if (settingsRes.ok) {
  15015. state.dnsSettings = await settingsRes.json();
  15016. populateDNSSettingsForm(state.dnsSettings);
  15017. }
  15018. if (staticRes.ok) {
  15019. state.dnsStaticRecords = await staticRes.json();
  15020. renderStaticDNSList();
  15021. }
  15022. if (statusRes.ok) {
  15023. state.dnsStatus = await statusRes.json();
  15024. updateDNSStatusView(state.dnsStatus);
  15025. }
  15026. } catch (err) {
  15027. console.error('Failed to load DNS settings:', err);
  15028. }
  15029. }
  15030. function populateDNSSettingsForm(s) {
  15031. if (!s) return;
  15032. const dnsForm = document.getElementById('form-dns-settings');
  15033. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  15034. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  15035. if (dynamicEl) {
  15036. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  15037. 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(' ');
  15038. } else {
  15039. dynamicEl.innerText = 'None';
  15040. }
  15041. }
  15042. // If user is actively typing or editing in the form, do not overwrite their inputs!
  15043. if (isEditing) return;
  15044. const serversInput = document.getElementById('dns-servers-input');
  15045. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  15046. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  15047. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  15048. const domainInput = document.getElementById('dns-domain-input');
  15049. if (domainInput) domainInput.value = s.domain || '';
  15050. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  15051. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  15052. }
  15053. function updateDNSStatusView(st) {
  15054. if (!st) return;
  15055. const preview = document.getElementById('dns-resolv-preview');
  15056. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15057. const pillText = document.getElementById('dns-live-status-text');
  15058. const pill = document.getElementById('dns-live-status-pill');
  15059. if (pill && pillText) {
  15060. if (st.service_running) {
  15061. 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';
  15062. pillText.innerText = 'DNS Service Active';
  15063. } else {
  15064. 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';
  15065. pillText.innerText = 'DNS Service Inactive';
  15066. }
  15067. }
  15068. }
  15069. function appendDNSPreset(preset) {
  15070. const input = document.getElementById('dns-servers-input');
  15071. if (!input) return;
  15072. const dnsForm = document.getElementById('form-dns-settings');
  15073. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15074. const current = input.value.trim();
  15075. if (!current) {
  15076. input.value = preset;
  15077. } else {
  15078. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15079. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15080. toAdd.forEach(ip => {
  15081. if (!existing.includes(ip)) existing.push(ip);
  15082. });
  15083. input.value = existing.join(', ');
  15084. }
  15085. }
  15086. async function saveDNSSettings(e) {
  15087. e.preventDefault();
  15088. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15089. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15090. if (servers.length === 0) {
  15091. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15092. return;
  15093. }
  15094. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15095. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15096. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15097. try {
  15098. const res = await fetch(`${API_BASE}/dns/settings`, {
  15099. method: 'POST',
  15100. headers: { 'Content-Type': 'application/json' },
  15101. body: JSON.stringify({
  15102. servers: servers,
  15103. cache_size: cacheSize,
  15104. domain: domain,
  15105. allow_remote_requests: allowRemote
  15106. })
  15107. });
  15108. const data = await res.json();
  15109. if (res.ok) {
  15110. const dnsForm = document.getElementById('form-dns-settings');
  15111. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15112. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15113. loadDNSSettings();
  15114. } else {
  15115. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15116. }
  15117. } catch (err) {
  15118. showToast('Error', err.message, 'error');
  15119. }
  15120. }
  15121. async function flushDNSCache() {
  15122. try {
  15123. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15124. if (res.ok) {
  15125. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15126. loadDNSSettings();
  15127. } else {
  15128. const err = await res.json();
  15129. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15130. }
  15131. } catch (err) {
  15132. showToast('Error', err.message, 'error');
  15133. }
  15134. }
  15135. function renderStaticDNSList() {
  15136. const tbody = document.getElementById('dns-static-tbody');
  15137. const empty = document.getElementById('dns-static-empty');
  15138. const badge = document.getElementById('dns-static-count-badge');
  15139. if (!tbody) return;
  15140. tbody.innerHTML = '';
  15141. const records = state.dnsStaticRecords || [];
  15142. if (badge) badge.innerText = `${records.length} Records`;
  15143. if (records.length === 0) {
  15144. empty?.classList.remove('hidden');
  15145. return;
  15146. }
  15147. empty?.classList.add('hidden');
  15148. records.forEach(rec => {
  15149. const tr = document.createElement('tr');
  15150. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15151. tr.innerHTML = `
  15152. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15153. <td class="py-2.5 px-4">
  15154. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15155. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15156. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15157. }">
  15158. ${rec.type || 'A'}
  15159. </span>
  15160. </td>
  15161. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15162. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15163. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15164. <td class="py-2.5 px-4">
  15165. <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'}">
  15166. ${rec.disabled ? 'Disabled' : 'Active'}
  15167. </span>
  15168. </td>
  15169. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15170. <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>
  15171. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15172. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15173. </td>
  15174. `;
  15175. tbody.appendChild(tr);
  15176. });
  15177. }
  15178. function openStaticDNSModal(id = null) {
  15179. const modal = document.getElementById('modal-static-dns');
  15180. const title = document.getElementById('modal-static-dns-title');
  15181. const form = document.getElementById('form-static-dns');
  15182. if (!modal || !form) return;
  15183. form.reset();
  15184. document.getElementById('modal-static-dns-id').value = '';
  15185. if (id) {
  15186. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15187. if (rec) {
  15188. if (title) title.innerText = 'Edit Static DNS Record';
  15189. document.getElementById('modal-static-dns-id').value = rec.id;
  15190. document.getElementById('modal-static-dns-name').value = rec.name;
  15191. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15192. document.getElementById('modal-static-dns-addr').value = rec.address;
  15193. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15194. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15195. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15196. }
  15197. } else {
  15198. if (title) title.innerText = 'Add Static DNS Record';
  15199. }
  15200. modal.classList.remove('hidden');
  15201. }
  15202. function closeStaticDNSModal() {
  15203. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15204. }
  15205. async function submitSaveStaticDNS(e) {
  15206. e.preventDefault();
  15207. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15208. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15209. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15210. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15211. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15212. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15213. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15214. if (!name || !address) {
  15215. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15216. return;
  15217. }
  15218. try {
  15219. const res = await fetch(`${API_BASE}/dns/static`, {
  15220. method: 'POST',
  15221. headers: { 'Content-Type': 'application/json' },
  15222. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15223. });
  15224. const data = await res.json();
  15225. if (res.ok) {
  15226. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15227. closeStaticDNSModal();
  15228. loadDNSSettings();
  15229. } else {
  15230. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15231. }
  15232. } catch (err) {
  15233. showToast('Error', err.message, 'error');
  15234. }
  15235. }
  15236. async function deleteStaticDNS(id) {
  15237. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15238. try {
  15239. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15240. if (res.ok) {
  15241. showToast('Deleted', 'Static DNS record deleted', 'success');
  15242. loadDNSSettings();
  15243. }
  15244. } catch (err) {
  15245. showToast('Error', err.message, 'error');
  15246. }
  15247. }
  15248. async function toggleStaticDNS(id, disabled) {
  15249. try {
  15250. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15251. method: 'POST',
  15252. headers: { 'Content-Type': 'application/json' },
  15253. body: JSON.stringify({ disabled })
  15254. });
  15255. if (res.ok) {
  15256. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15257. loadDNSSettings();
  15258. }
  15259. } catch (err) {
  15260. showToast('Error', err.message, 'error');
  15261. }
  15262. }
  15263. async function loadSystemSettings() {
  15264. try {
  15265. const sysForm = document.getElementById('form-system-settings');
  15266. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15267. const res = await fetch(`${API_BASE}/system/settings`);
  15268. if (res.ok) {
  15269. const data = await res.json();
  15270. if (!isEditing) {
  15271. const hostInput = document.getElementById('system-hostname-input');
  15272. if (hostInput) hostInput.value = data.hostname || '';
  15273. const tzInput = document.getElementById('system-timezone-input');
  15274. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15275. }
  15276. }
  15277. } catch (err) {
  15278. console.error('Failed to load system settings:', err);
  15279. }
  15280. }
  15281. async function saveSystemSettings(e) {
  15282. e.preventDefault();
  15283. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15284. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15285. try {
  15286. const res = await fetch(`${API_BASE}/system/settings`, {
  15287. method: 'POST',
  15288. headers: { 'Content-Type': 'application/json' },
  15289. body: JSON.stringify({ hostname, timezone })
  15290. });
  15291. const data = await res.json();
  15292. if (res.ok) {
  15293. const sysForm = document.getElementById('form-system-settings');
  15294. if (sysForm) sysForm.dataset.dirty = 'false';
  15295. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15296. const sideH = document.getElementById('side-hostname');
  15297. if (sideH) sideH.innerText = data.hostname;
  15298. } else {
  15299. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15300. }
  15301. } catch (err) {
  15302. showToast('Error', err.message, 'error');
  15303. }
  15304. }
  15305. // =============================================================================
  15306. // BACKUP & RESTORE MANAGER
  15307. // =============================================================================
  15308. state.selectedBackupFile = null;
  15309. state.inspectedBackupManifest = null;
  15310. state.pendingRestoreTarget = null;
  15311. state.backupsList = [];
  15312. async function exportBackupDownload() {
  15313. const btn = document.getElementById('btn-export-backup');
  15314. const commentInput = document.getElementById('backup-export-comment');
  15315. const comment = (commentInput?.value || '').trim();
  15316. const originalHtml = btn ? btn.innerHTML : '';
  15317. if (btn) {
  15318. btn.disabled = true;
  15319. 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...`;
  15320. }
  15321. try {
  15322. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15323. if (!res.ok) {
  15324. const err = await res.json().catch(() => ({}));
  15325. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15326. return;
  15327. }
  15328. const blob = await res.blob();
  15329. const disposition = res.headers.get('Content-Disposition') || '';
  15330. let filename = 'debtik-backup.zip';
  15331. const match = disposition.match(/filename="?([^";]+)"?/);
  15332. if (match && match[1]) {
  15333. filename = match[1];
  15334. }
  15335. const blobUrl = window.URL.createObjectURL(blob);
  15336. const a = document.createElement('a');
  15337. a.href = blobUrl;
  15338. a.download = filename;
  15339. document.body.appendChild(a);
  15340. a.click();
  15341. setTimeout(() => {
  15342. window.URL.revokeObjectURL(blobUrl);
  15343. a.remove();
  15344. }, 1000);
  15345. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15346. } catch (err) {
  15347. showToast('Export Error', err.message || 'Network error during download', 'error');
  15348. } finally {
  15349. if (btn) {
  15350. btn.disabled = false;
  15351. btn.innerHTML = originalHtml;
  15352. }
  15353. }
  15354. }
  15355. async function onBackupFileSelected(e) {
  15356. const file = e.target.files?.[0];
  15357. if (!file) return;
  15358. const label = document.getElementById('backup-file-label');
  15359. if (label) {
  15360. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15361. }
  15362. await inspectBackupFile(file);
  15363. }
  15364. async function inspectBackupFile(file) {
  15365. const preview = document.getElementById('backup-inspect-preview');
  15366. const restoreBtn = document.getElementById('btn-restore-backup');
  15367. const formData = new FormData();
  15368. formData.append('backup', file);
  15369. try {
  15370. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15371. method: 'POST',
  15372. body: formData
  15373. });
  15374. const data = await res.json();
  15375. if (!res.ok || !data.success || !data.manifest) {
  15376. if (preview) preview.classList.add('hidden');
  15377. if (restoreBtn) restoreBtn.disabled = true;
  15378. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15379. return;
  15380. }
  15381. const mf = data.manifest;
  15382. state.selectedBackupFile = file;
  15383. state.inspectedBackupManifest = mf;
  15384. const vEl = document.getElementById('backup-inspect-version');
  15385. const hEl = document.getElementById('backup-inspect-hostname');
  15386. const fEl = document.getElementById('backup-inspect-files');
  15387. const dEl = document.getElementById('backup-inspect-date');
  15388. const cEl = document.getElementById('backup-inspect-comment');
  15389. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15390. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15391. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15392. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15393. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15394. if (preview) preview.classList.remove('hidden');
  15395. if (restoreBtn) restoreBtn.disabled = false;
  15396. } catch (err) {
  15397. if (preview) preview.classList.add('hidden');
  15398. if (restoreBtn) restoreBtn.disabled = true;
  15399. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15400. }
  15401. }
  15402. function confirmRestoreBackup(localFilename = null) {
  15403. const modal = document.getElementById('modal-restore-confirm');
  15404. const details = document.getElementById('modal-restore-details');
  15405. const progress = document.getElementById('modal-restore-progress');
  15406. const cancelBtn = document.getElementById('btn-cancel-restore');
  15407. const execBtn = document.getElementById('btn-execute-restore');
  15408. if (progress) progress.classList.add('hidden');
  15409. if (cancelBtn) cancelBtn.disabled = false;
  15410. if (execBtn) {
  15411. execBtn.disabled = false;
  15412. execBtn.innerText = 'Yes, Restore & Reload';
  15413. }
  15414. if (localFilename) {
  15415. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15416. if (details) {
  15417. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15418. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15419. }
  15420. } else {
  15421. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15422. showToast('Error', 'Please select a valid backup archive first', 'error');
  15423. return;
  15424. }
  15425. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15426. const mf = state.inspectedBackupManifest;
  15427. if (details) {
  15428. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15429. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15430. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15431. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15432. }
  15433. }
  15434. if (modal) modal.classList.remove('hidden');
  15435. }
  15436. function closeRestoreModal() {
  15437. const modal = document.getElementById('modal-restore-confirm');
  15438. if (modal) modal.classList.add('hidden');
  15439. }
  15440. async function executeRestoreBackup() {
  15441. const target = state.pendingRestoreTarget;
  15442. if (!target) return;
  15443. const progress = document.getElementById('modal-restore-progress');
  15444. const progressText = document.getElementById('modal-restore-progress-text');
  15445. const cancelBtn = document.getElementById('btn-cancel-restore');
  15446. const execBtn = document.getElementById('btn-execute-restore');
  15447. if (cancelBtn) cancelBtn.disabled = true;
  15448. if (execBtn) execBtn.disabled = true;
  15449. if (progress) progress.classList.remove('hidden');
  15450. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15451. try {
  15452. let res;
  15453. if (target.type === 'file') {
  15454. const formData = new FormData();
  15455. formData.append('backup', target.file);
  15456. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15457. method: 'POST',
  15458. body: formData
  15459. });
  15460. } else {
  15461. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15462. method: 'POST'
  15463. });
  15464. }
  15465. const data = await res.json();
  15466. if (!res.ok || !data.success) {
  15467. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15468. if (cancelBtn) cancelBtn.disabled = false;
  15469. if (execBtn) execBtn.disabled = false;
  15470. if (progress) progress.classList.add('hidden');
  15471. return;
  15472. }
  15473. if (progressText) {
  15474. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15475. }
  15476. pollAfterRestoreReconnect();
  15477. } catch (err) {
  15478. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15479. if (cancelBtn) cancelBtn.disabled = false;
  15480. if (execBtn) execBtn.disabled = false;
  15481. if (progress) progress.classList.add('hidden');
  15482. }
  15483. }
  15484. function pollAfterRestoreReconnect() {
  15485. let attempts = 0;
  15486. const maxAttempts = 25;
  15487. const timer = setInterval(async () => {
  15488. attempts++;
  15489. try {
  15490. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15491. if (res.ok) {
  15492. clearInterval(timer);
  15493. closeRestoreModal();
  15494. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15495. setTimeout(() => {
  15496. window.location.reload();
  15497. }, 1200);
  15498. }
  15499. } catch (_) {
  15500. // Still restarting, retry
  15501. }
  15502. if (attempts >= maxAttempts) {
  15503. clearInterval(timer);
  15504. closeRestoreModal();
  15505. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15506. }
  15507. }, 1500);
  15508. }
  15509. async function loadBackupList() {
  15510. const tbody = document.getElementById('backups-table-tbody');
  15511. const empty = document.getElementById('backups-empty-state');
  15512. if (!tbody) return;
  15513. try {
  15514. const res = await fetch(`${API_BASE}/system/backups`);
  15515. if (!res.ok) return;
  15516. const list = await res.json();
  15517. state.backupsList = list || [];
  15518. renderBackupsTable(state.backupsList);
  15519. } catch (err) {
  15520. console.error('Failed to load backup list:', err);
  15521. }
  15522. }
  15523. function renderBackupsTable(backups) {
  15524. const tbody = document.getElementById('backups-table-tbody');
  15525. const empty = document.getElementById('backups-empty-state');
  15526. if (!tbody) return;
  15527. if (!backups || backups.length === 0) {
  15528. tbody.innerHTML = '';
  15529. if (empty) empty.classList.remove('hidden');
  15530. return;
  15531. }
  15532. if (empty) empty.classList.add('hidden');
  15533. tbody.innerHTML = backups.map(bk => {
  15534. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15535. const badge = isAuto
  15536. ? `<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>`
  15537. : `<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>`;
  15538. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15539. return `<tr class="hover:bg-slate-800/40 transition">
  15540. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15541. ${badge}
  15542. <span>${escapeHtml(bk.filename)}</span>
  15543. </td>
  15544. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15545. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15546. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15547. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15548. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15549. <td class="py-3 px-4 text-right space-x-2">
  15550. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15551. 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">
  15552. Download
  15553. </button>
  15554. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15555. 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">
  15556. Restore
  15557. </button>
  15558. </td>
  15559. </tr>`;
  15560. }).join('');
  15561. }
  15562. async function downloadLocalBackup(filename) {
  15563. try {
  15564. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15565. if (!res.ok) {
  15566. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15567. return;
  15568. }
  15569. const blob = await res.blob();
  15570. const blobUrl = window.URL.createObjectURL(blob);
  15571. const a = document.createElement('a');
  15572. a.href = blobUrl;
  15573. a.download = filename;
  15574. document.body.appendChild(a);
  15575. a.click();
  15576. setTimeout(() => {
  15577. window.URL.revokeObjectURL(blobUrl);
  15578. a.remove();
  15579. }, 1000);
  15580. } catch (err) {
  15581. showToast('Download Error', err.message, 'error');
  15582. }
  15583. }
  15584. // =============================================================================
  15585. // AUTHENTICATION & USER MANAGER
  15586. // =============================================================================
  15587. async function checkAuthStatus() {
  15588. try {
  15589. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15590. headers: {
  15591. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15592. }
  15593. });
  15594. if (res.ok) {
  15595. const user = await res.json();
  15596. state.currentUser = user;
  15597. updateUserProfileHeader(user);
  15598. hideLoginScreen();
  15599. state.isPolling = true;
  15600. fetchData();
  15601. initLiveTrafficStream();
  15602. return true;
  15603. } else {
  15604. showLoginScreen(false);
  15605. return false;
  15606. }
  15607. } catch (err) {
  15608. showLoginScreen(false);
  15609. return false;
  15610. }
  15611. }
  15612. function showLoginScreen(isExpired = false) {
  15613. const el = document.getElementById('login-screen');
  15614. if (el) el.classList.remove('hidden');
  15615. const errEl = document.getElementById('login-error');
  15616. const errTxt = document.getElementById('login-error-text');
  15617. if (isExpired && errEl && errTxt) {
  15618. errTxt.innerText = 'Session expired. Please sign in again.';
  15619. errEl.classList.remove('hidden');
  15620. } else if (errEl) {
  15621. errEl.classList.add('hidden');
  15622. }
  15623. const pwInput = document.getElementById('login-password');
  15624. if (pwInput) pwInput.value = '';
  15625. const userInput = document.getElementById('login-username');
  15626. if (userInput && !userInput.value) userInput.focus();
  15627. else if (pwInput) pwInput.focus();
  15628. }
  15629. function hideLoginScreen() {
  15630. const el = document.getElementById('login-screen');
  15631. if (el) el.classList.add('hidden');
  15632. const errEl = document.getElementById('login-error');
  15633. if (errEl) errEl.classList.add('hidden');
  15634. }
  15635. async function handleLoginSubmit(event) {
  15636. event.preventDefault();
  15637. const username = (document.getElementById('login-username')?.value || '').trim();
  15638. const password = document.getElementById('login-password')?.value || '';
  15639. const errEl = document.getElementById('login-error');
  15640. const errTxt = document.getElementById('login-error-text');
  15641. const btn = document.getElementById('login-submit-btn');
  15642. const btnText = document.getElementById('login-btn-text');
  15643. const spinner = document.getElementById('login-btn-spinner');
  15644. if (!username || !password) {
  15645. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15646. if (errEl) errEl.classList.remove('hidden');
  15647. return;
  15648. }
  15649. if (errEl) errEl.classList.add('hidden');
  15650. if (btn) btn.disabled = true;
  15651. if (btnText) btnText.innerText = 'Authenticating...';
  15652. if (spinner) spinner.classList.remove('hidden');
  15653. try {
  15654. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15655. method: 'POST',
  15656. headers: { 'Content-Type': 'application/json' },
  15657. body: JSON.stringify({ username, password })
  15658. });
  15659. const data = await res.json();
  15660. if (res.ok && data.success) {
  15661. localStorage.setItem('debtik_token', data.token);
  15662. state.currentUser = data.user;
  15663. updateUserProfileHeader(data.user);
  15664. hideLoginScreen();
  15665. state.isPolling = true;
  15666. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15667. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15668. navigate(hash);
  15669. fetchData();
  15670. initLiveTrafficStream();
  15671. // Ensure background telemetry polling is active
  15672. if (!window._telemetryInterval) {
  15673. window._telemetryInterval = setInterval(() => {
  15674. if (state.isPolling && state.currentUser && !document.hidden) {
  15675. fetchData(false);
  15676. }
  15677. }, 5000);
  15678. }
  15679. } else {
  15680. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15681. if (errEl) errEl.classList.remove('hidden');
  15682. }
  15683. } catch (err) {
  15684. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15685. if (errEl) errEl.classList.remove('hidden');
  15686. } finally {
  15687. if (btn) btn.disabled = false;
  15688. if (btnText) btnText.innerText = 'Sign In to Controller';
  15689. if (spinner) spinner.classList.add('hidden');
  15690. }
  15691. }
  15692. async function handleLogoutClick() {
  15693. try {
  15694. await originalFetch(`${API_BASE}/auth/logout`, {
  15695. method: 'POST',
  15696. headers: {
  15697. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15698. }
  15699. });
  15700. } catch (e) {}
  15701. stopSessionPolling();
  15702. localStorage.removeItem('debtik_token');
  15703. state.currentUser = null;
  15704. state.isPolling = false;
  15705. if (window._telemetryInterval) {
  15706. clearInterval(window._telemetryInterval);
  15707. window._telemetryInterval = null;
  15708. }
  15709. if (trafficEventSource) {
  15710. trafficEventSource.close();
  15711. trafficEventSource = null;
  15712. }
  15713. if (trafficPollFallback) {
  15714. clearInterval(trafficPollFallback);
  15715. trafficPollFallback = null;
  15716. }
  15717. showLoginScreen(false);
  15718. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15719. }
  15720. function togglePasswordVisibility(id) {
  15721. const input = document.getElementById(id);
  15722. if (!input) return;
  15723. input.type = input.type === 'password' ? 'text' : 'password';
  15724. }
  15725. function toggleUserMenu() {
  15726. const menu = document.getElementById('user-menu-dropdown');
  15727. if (menu) menu.classList.toggle('hidden');
  15728. }
  15729. function closeUserMenu() {
  15730. const menu = document.getElementById('user-menu-dropdown');
  15731. if (menu) menu.classList.add('hidden');
  15732. }
  15733. // Close user menu on outside click
  15734. document.addEventListener('click', (e) => {
  15735. const menu = document.getElementById('user-menu-dropdown');
  15736. if (!menu || menu.classList.contains('hidden')) return;
  15737. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15738. menu.classList.add('hidden');
  15739. }
  15740. });
  15741. function updateUserProfileHeader(user) {
  15742. if (!user) return;
  15743. const navName = document.getElementById('nav-user-name');
  15744. if (navName) navName.innerText = user.username;
  15745. const dropName = document.getElementById('dropdown-user-name');
  15746. if (dropName) dropName.innerText = user.username;
  15747. const navRole = document.getElementById('nav-user-role');
  15748. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15749. const navAvatar = document.getElementById('nav-user-avatar');
  15750. if (navAvatar) {
  15751. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15752. navAvatar.innerText = initials;
  15753. }
  15754. const statCurUser = document.getElementById('stat-current-user');
  15755. if (statCurUser) statCurUser.innerText = user.username;
  15756. const statCurRole = document.getElementById('stat-current-role');
  15757. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15758. // Role permissions UI visibility: hide user management for non-admins
  15759. const isFullAdmin = user.role === 'full';
  15760. const navUsers = document.getElementById('nav-users');
  15761. if (navUsers) {
  15762. if (isFullAdmin) navUsers.classList.remove('hidden');
  15763. else navUsers.classList.add('hidden');
  15764. }
  15765. const dropdownUsers = document.getElementById('dropdown-item-users');
  15766. if (dropdownUsers) {
  15767. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15768. else dropdownUsers.classList.add('hidden');
  15769. }
  15770. }
  15771. // ================= User Management CRUD =================
  15772. async function loadUsers(isManual = false) {
  15773. try {
  15774. const res = await fetch(`${API_BASE}/users`);
  15775. if (res.status === 403) {
  15776. const tbody = document.getElementById('users-table-tbody');
  15777. if (tbody) {
  15778. tbody.innerHTML = `
  15779. <tr>
  15780. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15781. <div class="inline-flex items-center gap-2">
  15782. <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>
  15783. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15784. </div>
  15785. </td>
  15786. </tr>
  15787. `;
  15788. }
  15789. return;
  15790. }
  15791. if (res.ok) {
  15792. state.users = await res.json();
  15793. renderUsersTable();
  15794. const totalUsers = document.getElementById('stat-total-users');
  15795. if (totalUsers) totalUsers.innerText = state.users.length;
  15796. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15797. const adminUsers = document.getElementById('stat-admin-users');
  15798. if (adminUsers) adminUsers.innerText = adminCount;
  15799. const badgeCount = document.getElementById('badge-users-count');
  15800. if (badgeCount) badgeCount.innerText = state.users.length;
  15801. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15802. }
  15803. } catch (err) {
  15804. console.error('Failed to load users:', err);
  15805. }
  15806. }
  15807. function renderUsersTable() {
  15808. const tbody = document.getElementById('users-table-tbody');
  15809. const emptyState = document.getElementById('users-empty-state');
  15810. if (!tbody) return;
  15811. tbody.innerHTML = '';
  15812. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15813. const filtered = (state.users || []).filter(u => {
  15814. if (!query) return true;
  15815. return u.username.toLowerCase().includes(query) ||
  15816. (u.role || '').toLowerCase().includes(query) ||
  15817. (u.comment || '').toLowerCase().includes(query);
  15818. });
  15819. if (filtered.length === 0) {
  15820. if (emptyState) emptyState.classList.remove('hidden');
  15821. return;
  15822. }
  15823. if (emptyState) emptyState.classList.add('hidden');
  15824. const currentAuthUser = state.currentUser?.username || '';
  15825. filtered.forEach(u => {
  15826. const isSelf = u.username === currentAuthUser;
  15827. const isFull = u.role === 'full';
  15828. const isWrite = u.role === 'write';
  15829. 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>`;
  15830. if (isFull) {
  15831. 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>`;
  15832. } else if (isWrite) {
  15833. 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>`;
  15834. }
  15835. const statusBadge = u.disabled
  15836. ? `<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>`
  15837. : `<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>`;
  15838. let lastLoginText = 'Never';
  15839. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15840. const dt = new Date(u.last_login_at);
  15841. lastLoginText = dt.toLocaleString();
  15842. }
  15843. const initials = u.username.slice(0, 2).toUpperCase();
  15844. const tr = document.createElement('tr');
  15845. tr.className = 'hover:bg-slate-800/40 transition group';
  15846. tr.innerHTML = `
  15847. <td class="py-3 px-4">
  15848. <div class="flex items-center gap-3">
  15849. <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">
  15850. ${initials}
  15851. </div>
  15852. <div>
  15853. <div class="font-bold text-white text-xs flex items-center gap-2">
  15854. <span>${escapeHtml(u.username)}</span>
  15855. ${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>' : ''}
  15856. </div>
  15857. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15858. </div>
  15859. </div>
  15860. </td>
  15861. <td class="py-3 px-4 font-sans">
  15862. ${roleBadge}
  15863. </td>
  15864. <td class="py-3 px-4 font-sans">
  15865. ${statusBadge}
  15866. </td>
  15867. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15868. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15869. </td>
  15870. <td class="py-3 px-4 text-slate-400 text-xs">
  15871. ${lastLoginText}
  15872. </td>
  15873. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15874. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15875. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15876. <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>
  15877. </button>
  15878. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15879. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15880. <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>
  15881. </button>
  15882. ${!isSelf ? `
  15883. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15884. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15885. <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>
  15886. </button>
  15887. ` : ''}
  15888. </td>
  15889. `;
  15890. tbody.appendChild(tr);
  15891. });
  15892. }
  15893. function openAddUserModal() {
  15894. document.getElementById('user-add-username').value = '';
  15895. document.getElementById('user-add-password').value = '';
  15896. document.getElementById('user-add-confirm').value = '';
  15897. document.getElementById('user-add-role').value = 'full';
  15898. document.getElementById('user-add-comment').value = '';
  15899. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15900. document.getElementById('user-add-username')?.focus();
  15901. }
  15902. function closeAddUserModal() {
  15903. document.getElementById('modal-add-user')?.classList.add('hidden');
  15904. }
  15905. async function submitAddUser(event) {
  15906. event.preventDefault();
  15907. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15908. const password = document.getElementById('user-add-password')?.value || '';
  15909. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15910. const role = document.getElementById('user-add-role')?.value || 'full';
  15911. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15912. if (password !== confirm) {
  15913. showToast('Validation Error', 'Passwords do not match', 'warning');
  15914. return;
  15915. }
  15916. if (password.length < 4) {
  15917. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15918. return;
  15919. }
  15920. try {
  15921. const res = await fetch(`${API_BASE}/users`, {
  15922. method: 'POST',
  15923. headers: { 'Content-Type': 'application/json' },
  15924. body: JSON.stringify({ username, password, role, comment })
  15925. });
  15926. const data = await res.json();
  15927. if (res.ok) {
  15928. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15929. closeAddUserModal();
  15930. loadUsers(false);
  15931. } else {
  15932. showToast('Error', data.message || 'Failed to create user', 'error');
  15933. }
  15934. } catch (err) {
  15935. showToast('Error', err.message, 'error');
  15936. }
  15937. }
  15938. function openEditUserModal(username) {
  15939. const user = (state.users || []).find(u => u.username === username);
  15940. if (!user) return;
  15941. document.getElementById('user-edit-username').value = user.username;
  15942. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15943. document.getElementById('user-edit-role').value = user.role || 'read';
  15944. document.getElementById('user-edit-comment').value = user.comment || '';
  15945. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15946. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15947. }
  15948. function closeEditUserModal() {
  15949. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15950. }
  15951. async function submitEditUser(event) {
  15952. event.preventDefault();
  15953. const username = document.getElementById('user-edit-username')?.value;
  15954. const role = document.getElementById('user-edit-role')?.value || 'read';
  15955. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15956. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15957. try {
  15958. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15959. method: 'PUT',
  15960. headers: { 'Content-Type': 'application/json' },
  15961. body: JSON.stringify({ role, comment, disabled })
  15962. });
  15963. const data = await res.json();
  15964. if (res.ok) {
  15965. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15966. closeEditUserModal();
  15967. loadUsers(false);
  15968. // If updated own role/disabled status, refresh self profile
  15969. if (username === state.currentUser?.username) {
  15970. checkAuthStatus();
  15971. }
  15972. } else {
  15973. showToast('Error', data.message || 'Failed to update user', 'error');
  15974. }
  15975. } catch (err) {
  15976. showToast('Error', err.message, 'error');
  15977. }
  15978. }
  15979. function openAdminResetPasswordModal(username) {
  15980. document.getElementById('admin-reset-username').value = username;
  15981. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15982. document.getElementById('admin-reset-new-pw').value = '';
  15983. document.getElementById('admin-reset-confirm-pw').value = '';
  15984. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15985. document.getElementById('admin-reset-new-pw')?.focus();
  15986. }
  15987. function closeAdminResetPasswordModal() {
  15988. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15989. }
  15990. async function submitAdminResetPassword(event) {
  15991. event.preventDefault();
  15992. const username = document.getElementById('admin-reset-username')?.value;
  15993. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15994. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15995. if (newPassword !== confirm) {
  15996. showToast('Validation Error', 'Passwords do not match', 'warning');
  15997. return;
  15998. }
  15999. if (newPassword.length < 4) {
  16000. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16001. return;
  16002. }
  16003. try {
  16004. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  16005. method: 'POST',
  16006. headers: { 'Content-Type': 'application/json' },
  16007. body: JSON.stringify({ new_password: newPassword })
  16008. });
  16009. const data = await res.json();
  16010. if (res.ok) {
  16011. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  16012. closeAdminResetPasswordModal();
  16013. } else {
  16014. showToast('Error', data.message || 'Failed to reset password', 'error');
  16015. }
  16016. } catch (err) {
  16017. showToast('Error', err.message, 'error');
  16018. }
  16019. }
  16020. async function deleteUser(username) {
  16021. if (username === state.currentUser?.username) {
  16022. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  16023. return;
  16024. }
  16025. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  16026. return;
  16027. }
  16028. try {
  16029. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16030. method: 'DELETE'
  16031. });
  16032. const data = await res.json();
  16033. if (res.ok) {
  16034. showToast('User Deleted', `User ${username} has been removed`, 'success');
  16035. loadUsers(false);
  16036. } else {
  16037. showToast('Error', data.message || 'Failed to delete user', 'error');
  16038. }
  16039. } catch (err) {
  16040. showToast('Error', err.message, 'error');
  16041. }
  16042. }
  16043. function openSelfPasswordModal() {
  16044. document.getElementById('self-current-password').value = '';
  16045. document.getElementById('self-new-password').value = '';
  16046. document.getElementById('self-confirm-password').value = '';
  16047. document.getElementById('modal-self-password')?.classList.remove('hidden');
  16048. document.getElementById('self-current-password')?.focus();
  16049. }
  16050. function closeSelfPasswordModal() {
  16051. document.getElementById('modal-self-password')?.classList.add('hidden');
  16052. }
  16053. async function submitSelfPassword(event) {
  16054. event.preventDefault();
  16055. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16056. const newPassword = document.getElementById('self-new-password')?.value || '';
  16057. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16058. if (newPassword !== confirm) {
  16059. showToast('Validation Error', 'New passwords do not match', 'warning');
  16060. return;
  16061. }
  16062. if (newPassword.length < 4) {
  16063. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16064. return;
  16065. }
  16066. try {
  16067. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16068. method: 'POST',
  16069. headers: { 'Content-Type': 'application/json' },
  16070. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16071. });
  16072. const data = await res.json();
  16073. if (res.ok) {
  16074. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16075. closeSelfPasswordModal();
  16076. } else {
  16077. showToast('Error', data.message || 'Failed to change password', 'error');
  16078. }
  16079. } catch (err) {
  16080. showToast('Error', err.message, 'error');
  16081. }
  16082. }
  16083. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16084. state.services = [];
  16085. async function loadServices(manual = false) {
  16086. try {
  16087. const res = await fetch(`${API_BASE}/system/services`);
  16088. if (!res.ok) throw new Error('Failed to load services');
  16089. const data = await res.json();
  16090. state.services = data || [];
  16091. renderServicesTable();
  16092. updateCertificatesBadges();
  16093. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16094. } catch (err) {
  16095. if (manual) showToast('Error', err.message, 'error');
  16096. }
  16097. }
  16098. function renderServicesTable() {
  16099. const tbody = document.getElementById('services-table-body');
  16100. if (!tbody) return;
  16101. if (!state.services || state.services.length === 0) {
  16102. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16103. return;
  16104. }
  16105. tbody.innerHTML = state.services.map(s => {
  16106. const isOff = s.disabled;
  16107. const statusBadge = isOff
  16108. ? '<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>'
  16109. : '<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>';
  16110. const toggleBtn = isOff
  16111. ? `<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>`
  16112. : `<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>`;
  16113. let certBadge = '';
  16114. if (s.name === 'www-ssl') {
  16115. if (s.certificate) {
  16116. 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>`;
  16117. } else {
  16118. 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>`;
  16119. }
  16120. }
  16121. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16122. return `
  16123. <tr class="hover:bg-slate-800/40 transition">
  16124. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16125. <td class="py-3 px-4">
  16126. <div class="flex items-center gap-2">
  16127. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16128. <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">
  16129. <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>
  16130. </button>
  16131. </div>
  16132. </td>
  16133. <td class="py-3 px-4">${statusBadge}</td>
  16134. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16135. <td class="py-3 px-4 text-right">
  16136. <div class="flex items-center justify-end gap-2">
  16137. <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">
  16138. <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>
  16139. <span>Edit</span>
  16140. </button>
  16141. ${toggleBtn}
  16142. </div>
  16143. </td>
  16144. </tr>
  16145. `;
  16146. }).join('');
  16147. }
  16148. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16149. document.getElementById('modal-service-name').value = serviceName;
  16150. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16151. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16152. document.getElementById('modal-service-port').value = currentPort;
  16153. const hintEl = document.getElementById('modal-service-port-hint');
  16154. const warnEl = document.getElementById('modal-service-warning');
  16155. const certGroup = document.getElementById('modal-service-cert-group');
  16156. const certSelect = document.getElementById('modal-service-cert-select');
  16157. if (serviceName === 'www') {
  16158. hintEl.textContent = 'Default HTTP web port: 80';
  16159. warnEl.classList.remove('hidden');
  16160. certGroup.classList.add('hidden');
  16161. } else if (serviceName === 'www-ssl') {
  16162. hintEl.textContent = 'Default HTTPS web port: 443';
  16163. warnEl.classList.remove('hidden');
  16164. certGroup.classList.remove('hidden');
  16165. const populateCertOptions = (certs) => {
  16166. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16167. (certs || []).forEach(c => {
  16168. const opt = document.createElement('option');
  16169. opt.value = c.name;
  16170. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16171. if (c.name === currentCert) opt.selected = true;
  16172. certSelect.appendChild(opt);
  16173. });
  16174. };
  16175. if (state.certificates && state.certificates.length > 0) {
  16176. populateCertOptions(state.certificates);
  16177. } else {
  16178. loadCertificates(false).then(() => {
  16179. populateCertOptions(state.certificates);
  16180. });
  16181. }
  16182. } else if (serviceName === 'telnet') {
  16183. hintEl.textContent = 'Default Telnet console port: 8282';
  16184. warnEl.classList.add('hidden');
  16185. certGroup.classList.add('hidden');
  16186. } else if (serviceName === 'ssh') {
  16187. hintEl.textContent = 'Default SSH port: 2222';
  16188. warnEl.classList.add('hidden');
  16189. certGroup.classList.add('hidden');
  16190. } else {
  16191. hintEl.textContent = '';
  16192. warnEl.classList.add('hidden');
  16193. certGroup.classList.add('hidden');
  16194. }
  16195. const modal = document.getElementById('modal-service-edit');
  16196. modal.classList.remove('hidden');
  16197. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16198. }
  16199. function closeEditServiceModal() {
  16200. const modal = document.getElementById('modal-service-edit');
  16201. if (modal) modal.classList.add('hidden');
  16202. }
  16203. async function submitSaveServicePort(event) {
  16204. event.preventDefault();
  16205. const name = document.getElementById('modal-service-name').value;
  16206. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16207. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16208. if (isNaN(port) || port < 1 || port > 65535) {
  16209. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16210. return;
  16211. }
  16212. const certSelect = document.getElementById('modal-service-cert-select');
  16213. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16214. try {
  16215. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16216. method: 'POST',
  16217. headers: { 'Content-Type': 'application/json' },
  16218. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16219. });
  16220. if (!res.ok) {
  16221. const errData = await res.json();
  16222. throw new Error(errData.message || 'Failed to update service settings');
  16223. }
  16224. closeEditServiceModal();
  16225. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16226. await loadServices();
  16227. } catch (err) {
  16228. showToast('Error', err.message, 'error');
  16229. }
  16230. }
  16231. async function toggleServiceState(serviceName, newDisabled) {
  16232. if (serviceName === 'www' && newDisabled) {
  16233. 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?")) {
  16234. return;
  16235. }
  16236. }
  16237. if (serviceName === 'www-ssl' && !newDisabled) {
  16238. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16239. if (!sslSvc || !sslSvc.certificate) {
  16240. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16241. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16242. return;
  16243. }
  16244. }
  16245. try {
  16246. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16247. method: 'POST',
  16248. headers: { 'Content-Type': 'application/json' },
  16249. body: JSON.stringify({ disabled: newDisabled })
  16250. });
  16251. if (!res.ok) {
  16252. const errData = await res.json();
  16253. throw new Error(errData.message || 'Failed to update service');
  16254. }
  16255. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16256. await loadServices();
  16257. } catch (err) {
  16258. showToast('Error', err.message, 'error');
  16259. }
  16260. }
  16261. // ==================== SYSTEM LOGS (/log) ====================
  16262. state.logs = [];
  16263. let logsTimer = null;
  16264. async function loadLogs(manual = false) {
  16265. const limitEl = document.getElementById('logs-limit-select');
  16266. const limit = limitEl ? limitEl.value : '100';
  16267. try {
  16268. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16269. if (!res.ok) throw new Error('Failed to load logs');
  16270. const data = await res.json();
  16271. state.logs = data.logs || [];
  16272. renderLogsTable();
  16273. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16274. } catch (err) {
  16275. if (manual) showToast('Error', err.message, 'error');
  16276. }
  16277. // Setup auto-refresh if enabled and on logs tab
  16278. if (!logsTimer && state.currentUser) {
  16279. logsTimer = setInterval(() => {
  16280. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16281. const auto = document.getElementById('logs-auto-refresh');
  16282. if (auto && auto.checked) {
  16283. loadLogs(false);
  16284. }
  16285. }
  16286. }, 3000);
  16287. }
  16288. }
  16289. function renderLogsTable() {
  16290. const tbody = document.getElementById('logs-table-body');
  16291. if (!tbody) return;
  16292. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16293. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16294. const filtered = state.logs.filter(entry => {
  16295. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16296. return false;
  16297. }
  16298. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16299. return false;
  16300. }
  16301. return true;
  16302. });
  16303. if (filtered.length === 0) {
  16304. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16305. return;
  16306. }
  16307. tbody.innerHTML = filtered.map(l => {
  16308. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16309. const topLower = l.topics.toLowerCase();
  16310. if (topLower.includes('auth')) {
  16311. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16312. } else if (topLower.includes('dhcp')) {
  16313. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16314. } else if (topLower.includes('route')) {
  16315. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16316. } else if (topLower.includes('firewall')) {
  16317. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16318. } else if (topLower.includes('error')) {
  16319. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16320. } else if (topLower.includes('system')) {
  16321. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16322. }
  16323. const d = new Date(l.time);
  16324. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16325. return `
  16326. <tr class="hover:bg-slate-800/40 transition">
  16327. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16328. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16329. <td class="py-2 px-3 whitespace-nowrap">
  16330. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16331. </td>
  16332. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16333. </tr>
  16334. `;
  16335. }).join('');
  16336. }
  16337. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16338. state.certificates = [];
  16339. async function loadCertificates(manual = false) {
  16340. try {
  16341. const res = await fetch(`${API_BASE}/certificates`);
  16342. if (!res.ok) throw new Error('Failed to load certificates');
  16343. state.certificates = await res.json() || [];
  16344. updateCertificatesBadges();
  16345. renderCertificatesTable();
  16346. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16347. } catch (err) {
  16348. if (manual) showToast('Error', err.message, 'error');
  16349. }
  16350. }
  16351. function updateCertificatesBadges() {
  16352. const total = (state.certificates || []).length;
  16353. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16354. const bCount = document.getElementById('badge-certs-count');
  16355. if (bCount) bCount.innerText = total;
  16356. const kpiTotal = document.getElementById('kpi-certs-total');
  16357. if (kpiTotal) kpiTotal.innerText = total;
  16358. const kpiCA = document.getElementById('kpi-certs-ca');
  16359. if (kpiCA) kpiCA.innerText = caCount;
  16360. const kpiHttps = document.getElementById('kpi-https-status');
  16361. if (kpiHttps) {
  16362. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16363. if (sslSvc) {
  16364. if (!sslSvc.disabled) {
  16365. 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>`;
  16366. } else {
  16367. 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>`;
  16368. }
  16369. }
  16370. }
  16371. }
  16372. function renderCertificatesTable() {
  16373. const tbody = document.getElementById('certs-table-body');
  16374. if (!tbody) return;
  16375. if (!state.certificates || state.certificates.length === 0) {
  16376. 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>';
  16377. return;
  16378. }
  16379. tbody.innerHTML = state.certificates.map(c => {
  16380. let typeBadge = '';
  16381. if (c.is_ca) {
  16382. 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>';
  16383. } else if (c.type === 'acme') {
  16384. 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>';
  16385. } else if (c.issuer && c.issuer !== c.common_name) {
  16386. 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>';
  16387. } else {
  16388. 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>';
  16389. }
  16390. const sansHtml = (c.sans && c.sans.length > 0)
  16391. ? 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('')
  16392. : '<span class="text-slate-500">-</span>';
  16393. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16394. let validStr = '-';
  16395. let validBadge = '';
  16396. if (validTo && !isNaN(validTo.getTime())) {
  16397. const now = new Date();
  16398. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16399. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16400. if (daysLeft < 0) {
  16401. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16402. } else if (daysLeft < 30) {
  16403. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16404. } else {
  16405. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16406. }
  16407. }
  16408. return `
  16409. <tr class="hover:bg-slate-800/40 transition">
  16410. <td class="py-3 px-4">${typeBadge}</td>
  16411. <td class="py-3 px-4">
  16412. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16413. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16414. </td>
  16415. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16416. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16417. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16418. <span>${validStr}</span> ${validBadge}
  16419. ${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>` : ''}
  16420. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16421. </td>
  16422. <td class="py-3 px-4 text-right whitespace-nowrap">
  16423. <div class="flex items-center justify-end gap-1.5">
  16424. <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">
  16425. <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>
  16426. <span>View</span>
  16427. </button>
  16428. <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">
  16429. <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>
  16430. </button>
  16431. </div>
  16432. </td>
  16433. </tr>
  16434. `;
  16435. }).join('');
  16436. }
  16437. // Create CA
  16438. function openCreateCAModal() {
  16439. document.getElementById('form-create-ca').reset();
  16440. document.getElementById('ca-days').value = '3650';
  16441. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16442. document.getElementById('ca-country').value = 'GR';
  16443. document.getElementById('ca-key-type').value = 'RSA-2048';
  16444. document.getElementById('modal-create-ca').classList.remove('hidden');
  16445. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16446. }
  16447. function closeCreateCAModal() {
  16448. document.getElementById('modal-create-ca').classList.add('hidden');
  16449. }
  16450. async function submitCreateCA(event) {
  16451. event.preventDefault();
  16452. const payload = {
  16453. name: document.getElementById('ca-name').value.trim(),
  16454. common_name: document.getElementById('ca-cn').value.trim(),
  16455. organization: document.getElementById('ca-org').value.trim(),
  16456. country: document.getElementById('ca-country').value.trim(),
  16457. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16458. key_type: document.getElementById('ca-key-type').value
  16459. };
  16460. try {
  16461. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16462. method: 'POST',
  16463. headers: { 'Content-Type': 'application/json' },
  16464. body: JSON.stringify(payload)
  16465. });
  16466. if (!res.ok) {
  16467. const errData = await res.json();
  16468. throw new Error(errData.message || 'Failed to create CA');
  16469. }
  16470. closeCreateCAModal();
  16471. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16472. await loadCertificates();
  16473. } catch (err) {
  16474. showToast('Error', err.message, 'error');
  16475. }
  16476. }
  16477. // Create Cert
  16478. function openCreateCertModal() {
  16479. document.getElementById('form-create-cert').reset();
  16480. document.getElementById('cert-days').value = '730';
  16481. document.getElementById('cert-key-type').value = 'RSA-2048';
  16482. const caSelect = document.getElementById('cert-ca-select');
  16483. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16484. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16485. const opt = document.createElement('option');
  16486. opt.value = ca.name;
  16487. opt.textContent = `${ca.name} (${ca.common_name})`;
  16488. caSelect.appendChild(opt);
  16489. });
  16490. document.getElementById('modal-create-cert').classList.remove('hidden');
  16491. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16492. }
  16493. function closeCreateCertModal() {
  16494. document.getElementById('modal-create-cert').classList.add('hidden');
  16495. }
  16496. async function submitCreateCert(event) {
  16497. event.preventDefault();
  16498. const rawSans = document.getElementById('cert-sans').value;
  16499. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16500. const caName = document.getElementById('cert-ca-select').value;
  16501. const payload = {
  16502. name: document.getElementById('cert-name').value.trim(),
  16503. common_name: document.getElementById('cert-cn').value.trim(),
  16504. ca_name: caName,
  16505. sans: sansList,
  16506. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16507. key_type: document.getElementById('cert-key-type').value,
  16508. is_server: true
  16509. };
  16510. try {
  16511. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16512. method: 'POST',
  16513. headers: { 'Content-Type': 'application/json' },
  16514. body: JSON.stringify(payload)
  16515. });
  16516. if (!res.ok) {
  16517. const errData = await res.json();
  16518. throw new Error(errData.message || 'Failed to issue certificate');
  16519. }
  16520. closeCreateCertModal();
  16521. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16522. await loadCertificates();
  16523. } catch (err) {
  16524. showToast('Error', err.message, 'error');
  16525. }
  16526. }
  16527. // Let's Encrypt
  16528. function openLetsEncryptModal() {
  16529. document.getElementById('form-letsencrypt').reset();
  16530. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16531. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16532. }
  16533. function closeLetsEncryptModal() {
  16534. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16535. }
  16536. async function submitLetsEncrypt(event) {
  16537. event.preventDefault();
  16538. const domain = document.getElementById('le-domain').value.trim();
  16539. const email = document.getElementById('le-email').value.trim();
  16540. let name = document.getElementById('le-name').value.trim();
  16541. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16542. const staging = document.getElementById('le-staging').checked;
  16543. const btn = document.getElementById('btn-submit-letsencrypt');
  16544. const origBtnHtml = btn.innerHTML;
  16545. btn.disabled = true;
  16546. 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>`;
  16547. try {
  16548. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16549. method: 'POST',
  16550. headers: { 'Content-Type': 'application/json' },
  16551. body: JSON.stringify({
  16552. name: name,
  16553. domain: domain,
  16554. email: email,
  16555. staging: staging
  16556. })
  16557. });
  16558. if (!res.ok) {
  16559. const errData = await res.json();
  16560. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16561. }
  16562. closeLetsEncryptModal();
  16563. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16564. await loadCertificates();
  16565. } catch (err) {
  16566. showToast('Let\'s Encrypt Error', err.message, 'error');
  16567. } finally {
  16568. btn.disabled = false;
  16569. btn.innerHTML = origBtnHtml;
  16570. }
  16571. }
  16572. // Import Cert
  16573. function openImportCertModal() {
  16574. document.getElementById('form-import-cert').reset();
  16575. document.getElementById('modal-import-cert').classList.remove('hidden');
  16576. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16577. }
  16578. function closeImportCertModal() {
  16579. document.getElementById('modal-import-cert').classList.add('hidden');
  16580. }
  16581. async function submitImportCert(event) {
  16582. event.preventDefault();
  16583. const payload = {
  16584. name: document.getElementById('import-cert-name').value.trim(),
  16585. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16586. key_pem: document.getElementById('import-key-pem').value.trim()
  16587. };
  16588. try {
  16589. const res = await fetch(`${API_BASE}/certificates/import`, {
  16590. method: 'POST',
  16591. headers: { 'Content-Type': 'application/json' },
  16592. body: JSON.stringify(payload)
  16593. });
  16594. if (!res.ok) {
  16595. const errData = await res.json();
  16596. throw new Error(errData.message || 'Failed to import certificate');
  16597. }
  16598. closeImportCertModal();
  16599. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16600. await loadCertificates();
  16601. } catch (err) {
  16602. showToast('Error', err.message, 'error');
  16603. }
  16604. }
  16605. // View / Export Modal
  16606. async function openViewCertModal(name) {
  16607. const c = (state.certificates || []).find(x => x.name === name);
  16608. if (!c) return;
  16609. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16610. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16611. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16612. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16613. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16614. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16615. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16616. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16617. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16618. document.getElementById('modal-view-cert').classList.remove('hidden');
  16619. try {
  16620. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16621. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16622. const data = await res.json();
  16623. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16624. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16625. } catch (err) {
  16626. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16627. document.getElementById('view-key-pem-text').value = '';
  16628. }
  16629. }
  16630. function closeViewCertModal() {
  16631. document.getElementById('modal-view-cert').classList.add('hidden');
  16632. }
  16633. function copyCertPEM() {
  16634. const text = document.getElementById('view-cert-pem-text').value;
  16635. if (!text) return;
  16636. navigator.clipboard.writeText(text).then(() => {
  16637. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16638. }).catch(() => {
  16639. showToast('Error', 'Failed to copy to clipboard', 'error');
  16640. });
  16641. }
  16642. function copyKeyPEM() {
  16643. const text = document.getElementById('view-key-pem-text').value;
  16644. if (!text) return;
  16645. navigator.clipboard.writeText(text).then(() => {
  16646. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16647. }).catch(() => {
  16648. showToast('Error', 'Failed to copy to clipboard', 'error');
  16649. });
  16650. }
  16651. async function deleteCertificate(name) {
  16652. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16653. return;
  16654. }
  16655. try {
  16656. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16657. method: 'DELETE'
  16658. });
  16659. if (!res.ok) {
  16660. const errData = await res.json();
  16661. throw new Error(errData.message || 'Failed to delete certificate');
  16662. }
  16663. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16664. await loadCertificates();
  16665. } catch (err) {
  16666. showToast('Error', err.message, 'error');
  16667. }
  16668. }
  16669. // Refresh immediately when returning to a backgrounded controller tab.
  16670. document.addEventListener('visibilitychange', () => {
  16671. if (!state.currentUser) return;
  16672. if (document.hidden) {
  16673. if (trafficEventSource) trafficEventSource.close();
  16674. trafficEventSource = null;
  16675. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16676. trafficPollFallback = null;
  16677. } else {
  16678. fetchData(false);
  16679. initLiveTrafficStream();
  16680. if (state.activeTab === 'bwtest') loadBwTestView();
  16681. }
  16682. });
  16683. async function loadUpdateStatus(populate = true) {
  16684. try {
  16685. const res = await fetch(`${API_BASE}/update/status`);
  16686. if (!res.ok) throw new Error(await responseError(res));
  16687. const data = await res.json();
  16688. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16689. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16690. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16691. document.getElementById('update-state').textContent = data.state || 'idle';
  16692. document.getElementById('update-log').textContent = data.log || '';
  16693. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16694. }
  16695. async function saveUpdateConfig() {
  16696. try {
  16697. const repository = document.getElementById('update-repository').value.trim();
  16698. const branch = 'master';
  16699. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16700. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16701. if (!res.ok) throw new Error(await responseError(res));
  16702. document.getElementById('update-install-button').disabled = true;
  16703. document.getElementById('update-available').textContent = '—';
  16704. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16705. await loadUpdateStatus(false);
  16706. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16707. }
  16708. async function checkUpdate() {
  16709. try {
  16710. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16711. if (!res.ok) throw new Error(await responseError(res));
  16712. const data = await res.json();
  16713. document.getElementById('update-available').textContent = data.available_version;
  16714. document.getElementById('update-install-button').disabled = !data.update_available;
  16715. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16716. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16717. }
  16718. async function startUpdate(action) {
  16719. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16720. try {
  16721. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16722. if (!res.ok) throw new Error(await responseError(res));
  16723. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16724. await loadUpdateStatus(false);
  16725. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16726. }
  16727. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16728. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16729. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16730. function safeFirewallRow(row) {
  16731. const result = {...row};
  16732. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16733. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16734. return result;
  16735. }
  16736. function setFirewallDays(prefix, days) {
  16737. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16738. 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); }
  16739. }
  16740. function getFirewallDays(prefix) {
  16741. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16742. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16743. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16744. return selected.join(',');
  16745. }
  16746. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16747. const id = document.getElementById(kind+'-modal-id')?.value;
  16748. if (!id) { resetDisplay(); return; }
  16749. try {
  16750. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16751. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16752. resetDisplay(); await loadFirewall(false);
  16753. } catch(error) { showToast('Error', error.message, 'error'); }
  16754. }
  16755. function reviewLegacyFirewallSettings(kind, id) {
  16756. if (!id) return true;
  16757. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16758. const rule = (rows || []).find(r => r.id === id);
  16759. if (!rule) return true;
  16760. 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'];
  16761. const present = unsupported.filter(key => rule[key]);
  16762. if (!present.length) return true;
  16763. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16764. }
  16765. function refreshFirewallRejectTypes() {
  16766. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16767. const old=select.value;
  16768. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16769. 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'];
  16770. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16771. if(types.includes(old))select.value=old;
  16772. }
  16773. function setFirewallActionSelection(kind, value) {
  16774. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16775. if(!Array.from(select.options).some(option=>option.value===value)) {
  16776. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16777. }
  16778. select.value=value;
  16779. }
  16780. // ==========================================
  16781. // REVERSE PROXY & APPLICATION GATEWAY
  16782. // ==========================================
  16783. state.proxyRules = [];
  16784. state.proxyConfig = null;
  16785. async function loadReverseProxy(manual = false) {
  16786. try {
  16787. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16788. fetch(`${API_BASE}/proxy/config`),
  16789. fetch(`${API_BASE}/proxy/rules`),
  16790. fetch(`${API_BASE}/certificates`).catch(() => null)
  16791. ]);
  16792. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16793. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16794. state.proxyConfig = await cfgRes.json();
  16795. state.proxyRules = await rulesRes.json() || [];
  16796. if (certsRes && certsRes.ok) {
  16797. state.certificates = await certsRes.json() || [];
  16798. }
  16799. renderProxyRules(state.proxyRules);
  16800. updateProxyMetrics();
  16801. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16802. } catch (err) {
  16803. console.error('loadReverseProxy error:', err);
  16804. if (manual) showToast('Error', err.message, 'error');
  16805. }
  16806. }
  16807. function updateProxyMetrics() {
  16808. const badge = document.getElementById('badge-proxy-count');
  16809. if (badge) badge.textContent = (state.proxyRules || []).length;
  16810. const metricRules = document.getElementById('proxy-metric-rules');
  16811. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16812. const cfg = state.proxyConfig;
  16813. const statusEl = document.getElementById('proxy-metric-status');
  16814. const portsEl = document.getElementById('proxy-metric-ports');
  16815. if (cfg) {
  16816. if (statusEl) {
  16817. if (cfg.enabled) {
  16818. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16819. } else {
  16820. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16821. }
  16822. }
  16823. if (portsEl) {
  16824. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16825. }
  16826. }
  16827. let totalRequests = 0;
  16828. const certSet = new Set();
  16829. (state.proxyRules || []).forEach(r => {
  16830. totalRequests += (r.stats && r.stats.requests) || 0;
  16831. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16832. });
  16833. const metricRequests = document.getElementById('proxy-metric-requests');
  16834. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16835. const metricCerts = document.getElementById('proxy-metric-certs');
  16836. if (metricCerts) metricCerts.textContent = certSet.size;
  16837. }
  16838. function renderProxyRules(rules) {
  16839. const tbody = document.getElementById('proxy-rules-table-body');
  16840. if (!tbody) return;
  16841. if (!rules || rules.length === 0) {
  16842. 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>';
  16843. return;
  16844. }
  16845. tbody.innerHTML = rules.map(r => {
  16846. const isEnabled = r.enabled !== false;
  16847. 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>';
  16848. 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>`;
  16849. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16850. 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>';
  16851. 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>';
  16852. 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>` : '';
  16853. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16854. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16855. return `
  16856. <tr class="hover:bg-slate-800/40 transition">
  16857. <td class="py-3 px-4">
  16858. <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'}">
  16859. <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>
  16860. </button>
  16861. </td>
  16862. <td class="py-3 px-4">
  16863. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16864. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16865. </td>
  16866. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16867. ${domainsStr}
  16868. </td>
  16869. <td class="py-3 px-4">
  16870. ${pathBadge}
  16871. </td>
  16872. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16873. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16874. </td>
  16875. <td class="py-3 px-4 whitespace-nowrap">
  16876. ${protoBadge}${certBadge}
  16877. </td>
  16878. <td class="py-3 px-4 font-mono">
  16879. ${stripBadge}
  16880. </td>
  16881. <td class="py-3 px-4 font-mono text-slate-300">
  16882. ${requests}
  16883. </td>
  16884. <td class="py-3 px-4 text-right whitespace-nowrap">
  16885. <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>
  16886. <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>
  16887. </td>
  16888. </tr>
  16889. `;
  16890. }).join('');
  16891. }
  16892. function populateProxyCertDropdown(selectedVal = '') {
  16893. const select = document.getElementById('proxy-rule-cert');
  16894. if (!select) return;
  16895. const certs = state.certificates || [];
  16896. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16897. certs.filter(c => !c.is_ca).forEach(c => {
  16898. const opt = document.createElement('option');
  16899. opt.value = c.name;
  16900. const cn = c.common_name ? ` (${c.common_name})` : '';
  16901. opt.textContent = `${c.name}${cn}`;
  16902. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16903. opt.selected = true;
  16904. }
  16905. select.appendChild(opt);
  16906. });
  16907. }
  16908. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16909. const select = document.getElementById('proxy-cfg-default-cert');
  16910. if (!select) return;
  16911. const certs = state.certificates || [];
  16912. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16913. certs.filter(c => !c.is_ca).forEach(c => {
  16914. const opt = document.createElement('option');
  16915. opt.value = c.name;
  16916. const cn = c.common_name ? ` (${c.common_name})` : '';
  16917. opt.textContent = `${c.name}${cn}`;
  16918. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16919. opt.selected = true;
  16920. }
  16921. select.appendChild(opt);
  16922. });
  16923. }
  16924. function onProxyProtoChange() {
  16925. const proto = document.getElementById('proxy-rule-proto')?.value;
  16926. const certSelect = document.getElementById('proxy-rule-cert');
  16927. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16928. if (proto === 'http') {
  16929. if (certSelect) certSelect.disabled = true;
  16930. if (redirectCheck) redirectCheck.disabled = true;
  16931. } else {
  16932. if (certSelect) certSelect.disabled = false;
  16933. if (redirectCheck) redirectCheck.disabled = false;
  16934. }
  16935. }
  16936. function openAddProxyRuleModal() {
  16937. const modal = document.getElementById('modal-proxy-rule');
  16938. if (!modal) return;
  16939. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16940. <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>
  16941. <span>Add Reverse Proxy Rule</span>
  16942. `;
  16943. document.getElementById('proxy-rule-id').value = '';
  16944. document.getElementById('proxy-rule-name').value = '';
  16945. document.getElementById('proxy-rule-domains').value = '';
  16946. document.getElementById('proxy-rule-path').value = '/';
  16947. document.getElementById('proxy-rule-target').value = '';
  16948. document.getElementById('proxy-rule-proto').value = 'both';
  16949. document.getElementById('proxy-rule-strip-path').checked = false;
  16950. document.getElementById('proxy-rule-http-to-https').checked = false;
  16951. document.getElementById('proxy-rule-preserve-host').checked = false;
  16952. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16953. document.getElementById('proxy-rule-enabled').checked = true;
  16954. document.getElementById('proxy-rule-comment').value = '';
  16955. populateProxyCertDropdown('');
  16956. onProxyProtoChange();
  16957. modal.classList.remove('hidden');
  16958. }
  16959. function openEditProxyRuleModal(id) {
  16960. const modal = document.getElementById('modal-proxy-rule');
  16961. if (!modal) return;
  16962. const rule = (state.proxyRules || []).find(r => r.id === id);
  16963. if (!rule) {
  16964. showToast('Error', 'Rule not found', 'error');
  16965. return;
  16966. }
  16967. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16968. <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>
  16969. <span>Edit Reverse Proxy Rule</span>
  16970. `;
  16971. document.getElementById('proxy-rule-id').value = rule.id || '';
  16972. document.getElementById('proxy-rule-name').value = rule.name || '';
  16973. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16974. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16975. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16976. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16977. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16978. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16979. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16980. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16981. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16982. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16983. populateProxyCertDropdown(rule.certificate || '');
  16984. onProxyProtoChange();
  16985. modal.classList.remove('hidden');
  16986. }
  16987. function closeProxyRuleModal() {
  16988. const modal = document.getElementById('modal-proxy-rule');
  16989. if (modal) modal.classList.add('hidden');
  16990. }
  16991. async function saveProxyRule(event) {
  16992. event.preventDefault();
  16993. const id = document.getElementById('proxy-rule-id').value;
  16994. const name = document.getElementById('proxy-rule-name').value.trim();
  16995. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16996. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16997. const target = document.getElementById('proxy-rule-target').value.trim();
  16998. const proto = document.getElementById('proxy-rule-proto').value;
  16999. const cert = document.getElementById('proxy-rule-cert').value;
  17000. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  17001. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  17002. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  17003. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  17004. const enabled = document.getElementById('proxy-rule-enabled').checked;
  17005. const comment = document.getElementById('proxy-rule-comment').value.trim();
  17006. let domains = [];
  17007. if (rawDomains && rawDomains !== '*') {
  17008. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  17009. }
  17010. const payload = {
  17011. id: id || undefined,
  17012. name,
  17013. domains,
  17014. path: pathVal,
  17015. target_url: target,
  17016. protocol: proto,
  17017. certificate: cert,
  17018. strip_path: stripPath,
  17019. http_to_https: httpToHttps,
  17020. preserve_host: preserveHost,
  17021. insecure_tls: insecureTLS,
  17022. enabled,
  17023. comment
  17024. };
  17025. try {
  17026. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  17027. const method = id ? 'PUT' : 'POST';
  17028. const res = await fetch(url, {
  17029. method,
  17030. headers: { 'Content-Type': 'application/json' },
  17031. body: JSON.stringify(payload)
  17032. });
  17033. if (!res.ok) {
  17034. const errData = await res.json().catch(() => ({}));
  17035. throw new Error(errData.message || 'Failed to save proxy rule');
  17036. }
  17037. closeProxyRuleModal();
  17038. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  17039. await loadReverseProxy(false);
  17040. } catch (err) {
  17041. showToast('Error', err.message, 'error');
  17042. }
  17043. }
  17044. async function deleteProxyRule(id) {
  17045. const rule = (state.proxyRules || []).find(r => r.id === id);
  17046. const name = rule ? rule.name : id;
  17047. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  17048. return;
  17049. }
  17050. try {
  17051. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  17052. method: 'DELETE'
  17053. });
  17054. if (!res.ok) {
  17055. const errData = await res.json().catch(() => ({}));
  17056. throw new Error(errData.message || 'Failed to delete rule');
  17057. }
  17058. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17059. await loadReverseProxy(false);
  17060. } catch (err) {
  17061. showToast('Error', err.message, 'error');
  17062. }
  17063. }
  17064. async function toggleProxyRuleState(id, currentState) {
  17065. try {
  17066. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17067. method: 'POST',
  17068. headers: { 'Content-Type': 'application/json' },
  17069. body: JSON.stringify({ enabled: !currentState })
  17070. });
  17071. if (!res.ok) {
  17072. const errData = await res.json().catch(() => ({}));
  17073. throw new Error(errData.message || 'Failed to toggle rule state');
  17074. }
  17075. await loadReverseProxy(false);
  17076. } catch (err) {
  17077. showToast('Error', err.message, 'error');
  17078. }
  17079. }
  17080. function openProxyConfigModal() {
  17081. const modal = document.getElementById('modal-proxy-config');
  17082. if (!modal) return;
  17083. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17084. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17085. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17086. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17087. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17088. modal.classList.remove('hidden');
  17089. }
  17090. function closeProxyConfigModal() {
  17091. const modal = document.getElementById('modal-proxy-config');
  17092. if (modal) modal.classList.add('hidden');
  17093. }
  17094. async function saveProxyConfig(event) {
  17095. event.preventDefault();
  17096. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17097. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17098. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17099. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17100. const payload = {
  17101. enabled,
  17102. http_port: httpPort,
  17103. https_port: httpsPort,
  17104. default_cert: defaultCert
  17105. };
  17106. try {
  17107. const res = await fetch(`${API_BASE}/proxy/config`, {
  17108. method: 'POST',
  17109. headers: { 'Content-Type': 'application/json' },
  17110. body: JSON.stringify(payload)
  17111. });
  17112. if (!res.ok) {
  17113. const errData = await res.json().catch(() => ({}));
  17114. throw new Error(errData.message || 'Failed to update proxy settings');
  17115. }
  17116. closeProxyConfigModal();
  17117. showToast('Success', 'Reverse proxy settings updated', 'success');
  17118. await loadReverseProxy(false);
  17119. } catch (err) {
  17120. showToast('Error', err.message, 'error');
  17121. }
  17122. }
  17123. // ==================== SD-WAN Controller ====================
  17124. async function loadSDWAN(manual = false) {
  17125. try {
  17126. const [groupsRes, telemetryRes] = await Promise.all([
  17127. fetch(`${API_BASE}/sdwan/groups`),
  17128. fetch(`${API_BASE}/sdwan/telemetry`)
  17129. ]);
  17130. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17131. state.sdwanGroups = await groupsRes.json() || [];
  17132. if (telemetryRes.ok) {
  17133. state.sdwanTelemetry = await telemetryRes.json() || {};
  17134. }
  17135. renderSDWANGroups(state.sdwanGroups);
  17136. renderSDWANMembers(state.sdwanGroups);
  17137. updateSDWANMetrics(state.sdwanTelemetry);
  17138. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17139. } catch (err) {
  17140. console.error('loadSDWAN error:', err);
  17141. if (manual) showToast('Error', err.message, 'error');
  17142. }
  17143. }
  17144. function updateSDWANMetrics(telemetry) {
  17145. const groups = state.sdwanGroups || [];
  17146. const t = telemetry || {};
  17147. const badge = document.getElementById('badge-sdwan-count');
  17148. if (badge) badge.textContent = groups.length;
  17149. const metricGroups = document.getElementById('sdwan-metric-groups');
  17150. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17151. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17152. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17153. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17154. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17155. const metricDown = document.getElementById('sdwan-metric-down');
  17156. if (metricDown) metricDown.textContent = t.down_members || 0;
  17157. }
  17158. function renderSDWANGroups(groups) {
  17159. const tbody = document.getElementById('sdwan-groups-table-body');
  17160. if (!tbody) return;
  17161. if (!groups || groups.length === 0) {
  17162. 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>';
  17163. return;
  17164. }
  17165. tbody.innerHTML = groups.map(g => {
  17166. const isEnabled = g.disabled !== true;
  17167. const members = g.members || [];
  17168. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17169. // Build distribution progress bar
  17170. let distHtml = '';
  17171. if (members.length === 0) {
  17172. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17173. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17174. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17175. const segments = members.map((m, idx) => {
  17176. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17177. const col = colors[idx % colors.length];
  17178. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17179. }).join('');
  17180. const labels = members.map((m, idx) => {
  17181. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17182. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17183. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17184. }).join('');
  17185. distHtml = `
  17186. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17187. <div class="flex flex-wrap">${labels}</div>
  17188. `;
  17189. } else if (g.mode === 'lowest-latency') {
  17190. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17191. } else if (g.mode === 'lowest-loss') {
  17192. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17193. } else if (g.mode === 'failover') {
  17194. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17195. }
  17196. let modeBadge = '';
  17197. switch (g.mode) {
  17198. case 'weighted':
  17199. 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>';
  17200. break;
  17201. case 'pcc':
  17202. 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>';
  17203. break;
  17204. case 'lowest-latency':
  17205. 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>';
  17206. break;
  17207. case 'lowest-loss':
  17208. 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>';
  17209. break;
  17210. case 'failover':
  17211. 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>';
  17212. break;
  17213. default:
  17214. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17215. }
  17216. const autoNatBadge = g.auto_nat
  17217. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17218. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17219. return `
  17220. <tr class="hover:bg-slate-800/40 transition">
  17221. <td class="py-3 px-4">
  17222. <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'}">
  17223. <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>
  17224. </button>
  17225. </td>
  17226. <td class="py-3 px-4">
  17227. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17228. <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>
  17229. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17230. </div>
  17231. </td>
  17232. <td class="py-3 px-4">${modeBadge}</td>
  17233. <td class="py-3 px-4">${distHtml}</td>
  17234. <td class="py-3 px-4">
  17235. <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>
  17236. </td>
  17237. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17238. <td class="py-3 px-4">${autoNatBadge}</td>
  17239. <td class="py-3 px-4 text-right">
  17240. <div class="flex items-center justify-end gap-1.5">
  17241. <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">
  17242. <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>
  17243. </button>
  17244. <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">
  17245. <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>
  17246. </button>
  17247. <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">
  17248. <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>
  17249. </button>
  17250. </div>
  17251. </td>
  17252. </tr>
  17253. `;
  17254. }).join('');
  17255. }
  17256. function renderSDWANMembers(groups) {
  17257. const tbody = document.getElementById('sdwan-members-table-body');
  17258. if (!tbody) return;
  17259. const allMembers = [];
  17260. (groups || []).forEach(g => {
  17261. (g.members || []).forEach(m => {
  17262. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17263. });
  17264. });
  17265. if (allMembers.length === 0) {
  17266. 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>';
  17267. return;
  17268. }
  17269. tbody.innerHTML = allMembers.map(m => {
  17270. const isEnabled = m.disabled !== true;
  17271. 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>';
  17272. if (!isEnabled) {
  17273. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17274. } else if (m.status === 'DEGRADED') {
  17275. 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>';
  17276. } else if (m.status === 'DOWN') {
  17277. 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>';
  17278. }
  17279. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17280. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17281. return `
  17282. <tr class="hover:bg-slate-800/40 transition">
  17283. <td class="py-3 px-4">
  17284. <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'}">
  17285. <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>
  17286. </button>
  17287. </td>
  17288. <td class="py-3 px-4">
  17289. <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>
  17290. </td>
  17291. <td class="py-3 px-4">
  17292. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17293. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17294. </td>
  17295. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17296. <td class="py-3 px-4">
  17297. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17298. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17299. </td>
  17300. <td class="py-3 px-4">${statusBadge}</td>
  17301. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17302. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17303. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17304. </td>
  17305. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17306. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17307. </td>
  17308. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17309. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17310. </td>
  17311. <td class="py-3 px-4 text-right">
  17312. <div class="flex items-center justify-end gap-1.5">
  17313. <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">
  17314. <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>
  17315. </button>
  17316. <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">
  17317. <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>
  17318. </button>
  17319. </div>
  17320. </td>
  17321. </tr>
  17322. `;
  17323. }).join('');
  17324. }
  17325. // Modal handling for SD-WAN Groups
  17326. function openAddSDWANGroupModal() {
  17327. const modal = document.getElementById('modal-sdwan-group');
  17328. if (!modal) return;
  17329. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17330. document.getElementById('sdwan-group-id').value = '';
  17331. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17332. document.getElementById('sdwan-group-name').disabled = false;
  17333. document.getElementById('sdwan-group-mode').value = 'weighted';
  17334. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17335. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17336. document.getElementById('sdwan-group-probe-interval').value = 3;
  17337. document.getElementById('sdwan-group-auto-nat').checked = true;
  17338. document.getElementById('sdwan-group-comment').value = '';
  17339. modal.classList.remove('hidden');
  17340. }
  17341. function openEditSDWANGroupModal(id) {
  17342. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17343. if (!group) return;
  17344. const modal = document.getElementById('modal-sdwan-group');
  17345. if (!modal) return;
  17346. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17347. document.getElementById('sdwan-group-id').value = group.id;
  17348. document.getElementById('sdwan-group-name').value = group.name;
  17349. document.getElementById('sdwan-group-name').disabled = true;
  17350. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17351. if (group.mode === 'pcc') {
  17352. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17353. } else {
  17354. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17355. }
  17356. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17357. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17358. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17359. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17360. modal.classList.remove('hidden');
  17361. }
  17362. function closeSDWANGroupModal() {
  17363. const modal = document.getElementById('modal-sdwan-group');
  17364. if (modal) modal.classList.add('hidden');
  17365. }
  17366. function onSDWANModeChange() {
  17367. const mode = document.getElementById('sdwan-group-mode').value;
  17368. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17369. if (pccContainer) {
  17370. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17371. else pccContainer.classList.add('hidden');
  17372. }
  17373. }
  17374. async function saveSDWANGroup(event) {
  17375. event.preventDefault();
  17376. const id = document.getElementById('sdwan-group-id').value;
  17377. const name = document.getElementById('sdwan-group-name').value.trim();
  17378. const mode = document.getElementById('sdwan-group-mode').value;
  17379. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17380. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17381. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17382. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17383. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17384. const payload = {
  17385. id: id || undefined,
  17386. name,
  17387. mode,
  17388. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17389. probe_interval: probeInterval,
  17390. auto_nat: autoNAT,
  17391. comment,
  17392. members: existing ? existing.members : undefined
  17393. };
  17394. try {
  17395. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17396. method: 'POST',
  17397. headers: { 'Content-Type': 'application/json' },
  17398. body: JSON.stringify(payload)
  17399. });
  17400. if (!res.ok) {
  17401. const err = await res.json().catch(() => ({}));
  17402. throw new Error(err.message || 'Failed to save SD-WAN group');
  17403. }
  17404. closeSDWANGroupModal();
  17405. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17406. await loadSDWAN(false);
  17407. } catch (err) {
  17408. showToast('Error', err.message, 'error');
  17409. }
  17410. }
  17411. async function toggleSDWANGroupState(id, currentState) {
  17412. try {
  17413. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17414. method: 'POST',
  17415. headers: { 'Content-Type': 'application/json' },
  17416. body: JSON.stringify({ disabled: currentState })
  17417. });
  17418. if (!res.ok) throw new Error('Failed to update group state');
  17419. await loadSDWAN(false);
  17420. } catch (err) {
  17421. showToast('Error', err.message, 'error');
  17422. }
  17423. }
  17424. async function deleteSDWANGroup(id) {
  17425. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17426. const name = group ? group.name : id;
  17427. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17428. try {
  17429. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17430. method: 'DELETE'
  17431. });
  17432. if (!res.ok) {
  17433. const err = await res.json().catch(() => ({}));
  17434. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17435. }
  17436. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17437. await loadSDWAN(false);
  17438. } catch (err) {
  17439. showToast('Error', err.message, 'error');
  17440. }
  17441. }
  17442. // Modal handling for SD-WAN Members
  17443. function populateSDWANGroupsSelect(selectedId = '') {
  17444. const sel = document.getElementById('sdwan-member-group-id');
  17445. if (!sel) return;
  17446. sel.innerHTML = '';
  17447. (state.sdwanGroups || []).forEach(g => {
  17448. const opt = document.createElement('option');
  17449. opt.value = g.id;
  17450. opt.textContent = `${g.name} (${g.mode})`;
  17451. if (g.id === selectedId) opt.selected = true;
  17452. sel.appendChild(opt);
  17453. });
  17454. }
  17455. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17456. const sel = document.getElementById('sdwan-member-interface');
  17457. if (!sel) return;
  17458. sel.innerHTML = '';
  17459. (state.interfaces || []).forEach(i => {
  17460. const opt = document.createElement('option');
  17461. opt.value = i.name;
  17462. opt.textContent = `${i.name} (${i.role || i.type})`;
  17463. if (i.name === selectedVal) opt.selected = true;
  17464. sel.appendChild(opt);
  17465. });
  17466. }
  17467. function openAddSDWANMemberModal(defaultGroupId = null) {
  17468. const modal = document.getElementById('modal-sdwan-member');
  17469. if (!modal) return;
  17470. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17471. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17472. return;
  17473. }
  17474. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17475. document.getElementById('sdwan-member-id').value = '';
  17476. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17477. populateSDWANMemberInterfaceSelect();
  17478. document.getElementById('sdwan-member-gateway').value = '';
  17479. document.getElementById('sdwan-member-weight').value = 50;
  17480. document.getElementById('sdwan-member-priority').value = 1;
  17481. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17482. document.getElementById('sdwan-member-max-lat').value = 250;
  17483. document.getElementById('sdwan-member-max-loss').value = 20;
  17484. document.getElementById('sdwan-member-comment').value = '';
  17485. modal.classList.remove('hidden');
  17486. }
  17487. function openEditSDWANMemberModal(groupId, memberId) {
  17488. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17489. if (!group) return;
  17490. const member = (group.members || []).find(m => m.id === memberId);
  17491. if (!member) return;
  17492. const modal = document.getElementById('modal-sdwan-member');
  17493. if (!modal) return;
  17494. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17495. document.getElementById('sdwan-member-id').value = member.id;
  17496. populateSDWANGroupsSelect(group.id);
  17497. document.getElementById('sdwan-member-group-id').disabled = true;
  17498. populateSDWANMemberInterfaceSelect(member.interface);
  17499. document.getElementById('sdwan-member-interface').disabled = true;
  17500. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17501. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17502. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17503. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17504. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17505. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17506. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17507. modal.classList.remove('hidden');
  17508. }
  17509. function closeSDWANMemberModal() {
  17510. const modal = document.getElementById('modal-sdwan-member');
  17511. if (modal) {
  17512. document.getElementById('sdwan-member-group-id').disabled = false;
  17513. document.getElementById('sdwan-member-interface').disabled = false;
  17514. modal.classList.add('hidden');
  17515. }
  17516. }
  17517. async function saveSDWANMember(event) {
  17518. event.preventDefault();
  17519. const id = document.getElementById('sdwan-member-id').value;
  17520. let groupId = document.getElementById('sdwan-member-group-id').value;
  17521. let iface = document.getElementById('sdwan-member-interface').value;
  17522. // In edit mode with disabled selects, fallback to existing member data if needed
  17523. if (id) {
  17524. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17525. if (existingGroup) {
  17526. if (!groupId) groupId = existingGroup.id;
  17527. const mem = (existingGroup.members || []).find(m => m.id === id);
  17528. if (mem && !iface) iface = mem.interface;
  17529. }
  17530. }
  17531. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17532. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17533. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17534. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17535. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17536. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17537. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17538. const payload = {
  17539. id: id || undefined,
  17540. interface: iface,
  17541. gateway,
  17542. weight,
  17543. priority,
  17544. target_probe: targetProbe,
  17545. max_latency: maxLatency,
  17546. max_loss: maxLoss,
  17547. comment
  17548. };
  17549. try {
  17550. const method = id ? 'PUT' : 'POST';
  17551. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17552. method,
  17553. headers: { 'Content-Type': 'application/json' },
  17554. body: JSON.stringify(payload)
  17555. });
  17556. if (!res.ok) {
  17557. const err = await res.json().catch(() => ({}));
  17558. throw new Error(err.message || 'Failed to save member link');
  17559. }
  17560. closeSDWANMemberModal();
  17561. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17562. await loadSDWAN(false);
  17563. } catch (err) {
  17564. showToast('Error', err.message, 'error');
  17565. }
  17566. }
  17567. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17568. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17569. if (!group) return;
  17570. const member = (group.members || []).find(m => m.id === memberId);
  17571. if (!member) return;
  17572. const payload = {
  17573. ...member,
  17574. disabled: currentState
  17575. };
  17576. try {
  17577. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17578. method: 'PUT',
  17579. headers: { 'Content-Type': 'application/json' },
  17580. body: JSON.stringify(payload)
  17581. });
  17582. if (!res.ok) throw new Error('Failed to update member state');
  17583. await loadSDWAN(false);
  17584. } catch (err) {
  17585. showToast('Error', err.message, 'error');
  17586. }
  17587. }
  17588. async function deleteSDWANMember(groupId, iface) {
  17589. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17590. try {
  17591. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17592. method: 'DELETE'
  17593. });
  17594. if (!res.ok) {
  17595. const err = await res.json().catch(() => ({}));
  17596. throw new Error(err.message || 'Failed to remove member link');
  17597. }
  17598. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17599. await loadSDWAN(false);
  17600. } catch (err) {
  17601. showToast('Error', err.message, 'error');
  17602. }
  17603. }
  17604. // ==============================================================================
  17605. // DYNAMIC ROUTING: RIP MODULE
  17606. // ==============================================================================
  17607. state.ripInstances = [];
  17608. state.ripInterfaces = [];
  17609. state.ripNeighborsLive = [];
  17610. state.ripRoutes = [];
  17611. state.selectedRipRow = {};
  17612. state.activeRipTab = 'instances';
  17613. function switchRipTab(tab) {
  17614. state.activeRipTab = tab;
  17615. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17616. const pane = document.getElementById(`rip-pane-${t}`);
  17617. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17618. if (pane) {
  17619. if (t === tab) pane.classList.remove('hidden');
  17620. else pane.classList.add('hidden');
  17621. }
  17622. if (btn) {
  17623. if (t === tab) {
  17624. 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';
  17625. } else {
  17626. 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';
  17627. }
  17628. }
  17629. });
  17630. }
  17631. function selectRipRow(tab, id) {
  17632. if (!state.selectedRipRow) state.selectedRipRow = {};
  17633. state.selectedRipRow[tab] = id;
  17634. if (tab === 'instances') {
  17635. renderRipInstances();
  17636. const btnEn = document.getElementById('btn-rip-inst-enable');
  17637. const btnDis = document.getElementById('btn-rip-inst-disable');
  17638. const btnRem = document.getElementById('btn-rip-inst-remove');
  17639. if (btnEn) btnEn.disabled = false;
  17640. if (btnDis) btnDis.disabled = false;
  17641. if (btnRem) btnRem.disabled = false;
  17642. } else if (tab === 'interfaces') {
  17643. renderRipInterfaces();
  17644. const btnEn = document.getElementById('btn-rip-iface-enable');
  17645. const btnDis = document.getElementById('btn-rip-iface-disable');
  17646. const btnRem = document.getElementById('btn-rip-iface-remove');
  17647. if (btnEn) btnEn.disabled = false;
  17648. if (btnDis) btnDis.disabled = false;
  17649. if (btnRem) btnRem.disabled = false;
  17650. }
  17651. }
  17652. function renderRipInstances() {
  17653. const tbody = document.getElementById('rip-instances-table-body');
  17654. if (!tbody) return;
  17655. const countEl = document.getElementById('rip-instances-footer-count');
  17656. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17657. let list = state.ripInstances || [];
  17658. if (filter) {
  17659. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17660. }
  17661. if (countEl) countEl.innerText = list.length;
  17662. const selId = state.selectedRipRow?.instances;
  17663. tbody.innerHTML = list.map((inst, idx) => {
  17664. const isSel = inst.id === selId;
  17665. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17666. const flagD = inst.disabled
  17667. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  17668. : (inst.running
  17669. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  17670. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  17671. const redist = [];
  17672. if (inst.redistribute_connected) redist.push('conn');
  17673. if (inst.redistribute_static) redist.push('static');
  17674. if (inst.redistribute_bgp) redist.push('bgp');
  17675. if (inst.redistribute_ospf) redist.push('ospf');
  17676. if (inst.redistribute_default) redist.push('default');
  17677. return `
  17678. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17679. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17680. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17681. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17682. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17683. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17684. </td>
  17685. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${inst.version == 1 || inst.version === 'ripng' ? 'RIPng' : 'RIPv2'}</td>
  17686. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17687. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17688. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17689. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17690. </tr>
  17691. `;
  17692. }).join('');
  17693. }
  17694. function renderRipInterfaces() {
  17695. const tbody = document.getElementById('rip-interfaces-table-body');
  17696. if (!tbody) return;
  17697. const countEl = document.getElementById('rip-interfaces-footer-count');
  17698. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17699. let list = state.ripInterfaces || [];
  17700. if (filter) {
  17701. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17702. }
  17703. if (countEl) countEl.innerText = list.length;
  17704. const selId = state.selectedRipRow?.interfaces;
  17705. tbody.innerHTML = list.map((iface, idx) => {
  17706. const isSel = iface.id === selId;
  17707. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17708. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17709. return `
  17710. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17711. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17712. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17713. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17714. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17715. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17716. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17717. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17718. <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>
  17719. </tr>
  17720. `;
  17721. }).join('');
  17722. }
  17723. function renderRipNeighbors() {
  17724. const tbody = document.getElementById('rip-neighbors-table-body');
  17725. if (!tbody) return;
  17726. const countEl = document.getElementById('rip-neighbors-footer-count');
  17727. const list = state.ripNeighborsLive || [];
  17728. if (countEl) countEl.innerText = list.length;
  17729. tbody.innerHTML = list.map((nbr, idx) => `
  17730. <tr class="hover:bg-[#1a2636] text-slate-300">
  17731. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17732. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17733. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17734. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17735. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17736. </tr>
  17737. `).join('');
  17738. }
  17739. function renderRipRoutes() {
  17740. const tbody = document.getElementById('rip-routes-table-body');
  17741. if (!tbody) return;
  17742. const countEl = document.getElementById('rip-routes-footer-count');
  17743. const list = state.ripRoutes || [];
  17744. if (countEl) countEl.innerText = list.length;
  17745. tbody.innerHTML = list.map((r, idx) => `
  17746. <tr class="hover:bg-[#1a2636] text-slate-300">
  17747. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17748. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17749. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17750. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17751. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17752. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17753. </tr>
  17754. `).join('');
  17755. }
  17756. function openRipInstanceModal() {
  17757. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17758. document.getElementById('modal-rip-instance-id').value = '';
  17759. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17760. document.getElementById('modal-rip-instance-version').value = '2';
  17761. document.getElementById('modal-rip-instance-update').value = '30';
  17762. document.getElementById('modal-rip-instance-timeout').value = '180';
  17763. document.getElementById('modal-rip-instance-garbage').value = '120';
  17764. document.getElementById('modal-rip-instance-metric').value = '1';
  17765. document.getElementById('modal-rip-instance-comment').value = '';
  17766. document.getElementById('modal-rip-instance-enabled').checked = true;
  17767. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17768. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17769. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17770. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17771. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17772. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17773. }
  17774. function openEditRipInstanceModal(id) {
  17775. const inst = (state.ripInstances || []).find(i => i.id === id);
  17776. if (!inst) return;
  17777. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17778. document.getElementById('modal-rip-instance-id').value = inst.id;
  17779. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17780. document.getElementById('modal-rip-instance-version').value = (inst.version == 1 || inst.version === 'ripng') ? '1' : '2';
  17781. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17782. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17783. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17784. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17785. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17786. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17787. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17788. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17789. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17790. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17791. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17792. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17793. }
  17794. function closeRipInstanceModal() {
  17795. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17796. }
  17797. async function submitRipInstance(e) {
  17798. e.preventDefault();
  17799. const id = document.getElementById('modal-rip-instance-id').value;
  17800. const payload = {
  17801. id: id || undefined,
  17802. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17803. version: parseInt(document.getElementById('modal-rip-instance-version').value, 10) || 2,
  17804. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17805. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17806. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17807. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17808. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17809. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17810. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17811. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17812. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17813. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17814. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17815. };
  17816. try {
  17817. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17818. method: 'POST',
  17819. headers: { 'Content-Type': 'application/json' },
  17820. body: JSON.stringify(payload)
  17821. });
  17822. if (!res.ok) throw new Error(await res.text());
  17823. closeRipInstanceModal();
  17824. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17825. await loadDynamicRouting(false);
  17826. } catch (err) {
  17827. showToast('Error', err.message, 'error');
  17828. }
  17829. }
  17830. async function enableSelectedRipInstance() {
  17831. const id = state.selectedRipRow?.instances;
  17832. if (!id) return;
  17833. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17834. await loadDynamicRouting(false);
  17835. }
  17836. async function disableSelectedRipInstance() {
  17837. const id = state.selectedRipRow?.instances;
  17838. if (!id) return;
  17839. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17840. await loadDynamicRouting(false);
  17841. }
  17842. async function removeSelectedRipInstance() {
  17843. const id = state.selectedRipRow?.instances;
  17844. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  17845. await fetch(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' });
  17846. state.selectedRipRow.instances = null;
  17847. await loadDynamicRouting(false);
  17848. }
  17849. function openRipInterfaceModal() {
  17850. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  17851. document.getElementById('modal-rip-iface-id').value = '';
  17852. const dl = document.getElementById('rip-iface-datalist');
  17853. if (dl) {
  17854. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17855. }
  17856. const instSel = document.getElementById('modal-rip-iface-instance');
  17857. if (instSel && instSel.tagName === 'SELECT') {
  17858. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17859. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17860. }
  17861. document.getElementById('modal-rip-iface-pattern').value = '*';
  17862. if (instSel) instSel.value = (state.ripInstances && state.ripInstances.length > 0) ? state.ripInstances[0].name : 'default';
  17863. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  17864. document.getElementById('modal-rip-iface-metric').value = '1';
  17865. document.getElementById('modal-rip-iface-comment').value = '';
  17866. document.getElementById('modal-rip-iface-enabled').checked = true;
  17867. document.getElementById('modal-rip-iface-passive').checked = false;
  17868. document.getElementById('modal-rip-iface-bfd').checked = false;
  17869. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17870. }
  17871. function openEditRipInterfaceModal(id) {
  17872. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  17873. if (!iface) return;
  17874. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  17875. document.getElementById('modal-rip-iface-id').value = iface.id;
  17876. const dl = document.getElementById('rip-iface-datalist');
  17877. if (dl) {
  17878. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17879. }
  17880. const instSel = document.getElementById('modal-rip-iface-instance');
  17881. if (instSel && instSel.tagName === 'SELECT') {
  17882. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17883. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17884. instSel.value = iface.instance || 'default';
  17885. } else if (instSel) {
  17886. instSel.value = iface.instance || '';
  17887. }
  17888. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '*';
  17889. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  17890. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  17891. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  17892. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  17893. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  17894. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  17895. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17896. }
  17897. function closeRipInterfaceModal() {
  17898. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  17899. }
  17900. async function submitRipInterface(e) {
  17901. e.preventDefault();
  17902. const id = document.getElementById('modal-rip-iface-id').value;
  17903. const payload = {
  17904. id: id || undefined,
  17905. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  17906. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  17907. mode: document.getElementById('modal-rip-iface-mode').value,
  17908. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  17909. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  17910. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  17911. passive: document.getElementById('modal-rip-iface-passive').checked,
  17912. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  17913. };
  17914. try {
  17915. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  17916. method: 'POST',
  17917. headers: { 'Content-Type': 'application/json' },
  17918. body: JSON.stringify(payload)
  17919. });
  17920. if (!res.ok) throw new Error(await res.text());
  17921. closeRipInterfaceModal();
  17922. showToast('Saved', `RIP interface template saved`, 'success');
  17923. await loadDynamicRouting(false);
  17924. } catch (err) {
  17925. showToast('Error', err.message, 'error');
  17926. }
  17927. }
  17928. async function enableSelectedRipInterface() {
  17929. const id = state.selectedRipRow?.interfaces;
  17930. if (!id) return;
  17931. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17932. await loadDynamicRouting(false);
  17933. }
  17934. async function disableSelectedRipInterface() {
  17935. const id = state.selectedRipRow?.interfaces;
  17936. if (!id) return;
  17937. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17938. await loadDynamicRouting(false);
  17939. }
  17940. async function removeSelectedRipInterface() {
  17941. const id = state.selectedRipRow?.interfaces;
  17942. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  17943. await fetch(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' });
  17944. state.selectedRipRow.interfaces = null;
  17945. await loadDynamicRouting(false);
  17946. }
  17947. // ==============================================================================
  17948. // DYNAMIC ROUTING: BFD MODULE
  17949. // ==============================================================================
  17950. state.bfdInstance = null;
  17951. state.bfdInterfaces = [];
  17952. state.bfdNeighbors = [];
  17953. state.bfdSessions = [];
  17954. state.selectedBfdRow = {};
  17955. state.activeBfdTab = 'config';
  17956. function switchBfdTab(tab) {
  17957. state.activeBfdTab = tab;
  17958. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  17959. const pane = document.getElementById(`bfd-pane-${t}`);
  17960. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  17961. if (pane) {
  17962. if (t === tab) pane.classList.remove('hidden');
  17963. else pane.classList.add('hidden');
  17964. }
  17965. if (btn) {
  17966. if (t === tab) {
  17967. 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';
  17968. } else {
  17969. 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';
  17970. }
  17971. }
  17972. });
  17973. }
  17974. function selectBfdRow(tab, id) {
  17975. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  17976. state.selectedBfdRow[tab] = id;
  17977. if (tab === 'interfaces') {
  17978. renderBfdInterfaces();
  17979. const btnEn = document.getElementById('btn-bfd-iface-enable');
  17980. const btnDis = document.getElementById('btn-bfd-iface-disable');
  17981. const btnRem = document.getElementById('btn-bfd-iface-remove');
  17982. if (btnEn) btnEn.disabled = false;
  17983. if (btnDis) btnDis.disabled = false;
  17984. if (btnRem) btnRem.disabled = false;
  17985. } else if (tab === 'peers') {
  17986. renderBfdPeers();
  17987. const btnEn = document.getElementById('btn-bfd-peer-enable');
  17988. const btnDis = document.getElementById('btn-bfd-peer-disable');
  17989. const btnRem = document.getElementById('btn-bfd-peer-remove');
  17990. if (btnEn) btnEn.disabled = false;
  17991. if (btnDis) btnDis.disabled = false;
  17992. if (btnRem) btnRem.disabled = false;
  17993. }
  17994. }
  17995. function renderBfdConfig() {
  17996. const inst = state.bfdInstance;
  17997. const pill = document.getElementById('bfd-live-status-pill');
  17998. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  17999. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  18000. const peerStat = document.getElementById('bfd-stat-peers');
  18001. const sessStat = document.getElementById('bfd-stat-sessions');
  18002. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  18003. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  18004. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  18005. const isEnabled = inst && (inst.enabled || inst.running || (!inst.disabled && (state.bfdInterfaces || []).length > 0));
  18006. if (!inst || inst.disabled || !isEnabled) {
  18007. if (pill) {
  18008. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  18009. pill.innerText = 'DISABLED';
  18010. }
  18011. if (toggleBtn) {
  18012. toggleBtn.innerText = 'Enable BFD';
  18013. 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';
  18014. }
  18015. } else {
  18016. if (pill) {
  18017. if (inst.running) {
  18018. 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';
  18019. pill.innerText = 'RUNNING (ACTIVE)';
  18020. } else {
  18021. 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';
  18022. pill.innerText = 'CONFIGURED';
  18023. }
  18024. }
  18025. if (toggleBtn) {
  18026. toggleBtn.innerText = 'Disable BFD';
  18027. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  18028. }
  18029. }
  18030. }
  18031. async function toggleBfdGlobalState() {
  18032. const current = state.bfdInstance;
  18033. const isCurrentlyEnabled = current && (current.enabled || current.running) && !current.disabled;
  18034. const newEnabled = !isCurrentlyEnabled;
  18035. const newDisabled = !newEnabled;
  18036. try {
  18037. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  18038. method: 'POST',
  18039. headers: { 'Content-Type': 'application/json' },
  18040. body: JSON.stringify({ enabled: newEnabled, disabled: newDisabled })
  18041. });
  18042. if (!res.ok) throw new Error(await res.text());
  18043. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  18044. await loadDynamicRouting(false);
  18045. } catch (err) {
  18046. showToast('Error', err.message, 'error');
  18047. }
  18048. }
  18049. function renderBfdInterfaces() {
  18050. const tbody = document.getElementById('bfd-interfaces-table-body');
  18051. if (!tbody) return;
  18052. const countEl = document.getElementById('bfd-interfaces-footer-count');
  18053. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  18054. let list = state.bfdInterfaces || [];
  18055. if (filter) {
  18056. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18057. }
  18058. if (countEl) countEl.innerText = list.length;
  18059. const selId = state.selectedBfdRow?.interfaces;
  18060. tbody.innerHTML = list.map((iface, idx) => {
  18061. const isSel = iface.id === selId;
  18062. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18063. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18064. return `
  18065. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  18066. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18067. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18068. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18069. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18070. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  18071. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  18072. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  18073. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  18074. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  18075. </tr>
  18076. `;
  18077. }).join('');
  18078. }
  18079. function renderBfdPeers() {
  18080. const tbody = document.getElementById('bfd-peers-table-body');
  18081. if (!tbody) return;
  18082. const countEl = document.getElementById('bfd-peers-footer-count');
  18083. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  18084. let list = state.bfdNeighbors || [];
  18085. if (filter) {
  18086. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18087. }
  18088. if (countEl) countEl.innerText = list.length;
  18089. const selId = state.selectedBfdRow?.peers;
  18090. tbody.innerHTML = list.map((p, idx) => {
  18091. const isSel = p.id === selId;
  18092. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18093. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18094. return `
  18095. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18096. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18097. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18098. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18099. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18100. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18101. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(p.local_address || 'auto')}</td>
  18102. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18103. </tr>
  18104. `;
  18105. }).join('');
  18106. }
  18107. function renderBfdSessions() {
  18108. const tbody = document.getElementById('bfd-sessions-table-body');
  18109. if (!tbody) return;
  18110. const countEl = document.getElementById('bfd-sessions-footer-count');
  18111. const list = state.bfdSessions || [];
  18112. if (countEl) countEl.innerText = list.length;
  18113. tbody.innerHTML = list.map((s, idx) => {
  18114. const isUp = (s.state || '').toLowerCase() === 'up';
  18115. const stateBadge = isUp
  18116. ? '<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>'
  18117. : `<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>`;
  18118. return `
  18119. <tr class="hover:bg-[#1a2636] text-slate-300">
  18120. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18121. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18122. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18123. <td class="py-1.5 px-3">${stateBadge}</td>
  18124. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18125. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18126. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18127. </tr>
  18128. `;
  18129. }).join('');
  18130. }
  18131. function openBfdInterfaceModal() {
  18132. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18133. document.getElementById('modal-bfd-iface-id').value = '';
  18134. const dl = document.getElementById('bfd-iface-datalist');
  18135. if (dl) {
  18136. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18137. }
  18138. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18139. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18140. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18141. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18142. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18143. document.getElementById('modal-bfd-iface-comment').value = '';
  18144. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18145. document.getElementById('modal-bfd-iface-passive').checked = false;
  18146. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18147. }
  18148. function openEditBfdInterfaceModal(id) {
  18149. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18150. if (!iface) return;
  18151. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18152. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18153. const dl = document.getElementById('bfd-iface-datalist');
  18154. if (dl) {
  18155. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18156. }
  18157. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18158. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18159. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18160. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18161. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18162. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18163. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18164. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18165. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18166. }
  18167. function closeBfdInterfaceModal() {
  18168. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18169. }
  18170. async function submitBfdInterface(e) {
  18171. e.preventDefault();
  18172. const id = document.getElementById('modal-bfd-iface-id').value;
  18173. const payload = {
  18174. id: id || undefined,
  18175. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18176. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18177. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18178. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18179. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18180. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18181. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18182. passive: document.getElementById('modal-bfd-iface-passive').checked
  18183. };
  18184. try {
  18185. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18186. method: 'POST',
  18187. headers: { 'Content-Type': 'application/json' },
  18188. body: JSON.stringify(payload)
  18189. });
  18190. if (!res.ok) throw new Error(await res.text());
  18191. closeBfdInterfaceModal();
  18192. showToast('Saved', `BFD profile saved`, 'success');
  18193. await loadDynamicRouting(false);
  18194. } catch (err) {
  18195. showToast('Error', err.message, 'error');
  18196. }
  18197. }
  18198. async function enableSelectedBfdInterface() {
  18199. const id = state.selectedBfdRow?.interfaces;
  18200. if (!id) return;
  18201. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18202. await loadDynamicRouting(false);
  18203. }
  18204. async function disableSelectedBfdInterface() {
  18205. const id = state.selectedBfdRow?.interfaces;
  18206. if (!id) return;
  18207. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18208. await loadDynamicRouting(false);
  18209. }
  18210. async function removeSelectedBfdInterface() {
  18211. const id = state.selectedBfdRow?.interfaces;
  18212. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18213. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' });
  18214. state.selectedBfdRow.interfaces = null;
  18215. await loadDynamicRouting(false);
  18216. }
  18217. function openBfdPeerModal() {
  18218. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18219. document.getElementById('modal-bfd-peer-id').value = '';
  18220. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18221. if (dlPeer) {
  18222. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18223. }
  18224. document.getElementById('modal-bfd-peer-address').value = '';
  18225. document.getElementById('modal-bfd-peer-interface').value = '';
  18226. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18227. if (localAddrEl) localAddrEl.value = '';
  18228. document.getElementById('modal-bfd-peer-comment').value = '';
  18229. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18230. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18231. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18232. }
  18233. function openEditBfdPeerModal(id) {
  18234. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18235. if (!p) return;
  18236. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18237. document.getElementById('modal-bfd-peer-id').value = p.id;
  18238. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18239. if (dlPeer) {
  18240. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18241. }
  18242. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18243. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18244. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18245. if (localAddrEl) localAddrEl.value = p.local_address || '';
  18246. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18247. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18248. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18249. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18250. }
  18251. function closeBfdPeerModal() {
  18252. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18253. }
  18254. async function submitBfdPeer(e) {
  18255. e.preventDefault();
  18256. const id = document.getElementById('modal-bfd-peer-id').value;
  18257. const localAddr = document.getElementById('modal-bfd-peer-local-address')?.value.trim() || '';
  18258. const payload = {
  18259. id: id || undefined,
  18260. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18261. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18262. local_address: localAddr,
  18263. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18264. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18265. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18266. };
  18267. try {
  18268. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18269. method: 'POST',
  18270. headers: { 'Content-Type': 'application/json' },
  18271. body: JSON.stringify(payload)
  18272. });
  18273. if (!res.ok) throw new Error(await res.text());
  18274. closeBfdPeerModal();
  18275. showToast('Saved', `BFD peer saved`, 'success');
  18276. await loadDynamicRouting(false);
  18277. } catch (err) {
  18278. showToast('Error', err.message, 'error');
  18279. }
  18280. }
  18281. async function enableSelectedBfdPeer() {
  18282. const id = state.selectedBfdRow?.peers;
  18283. if (!id) return;
  18284. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18285. if (!p) return;
  18286. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) });
  18287. await loadDynamicRouting(false);
  18288. }
  18289. async function disableSelectedBfdPeer() {
  18290. const id = state.selectedBfdRow?.peers;
  18291. if (!id) return;
  18292. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18293. if (!p) return;
  18294. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) });
  18295. await loadDynamicRouting(false);
  18296. }
  18297. async function removeSelectedBfdPeer() {
  18298. const id = state.selectedBfdRow?.peers;
  18299. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18300. await fetch(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' });
  18301. state.selectedBfdRow.peers = null;
  18302. await loadDynamicRouting(false);
  18303. }
  18304. // ==============================================================================
  18305. // DYNAMIC ROUTING: BABEL MODULE
  18306. // ==============================================================================
  18307. state.babelInstances = [];
  18308. state.babelInterfaces = [];
  18309. state.babelInterfacesLive = [];
  18310. state.babelNeighbors = [];
  18311. state.babelRoutes = [];
  18312. state.selectedBabelRow = {};
  18313. state.activeBabelTab = 'instances';
  18314. function switchBabelTab(tab) {
  18315. state.activeBabelTab = tab;
  18316. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18317. const pane = document.getElementById(`babel-pane-${t}`);
  18318. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18319. if (pane) {
  18320. if (t === tab) pane.classList.remove('hidden');
  18321. else pane.classList.add('hidden');
  18322. }
  18323. if (btn) {
  18324. if (t === tab) {
  18325. 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';
  18326. } else {
  18327. 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';
  18328. }
  18329. }
  18330. });
  18331. }
  18332. function selectBabelRow(tab, id) {
  18333. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18334. state.selectedBabelRow[tab] = id;
  18335. if (tab === 'instances') {
  18336. renderBabelInstances();
  18337. const btnEn = document.getElementById('btn-babel-inst-enable');
  18338. const btnDis = document.getElementById('btn-babel-inst-disable');
  18339. const btnRem = document.getElementById('btn-babel-inst-remove');
  18340. if (btnEn) btnEn.disabled = false;
  18341. if (btnDis) btnDis.disabled = false;
  18342. if (btnRem) btnRem.disabled = false;
  18343. } else if (tab === 'interfaces') {
  18344. renderBabelInterfaces();
  18345. const btnEn = document.getElementById('btn-babel-iface-enable');
  18346. const btnDis = document.getElementById('btn-babel-iface-disable');
  18347. const btnRem = document.getElementById('btn-babel-iface-remove');
  18348. if (btnEn) btnEn.disabled = false;
  18349. if (btnDis) btnDis.disabled = false;
  18350. if (btnRem) btnRem.disabled = false;
  18351. }
  18352. }
  18353. function renderBabelInstances() {
  18354. const tbody = document.getElementById('babel-instances-table-body');
  18355. if (!tbody) return;
  18356. const countEl = document.getElementById('babel-instances-footer-count');
  18357. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18358. let list = state.babelInstances || [];
  18359. if (filter) {
  18360. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18361. }
  18362. if (countEl) countEl.innerText = list.length;
  18363. const selId = state.selectedBabelRow?.instances;
  18364. tbody.innerHTML = list.map((inst, idx) => {
  18365. const isSel = inst.id === selId;
  18366. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18367. const flagD = inst.disabled
  18368. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18369. : (inst.running
  18370. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18371. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18372. const redist = [];
  18373. if (inst.redistribute_connected) redist.push('conn');
  18374. if (inst.redistribute_static) redist.push('static');
  18375. if (inst.redistribute_bgp) redist.push('bgp');
  18376. if (inst.redistribute_ospf) redist.push('ospf');
  18377. if (inst.redistribute_default) redist.push('default');
  18378. return `
  18379. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18380. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18381. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18382. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18383. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18384. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18385. </td>
  18386. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18387. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18388. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18389. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18390. </tr>
  18391. `;
  18392. }).join('');
  18393. }
  18394. function renderBabelInterfaces() {
  18395. const tbody = document.getElementById('babel-interfaces-table-body');
  18396. if (!tbody) return;
  18397. const countEl = document.getElementById('babel-interfaces-footer-count');
  18398. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18399. let list = state.babelInterfaces || [];
  18400. if (filter) {
  18401. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18402. }
  18403. if (countEl) countEl.innerText = list.length;
  18404. const selId = state.selectedBabelRow?.interfaces;
  18405. tbody.innerHTML = list.map((iface, idx) => {
  18406. const isSel = iface.id === selId;
  18407. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18408. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18409. return `
  18410. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18411. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18412. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18413. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18414. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18415. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18416. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18417. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18418. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18419. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18420. </tr>
  18421. `;
  18422. }).join('');
  18423. }
  18424. function renderBabelLiveInterfaces() {
  18425. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18426. if (!tbody) return;
  18427. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18428. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18429. let list = state.babelInterfacesLive || [];
  18430. if (filter) {
  18431. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18432. }
  18433. if (countEl) countEl.innerText = list.length;
  18434. tbody.innerHTML = list.map((iface, idx) => {
  18435. const isUp = (iface.state || '').toLowerCase() === 'up';
  18436. const stateBadge = isUp
  18437. ? '<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>'
  18438. : '<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>';
  18439. return `
  18440. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18441. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18442. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18443. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18444. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18445. <td class="py-1.5 px-3">${stateBadge}</td>
  18446. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18447. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18448. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18449. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18450. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18451. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18452. </tr>
  18453. `;
  18454. }).join('');
  18455. }
  18456. function renderBabelNeighbors() {
  18457. const tbody = document.getElementById('babel-neighbors-table-body');
  18458. if (!tbody) return;
  18459. const countEl = document.getElementById('babel-neighbors-footer-count');
  18460. const list = state.babelNeighbors || [];
  18461. if (countEl) countEl.innerText = list.length;
  18462. tbody.innerHTML = list.map((nbr, idx) => `
  18463. <tr class="hover:bg-[#1a2636] text-slate-300">
  18464. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18465. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18466. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18467. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18468. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18469. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18470. </tr>
  18471. `).join('');
  18472. }
  18473. function renderBabelRoutes() {
  18474. const tbody = document.getElementById('babel-routes-table-body');
  18475. if (!tbody) return;
  18476. const countEl = document.getElementById('babel-routes-footer-count');
  18477. const list = state.babelRoutes || [];
  18478. if (countEl) countEl.innerText = list.length;
  18479. tbody.innerHTML = list.map((r, idx) => `
  18480. <tr class="hover:bg-[#1a2636] text-slate-300">
  18481. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18482. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18483. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18484. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18485. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18486. </tr>
  18487. `).join('');
  18488. }
  18489. function openBabelInstanceModal() {
  18490. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18491. document.getElementById('modal-babel-instance-id').value = '';
  18492. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18493. document.getElementById('modal-babel-instance-routerid').value = '';
  18494. document.getElementById('modal-babel-instance-metric').value = '10';
  18495. document.getElementById('modal-babel-instance-comment').value = '';
  18496. document.getElementById('modal-babel-instance-enabled').checked = true;
  18497. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18498. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18499. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18500. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18501. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18502. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18503. }
  18504. function openEditBabelInstanceModal(id) {
  18505. const inst = (state.babelInstances || []).find(i => i.id === id);
  18506. if (!inst) return;
  18507. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18508. document.getElementById('modal-babel-instance-id').value = inst.id;
  18509. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18510. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18511. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18512. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18513. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18514. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18515. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18516. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18517. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18518. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18519. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18520. }
  18521. function closeBabelInstanceModal() {
  18522. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18523. }
  18524. async function submitBabelInstance(e) {
  18525. e.preventDefault();
  18526. const id = document.getElementById('modal-babel-instance-id').value;
  18527. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18528. const payload = {
  18529. id: id || undefined,
  18530. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18531. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18532. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18533. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18534. enabled: isEnabled,
  18535. disabled: !isEnabled,
  18536. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18537. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18538. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18539. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18540. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18541. };
  18542. try {
  18543. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18544. method: 'POST',
  18545. headers: { 'Content-Type': 'application/json' },
  18546. body: JSON.stringify(payload)
  18547. });
  18548. if (!res.ok) throw new Error(await res.text());
  18549. closeBabelInstanceModal();
  18550. showToast('Saved', `Babel instance saved`, 'success');
  18551. await loadDynamicRouting(false);
  18552. } catch (err) {
  18553. showToast('Error', err.message, 'error');
  18554. }
  18555. }
  18556. async function enableSelectedBabelInstance() {
  18557. const id = state.selectedBabelRow?.instances;
  18558. if (!id) return;
  18559. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18560. await loadDynamicRouting(false);
  18561. }
  18562. async function disableSelectedBabelInstance() {
  18563. const id = state.selectedBabelRow?.instances;
  18564. if (!id) return;
  18565. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18566. await loadDynamicRouting(false);
  18567. }
  18568. async function removeSelectedBabelInstance() {
  18569. const id = state.selectedBabelRow?.instances;
  18570. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18571. await fetch(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' });
  18572. state.selectedBabelRow.instances = null;
  18573. await loadDynamicRouting(false);
  18574. }
  18575. function toggleBabelAuthKey() {
  18576. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18577. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18578. if (wrap) {
  18579. if (authVal === 'mac') wrap.classList.remove('hidden');
  18580. else wrap.classList.add('hidden');
  18581. }
  18582. }
  18583. function openBabelInterfaceModal() {
  18584. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18585. document.getElementById('modal-babel-iface-id').value = '';
  18586. const instSel = document.getElementById('modal-babel-iface-instance');
  18587. if (instSel) {
  18588. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18589. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18590. if (state.babelInstances && state.babelInstances.length > 0) {
  18591. instSel.value = state.babelInstances[0].name;
  18592. }
  18593. }
  18594. const dl = document.getElementById('babel-iface-datalist');
  18595. if (dl) {
  18596. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18597. }
  18598. document.getElementById('modal-babel-iface-pattern').value = '*';
  18599. document.getElementById('modal-babel-iface-type').value = 'wired';
  18600. document.getElementById('modal-babel-iface-auth').value = 'none';
  18601. document.getElementById('modal-babel-iface-auth-key').value = '';
  18602. toggleBabelAuthKey();
  18603. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18604. document.getElementById('modal-babel-iface-hello').value = '4';
  18605. document.getElementById('modal-babel-iface-update').value = '16';
  18606. document.getElementById('modal-babel-iface-comment').value = '';
  18607. document.getElementById('modal-babel-iface-enabled').checked = true;
  18608. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18609. }
  18610. function openEditBabelInterfaceModal(id) {
  18611. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18612. if (!iface) return;
  18613. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18614. document.getElementById('modal-babel-iface-id').value = iface.id;
  18615. const instSel = document.getElementById('modal-babel-iface-instance');
  18616. if (instSel) {
  18617. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18618. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18619. instSel.value = iface.instance || 'all';
  18620. }
  18621. const dl = document.getElementById('babel-iface-datalist');
  18622. if (dl) {
  18623. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18624. }
  18625. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18626. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18627. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18628. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18629. toggleBabelAuthKey();
  18630. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18631. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18632. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18633. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18634. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18635. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18636. }
  18637. function closeBabelInterfaceModal() {
  18638. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18639. }
  18640. async function submitBabelInterface(e) {
  18641. e.preventDefault();
  18642. const id = document.getElementById('modal-babel-iface-id').value;
  18643. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18644. const payload = {
  18645. id: id || undefined,
  18646. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18647. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18648. type: document.getElementById('modal-babel-iface-type').value,
  18649. auth: document.getElementById('modal-babel-iface-auth').value,
  18650. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18651. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18652. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18653. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18654. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18655. disabled: !isEnabled
  18656. };
  18657. try {
  18658. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18659. method: 'POST',
  18660. headers: { 'Content-Type': 'application/json' },
  18661. body: JSON.stringify(payload)
  18662. });
  18663. if (!res.ok) throw new Error(await res.text());
  18664. closeBabelInterfaceModal();
  18665. showToast('Saved', `Babel interface template saved`, 'success');
  18666. await loadDynamicRouting(false);
  18667. } catch (err) {
  18668. showToast('Error', err.message, 'error');
  18669. }
  18670. }
  18671. async function enableSelectedBabelInterface() {
  18672. const id = state.selectedBabelRow?.interfaces;
  18673. if (!id) return;
  18674. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18675. await loadDynamicRouting(false);
  18676. }
  18677. async function disableSelectedBabelInterface() {
  18678. const id = state.selectedBabelRow?.interfaces;
  18679. if (!id) return;
  18680. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18681. await loadDynamicRouting(false);
  18682. }
  18683. async function removeSelectedBabelInterface() {
  18684. const id = state.selectedBabelRow?.interfaces;
  18685. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18686. await fetch(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' });
  18687. state.selectedBabelRow.interfaces = null;
  18688. await loadDynamicRouting(false);
  18689. }
  18690. // ==============================================================================
  18691. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18692. // ==============================================================================
  18693. state.radvInstances = [];
  18694. state.radvInterfaces = [];
  18695. state.selectedRadvRow = {};
  18696. state.activeRadvTab = 'instances';
  18697. function switchRadvTab(tab) {
  18698. state.activeRadvTab = tab;
  18699. ['instances', 'interfaces'].forEach(t => {
  18700. const pane = document.getElementById(`radv-pane-${t}`);
  18701. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18702. if (pane) {
  18703. if (t === tab) pane.classList.remove('hidden');
  18704. else pane.classList.add('hidden');
  18705. }
  18706. if (btn) {
  18707. if (t === tab) {
  18708. 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';
  18709. } else {
  18710. 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';
  18711. }
  18712. }
  18713. });
  18714. }
  18715. function selectRadvRow(tab, id) {
  18716. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18717. state.selectedRadvRow[tab] = id;
  18718. if (tab === 'instances') {
  18719. renderRAdvInstances();
  18720. const btnEn = document.getElementById('btn-radv-inst-enable');
  18721. const btnDis = document.getElementById('btn-radv-inst-disable');
  18722. const btnRem = document.getElementById('btn-radv-inst-remove');
  18723. if (btnEn) btnEn.disabled = false;
  18724. if (btnDis) btnDis.disabled = false;
  18725. if (btnRem) btnRem.disabled = false;
  18726. } else if (tab === 'interfaces') {
  18727. renderRAdvInterfaces();
  18728. const btnEn = document.getElementById('btn-radv-iface-enable');
  18729. const btnDis = document.getElementById('btn-radv-iface-disable');
  18730. const btnRem = document.getElementById('btn-radv-iface-remove');
  18731. if (btnEn) btnEn.disabled = false;
  18732. if (btnDis) btnDis.disabled = false;
  18733. if (btnRem) btnRem.disabled = false;
  18734. }
  18735. }
  18736. function renderRAdvInstances() {
  18737. const tbody = document.getElementById('radv-instances-table-body');
  18738. if (!tbody) return;
  18739. const countEl = document.getElementById('radv-instances-footer-count');
  18740. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18741. let list = state.radvInstances || [];
  18742. if (filter) {
  18743. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18744. }
  18745. if (countEl) countEl.innerText = list.length;
  18746. const selId = state.selectedRadvRow?.instances;
  18747. tbody.innerHTML = list.map((inst, idx) => {
  18748. const isSel = inst.id === selId;
  18749. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18750. const flagD = inst.disabled
  18751. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  18752. : (inst.running
  18753. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  18754. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  18755. return `
  18756. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18757. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18758. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18759. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18760. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18761. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18762. </td>
  18763. <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>
  18764. </tr>
  18765. `;
  18766. }).join('');
  18767. }
  18768. function renderRAdvInterfaces() {
  18769. const tbody = document.getElementById('radv-interfaces-table-body');
  18770. if (!tbody) return;
  18771. const countEl = document.getElementById('radv-interfaces-footer-count');
  18772. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18773. let list = state.radvInterfaces || [];
  18774. if (filter) {
  18775. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18776. }
  18777. if (countEl) countEl.innerText = list.length;
  18778. const selId = state.selectedRadvRow?.interfaces;
  18779. tbody.innerHTML = list.map((iface, idx) => {
  18780. const isSel = iface.id === selId;
  18781. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18782. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18783. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18784. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18785. return `
  18786. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18787. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18788. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18789. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18790. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18791. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18792. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18793. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18794. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18795. </tr>
  18796. `;
  18797. }).join('');
  18798. }
  18799. function openRAdvInstanceModal() {
  18800. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18801. document.getElementById('modal-radv-instance-id').value = '';
  18802. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18803. document.getElementById('modal-radv-instance-comment').value = '';
  18804. document.getElementById('modal-radv-instance-enabled').checked = true;
  18805. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18806. }
  18807. function openEditRAdvInstanceModal(id) {
  18808. const inst = (state.radvInstances || []).find(i => i.id === id);
  18809. if (!inst) return;
  18810. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18811. document.getElementById('modal-radv-instance-id').value = inst.id;
  18812. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18813. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18814. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18815. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18816. }
  18817. function closeRAdvInstanceModal() {
  18818. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18819. }
  18820. async function submitRAdvInstance(e) {
  18821. e.preventDefault();
  18822. const id = document.getElementById('modal-radv-instance-id').value;
  18823. const payload = {
  18824. id: id || undefined,
  18825. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18826. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18827. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  18828. };
  18829. try {
  18830. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  18831. method: 'POST',
  18832. headers: { 'Content-Type': 'application/json' },
  18833. body: JSON.stringify(payload)
  18834. });
  18835. if (!res.ok) throw new Error(await res.text());
  18836. closeRAdvInstanceModal();
  18837. showToast('Saved', `RAdv instance saved`, 'success');
  18838. await loadDynamicRouting(false);
  18839. } catch (err) {
  18840. showToast('Error', err.message, 'error');
  18841. }
  18842. }
  18843. async function enableSelectedRadvInstance() {
  18844. const id = state.selectedRadvRow?.instances;
  18845. if (!id) return;
  18846. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18847. await loadDynamicRouting(false);
  18848. }
  18849. async function disableSelectedRadvInstance() {
  18850. const id = state.selectedRadvRow?.instances;
  18851. if (!id) return;
  18852. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18853. await loadDynamicRouting(false);
  18854. }
  18855. async function removeSelectedRadvInstance() {
  18856. const id = state.selectedRadvRow?.instances;
  18857. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  18858. await fetch(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' });
  18859. state.selectedRadvRow.instances = null;
  18860. await loadDynamicRouting(false);
  18861. }
  18862. function openRAdvInterfaceModal() {
  18863. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  18864. document.getElementById('modal-radv-iface-id').value = '';
  18865. const dl = document.getElementById('radv-iface-datalist');
  18866. if (dl) {
  18867. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18868. }
  18869. const instSel = document.getElementById('modal-radv-iface-instance');
  18870. if (instSel && instSel.tagName === 'SELECT') {
  18871. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18872. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18873. instSel.value = (state.radvInstances && state.radvInstances.length > 0) ? state.radvInstances[0].name : 'default';
  18874. } else if (instSel) {
  18875. instSel.value = 'default';
  18876. }
  18877. document.getElementById('modal-radv-iface-interface').value = '*';
  18878. document.getElementById('modal-radv-iface-min-ra').value = '200';
  18879. document.getElementById('modal-radv-iface-max-ra').value = '600';
  18880. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  18881. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  18882. document.getElementById('modal-radv-iface-prefixes').value = '';
  18883. document.getElementById('modal-radv-iface-rdnss').value = '';
  18884. document.getElementById('modal-radv-iface-comment').value = '';
  18885. document.getElementById('modal-radv-iface-enabled').checked = true;
  18886. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18887. }
  18888. function openEditRAdvInterfaceModal(id) {
  18889. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  18890. if (!iface) return;
  18891. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  18892. document.getElementById('modal-radv-iface-id').value = iface.id;
  18893. const dl = document.getElementById('radv-iface-datalist');
  18894. if (dl) {
  18895. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18896. }
  18897. const instSel = document.getElementById('modal-radv-iface-instance');
  18898. if (instSel && instSel.tagName === 'SELECT') {
  18899. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18900. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18901. instSel.value = iface.instance || 'default';
  18902. } else if (instSel) {
  18903. instSel.value = iface.instance || '';
  18904. }
  18905. document.getElementById('modal-radv-iface-interface').value = iface.interface || '*';
  18906. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  18907. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  18908. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  18909. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  18910. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  18911. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  18912. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  18913. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  18914. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18915. }
  18916. function closeRAdvInterfaceModal() {
  18917. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  18918. }
  18919. async function submitRAdvInterface(e) {
  18920. e.preventDefault();
  18921. const id = document.getElementById('modal-radv-iface-id').value;
  18922. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  18923. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  18924. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18925. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18926. const payload = {
  18927. id: id || undefined,
  18928. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  18929. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  18930. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  18931. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  18932. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  18933. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  18934. prefixes: prefixes,
  18935. rdnss: rdnss,
  18936. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  18937. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  18938. };
  18939. try {
  18940. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  18941. method: 'POST',
  18942. headers: { 'Content-Type': 'application/json' },
  18943. body: JSON.stringify(payload)
  18944. });
  18945. if (!res.ok) throw new Error(await res.text());
  18946. closeRAdvInterfaceModal();
  18947. showToast('Saved', `RAdv interface saved`, 'success');
  18948. await loadDynamicRouting(false);
  18949. } catch (err) {
  18950. showToast('Error', err.message, 'error');
  18951. }
  18952. }
  18953. async function enableSelectedRadvInterface() {
  18954. const id = state.selectedRadvRow?.interfaces;
  18955. if (!id) return;
  18956. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18957. await loadDynamicRouting(false);
  18958. }
  18959. async function disableSelectedRadvInterface() {
  18960. const id = state.selectedRadvRow?.interfaces;
  18961. if (!id) return;
  18962. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18963. await loadDynamicRouting(false);
  18964. }
  18965. async function removeSelectedRadvInterface() {
  18966. const id = state.selectedRadvRow?.interfaces;
  18967. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  18968. await fetch(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' });
  18969. state.selectedRadvRow.interfaces = null;
  18970. await loadDynamicRouting(false);
  18971. }
  18972. // ================= EIGRP ROUTING CONTROLLER =================
  18973. state.selectedEigrpRow = { instances: null, networks: null, interfaces: null };
  18974. function switchEigrpTab(tab) {
  18975. state.activeEigrpTab = tab;
  18976. const tabs = ['instances', 'networks', 'interfaces', 'neighbors', 'topology'];
  18977. tabs.forEach(t => {
  18978. const btn = document.getElementById(`eigrp-tab-btn-${t}`);
  18979. const pane = document.getElementById(`eigrp-pane-${t}`);
  18980. if (btn) {
  18981. if (t === tab) {
  18982. 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';
  18983. } else {
  18984. 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';
  18985. }
  18986. }
  18987. if (pane) {
  18988. if (t === tab) pane.classList.remove('hidden');
  18989. else pane.classList.add('hidden');
  18990. }
  18991. });
  18992. const dlIface = document.getElementById('eigrp-iface-datalist');
  18993. if (dlIface && state.interfaces) {
  18994. dlIface.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18995. }
  18996. const dlNet = document.getElementById('eigrp-net-datalist');
  18997. if (dlNet && state.interfaces) {
  18998. const cidrs = [];
  18999. state.interfaces.forEach(i => {
  19000. (i.addrs || []).forEach(a => {
  19001. if (a.includes('.') && a.includes('/')) cidrs.push(a);
  19002. });
  19003. });
  19004. dlNet.innerHTML = '<option value="0.0.0.0/0">' + cidrs.map(c => `<option value="${escapeHtml(c)}">`).join('');
  19005. }
  19006. }
  19007. function selectEigrpRow(kind, id) {
  19008. if (!state.selectedEigrpRow) state.selectedEigrpRow = {};
  19009. if (state.selectedEigrpRow[kind] === id) {
  19010. state.selectedEigrpRow[kind] = null;
  19011. } else {
  19012. state.selectedEigrpRow[kind] = id;
  19013. }
  19014. if (kind === 'instances') {
  19015. renderEigrpInstances();
  19016. const isSel = !!state.selectedEigrpRow.instances;
  19017. const btnEn = document.getElementById('btn-eigrp-inst-enable');
  19018. const btnDis = document.getElementById('btn-eigrp-inst-disable');
  19019. const btnRem = document.getElementById('btn-eigrp-inst-remove');
  19020. if (btnEn) btnEn.disabled = !isSel;
  19021. if (btnDis) btnDis.disabled = !isSel;
  19022. if (btnRem) btnRem.disabled = !isSel;
  19023. } else if (kind === 'networks') {
  19024. renderEigrpNetworks();
  19025. const isSel = !!state.selectedEigrpRow.networks;
  19026. const btnRem = document.getElementById('btn-eigrp-net-remove');
  19027. if (btnRem) btnRem.disabled = !isSel;
  19028. } else if (kind === 'interfaces') {
  19029. renderEigrpInterfaces();
  19030. const isSel = !!state.selectedEigrpRow.interfaces;
  19031. const btnEn = document.getElementById('btn-eigrp-iface-enable');
  19032. const btnDis = document.getElementById('btn-eigrp-iface-disable');
  19033. const btnRem = document.getElementById('btn-eigrp-iface-remove');
  19034. if (btnEn) btnEn.disabled = !isSel;
  19035. if (btnDis) btnDis.disabled = !isSel;
  19036. if (btnRem) btnRem.disabled = !isSel;
  19037. }
  19038. }
  19039. // --- EIGRP INSTANCES ---
  19040. function renderEigrpInstances() {
  19041. const tbody = document.getElementById('eigrp-instances-table-body');
  19042. if (!tbody) return;
  19043. const countEl = document.getElementById('eigrp-instances-footer-count');
  19044. const filter = (document.getElementById('filter-eigrp-instances')?.value || '').toLowerCase();
  19045. let list = state.eigrpInstances || [];
  19046. if (filter) {
  19047. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || String(i.as || '').includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19048. }
  19049. if (countEl) countEl.innerText = list.length;
  19050. const selId = state.selectedEigrpRow?.instances;
  19051. tbody.innerHTML = list.map((inst, idx) => {
  19052. const isSel = inst.id === selId;
  19053. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19054. const flagD = inst.disabled
  19055. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  19056. : (inst.running
  19057. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  19058. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  19059. const redist = [];
  19060. if (inst.redistribute_connected) redist.push('conn');
  19061. if (inst.redistribute_static) redist.push('static');
  19062. if (inst.redistribute_ospf) redist.push('ospf');
  19063. if (inst.redistribute_bgp) redist.push('bgp');
  19064. return `
  19065. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('instances', '${inst.id}')" ondblclick="openEditEigrpInstanceModal('${inst.id}')">
  19066. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19067. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19068. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  19069. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  19070. <span class="text-purple-400">⚡</span> <span>${escapeHtml(inst.name || 'default')}</span>
  19071. </td>
  19072. <td class="py-1.5 px-3 font-mono text-purple-300 font-bold">${inst.as || 100}</td>
  19073. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  19074. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  19075. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.variance || 1}</td>
  19076. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.max_paths || 4}</td>
  19077. </tr>
  19078. `;
  19079. }).join('');
  19080. }
  19081. function openEigrpInstanceModal() {
  19082. document.getElementById('eigrp-instance-modal-title').innerText = 'Add EIGRP Instance';
  19083. document.getElementById('modal-eigrp-instance-id').value = '';
  19084. document.getElementById('modal-eigrp-instance-name').value = 'eigrp' + ((state.eigrpInstances || []).length + 1);
  19085. document.getElementById('modal-eigrp-instance-as').value = '100';
  19086. document.getElementById('modal-eigrp-instance-routerid').value = '';
  19087. document.getElementById('modal-eigrp-instance-comment').value = '';
  19088. document.getElementById('modal-eigrp-instance-variance').value = '1';
  19089. document.getElementById('modal-eigrp-instance-maxpaths').value = '4';
  19090. document.getElementById('modal-eigrp-instance-metric').value = '10000';
  19091. document.getElementById('modal-eigrp-instance-redist-conn').checked = false;
  19092. document.getElementById('modal-eigrp-instance-redist-static').checked = false;
  19093. document.getElementById('modal-eigrp-instance-redist-ospf').checked = false;
  19094. document.getElementById('modal-eigrp-instance-redist-bgp').checked = false;
  19095. document.getElementById('modal-eigrp-instance-enabled').checked = true;
  19096. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19097. }
  19098. function openEditEigrpInstanceModal(id) {
  19099. const inst = (state.eigrpInstances || []).find(i => i.id === id);
  19100. if (!inst) return;
  19101. document.getElementById('eigrp-instance-modal-title').innerText = `Edit EIGRP Instance: ${inst.name}`;
  19102. document.getElementById('modal-eigrp-instance-id').value = inst.id;
  19103. document.getElementById('modal-eigrp-instance-name').value = inst.name || '';
  19104. document.getElementById('modal-eigrp-instance-as').value = inst.as || 100;
  19105. document.getElementById('modal-eigrp-instance-routerid').value = inst.router_id || '';
  19106. document.getElementById('modal-eigrp-instance-comment').value = inst.comment || '';
  19107. document.getElementById('modal-eigrp-instance-variance').value = inst.variance || 1;
  19108. document.getElementById('modal-eigrp-instance-maxpaths').value = inst.max_paths || 4;
  19109. document.getElementById('modal-eigrp-instance-metric').value = inst.default_metric || 10000;
  19110. document.getElementById('modal-eigrp-instance-redist-conn').checked = !!inst.redistribute_connected;
  19111. document.getElementById('modal-eigrp-instance-redist-static').checked = !!inst.redistribute_static;
  19112. document.getElementById('modal-eigrp-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  19113. document.getElementById('modal-eigrp-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  19114. document.getElementById('modal-eigrp-instance-enabled').checked = !inst.disabled;
  19115. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19116. }
  19117. function closeEigrpInstanceModal() {
  19118. document.getElementById('eigrp-instance-modal')?.classList.add('hidden');
  19119. }
  19120. async function submitEigrpInstance(e) {
  19121. e.preventDefault();
  19122. const payload = {
  19123. id: document.getElementById('modal-eigrp-instance-id').value.trim() || undefined,
  19124. name: document.getElementById('modal-eigrp-instance-name').value.trim(),
  19125. as: parseInt(document.getElementById('modal-eigrp-instance-as').value, 10) || 100,
  19126. router_id: document.getElementById('modal-eigrp-instance-routerid').value.trim(),
  19127. comment: document.getElementById('modal-eigrp-instance-comment').value.trim(),
  19128. variance: parseInt(document.getElementById('modal-eigrp-instance-variance').value, 10) || 1,
  19129. max_paths: parseInt(document.getElementById('modal-eigrp-instance-maxpaths').value, 10) || 4,
  19130. default_metric: parseInt(document.getElementById('modal-eigrp-instance-metric').value, 10) || 10000,
  19131. redistribute_connected: document.getElementById('modal-eigrp-instance-redist-conn').checked,
  19132. redistribute_static: document.getElementById('modal-eigrp-instance-redist-static').checked,
  19133. redistribute_ospf: document.getElementById('modal-eigrp-instance-redist-ospf').checked,
  19134. redistribute_bgp: document.getElementById('modal-eigrp-instance-redist-bgp').checked,
  19135. disabled: !document.getElementById('modal-eigrp-instance-enabled').checked
  19136. };
  19137. try {
  19138. const res = await fetch(`${API_BASE}/routing/eigrp/instances`, {
  19139. method: 'POST',
  19140. headers: { 'Content-Type': 'application/json' },
  19141. body: JSON.stringify(payload)
  19142. });
  19143. if (!res.ok) throw new Error(await res.text());
  19144. closeEigrpInstanceModal();
  19145. showToast('Saved', `EIGRP instance saved`, 'success');
  19146. await loadDynamicRouting(false);
  19147. } catch (err) {
  19148. showToast('Error', err.message, 'error');
  19149. }
  19150. }
  19151. async function enableSelectedEigrpInstance() {
  19152. const id = state.selectedEigrpRow?.instances;
  19153. if (!id) return;
  19154. await fetch(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  19155. await loadDynamicRouting(false);
  19156. }
  19157. async function disableSelectedEigrpInstance() {
  19158. const id = state.selectedEigrpRow?.instances;
  19159. if (!id) return;
  19160. await fetch(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  19161. await loadDynamicRouting(false);
  19162. }
  19163. async function removeSelectedEigrpInstance() {
  19164. const id = state.selectedEigrpRow?.instances;
  19165. if (!id || !confirm('Are you sure you want to remove this EIGRP instance?')) return;
  19166. await fetch(`${API_BASE}/routing/eigrp/instances/${id}`, { method: 'DELETE' });
  19167. state.selectedEigrpRow.instances = null;
  19168. await loadDynamicRouting(false);
  19169. }
  19170. // --- EIGRP NETWORKS ---
  19171. function renderEigrpNetworks() {
  19172. const tbody = document.getElementById('eigrp-networks-table-body');
  19173. if (!tbody) return;
  19174. const countEl = document.getElementById('eigrp-networks-footer-count');
  19175. const filter = (document.getElementById('filter-eigrp-networks')?.value || '').toLowerCase();
  19176. let list = state.eigrpNetworks || [];
  19177. if (filter) {
  19178. list = list.filter(n => (n.network || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  19179. }
  19180. if (countEl) countEl.innerText = list.length;
  19181. const selId = state.selectedEigrpRow?.networks;
  19182. tbody.innerHTML = list.map((net, idx) => {
  19183. const isSel = net.id === selId;
  19184. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19185. return `
  19186. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('networks', '${net.id}')">
  19187. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19188. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(net.comment || '')}</td>
  19189. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(net.network || '')}</td>
  19190. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(net.instance || 'all')}</td>
  19191. </tr>
  19192. `;
  19193. }).join('');
  19194. }
  19195. function openEigrpNetworkModal() {
  19196. document.getElementById('modal-eigrp-network-id').value = '';
  19197. const instSel = document.getElementById('modal-eigrp-network-instance');
  19198. if (instSel) {
  19199. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19200. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19201. }
  19202. document.getElementById('modal-eigrp-network-cidr').value = '0.0.0.0/0';
  19203. document.getElementById('modal-eigrp-network-comment').value = '';
  19204. document.getElementById('eigrp-network-modal')?.classList.remove('hidden');
  19205. }
  19206. function closeEigrpNetworkModal() {
  19207. document.getElementById('eigrp-network-modal')?.classList.add('hidden');
  19208. }
  19209. async function submitEigrpNetwork(e) {
  19210. e.preventDefault();
  19211. const payload = {
  19212. id: document.getElementById('modal-eigrp-network-id').value.trim() || undefined,
  19213. instance: document.getElementById('modal-eigrp-network-instance').value,
  19214. network: document.getElementById('modal-eigrp-network-cidr').value.trim(),
  19215. comment: document.getElementById('modal-eigrp-network-comment').value.trim()
  19216. };
  19217. try {
  19218. const res = await fetch(`${API_BASE}/routing/eigrp/networks`, {
  19219. method: 'POST',
  19220. headers: { 'Content-Type': 'application/json' },
  19221. body: JSON.stringify(payload)
  19222. });
  19223. if (!res.ok) throw new Error(await res.text());
  19224. closeEigrpNetworkModal();
  19225. showToast('Saved', `EIGRP network saved`, 'success');
  19226. await loadDynamicRouting(false);
  19227. } catch (err) {
  19228. showToast('Error', err.message, 'error');
  19229. }
  19230. }
  19231. async function removeSelectedEigrpNetwork() {
  19232. const id = state.selectedEigrpRow?.networks;
  19233. if (!id || !confirm('Are you sure you want to remove this EIGRP network?')) return;
  19234. await fetch(`${API_BASE}/routing/eigrp/networks/${id}`, { method: 'DELETE' });
  19235. state.selectedEigrpRow.networks = null;
  19236. await loadDynamicRouting(false);
  19237. }
  19238. // --- EIGRP INTERFACES ---
  19239. function renderEigrpInterfaces() {
  19240. const tbody = document.getElementById('eigrp-interfaces-table-body');
  19241. if (!tbody) return;
  19242. const countEl = document.getElementById('eigrp-interfaces-footer-count');
  19243. const filter = (document.getElementById('filter-eigrp-interfaces')?.value || '').toLowerCase();
  19244. let list = state.eigrpInterfaces || [];
  19245. if (filter) {
  19246. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19247. }
  19248. if (countEl) countEl.innerText = list.length;
  19249. const selId = state.selectedEigrpRow?.interfaces;
  19250. tbody.innerHTML = list.map((iface, idx) => {
  19251. const isSel = iface.id === selId;
  19252. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19253. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400 font-bold">E</span>';
  19254. return `
  19255. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('interfaces', '${iface.id}')" ondblclick="openEditEigrpInterfaceModal('${iface.id}')">
  19256. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19257. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19258. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  19259. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  19260. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  19261. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 5}s / ${iface.hold_time || 15}s</td>
  19262. <td class="py-1.5 px-3 font-mono ${iface.passive ? 'text-amber-400 font-bold' : 'text-slate-400'}">${iface.passive ? 'Yes' : 'No'}</td>
  19263. <td class="py-1.5 px-3 font-mono ${iface.split_horizon ? 'text-emerald-400' : 'text-slate-400'}">${iface.split_horizon ? 'Yes' : 'No'}</td>
  19264. <td class="py-1.5 px-3 text-slate-300 uppercase font-mono">${escapeHtml(iface.auth_mode || 'none')}</td>
  19265. </tr>
  19266. `;
  19267. }).join('');
  19268. }
  19269. function toggleEigrpAuthKey() {
  19270. const mode = document.getElementById('modal-eigrp-iface-auth-mode')?.value;
  19271. const wrap = document.getElementById('modal-eigrp-iface-auth-key-wrap');
  19272. if (wrap) {
  19273. if (mode === 'md5') wrap.classList.remove('hidden');
  19274. else wrap.classList.add('hidden');
  19275. }
  19276. }
  19277. function openEigrpInterfaceModal() {
  19278. document.getElementById('eigrp-interface-modal-title').innerText = 'Add EIGRP Interface Profile';
  19279. document.getElementById('modal-eigrp-iface-id').value = '';
  19280. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19281. if (instSel) {
  19282. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19283. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19284. }
  19285. const dl = document.getElementById('eigrp-iface-datalist');
  19286. if (dl && state.interfaces) {
  19287. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19288. }
  19289. document.getElementById('modal-eigrp-iface-interface').value = '*';
  19290. document.getElementById('modal-eigrp-iface-hello').value = '5';
  19291. document.getElementById('modal-eigrp-iface-hold').value = '15';
  19292. document.getElementById('modal-eigrp-iface-auth-mode').value = 'none';
  19293. document.getElementById('modal-eigrp-iface-auth-key').value = '';
  19294. toggleEigrpAuthKey();
  19295. document.getElementById('modal-eigrp-iface-passive').checked = false;
  19296. document.getElementById('modal-eigrp-iface-split-horizon').checked = true;
  19297. document.getElementById('modal-eigrp-iface-comment').value = '';
  19298. document.getElementById('modal-eigrp-iface-enabled').checked = true;
  19299. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19300. }
  19301. function openEditEigrpInterfaceModal(id) {
  19302. const iface = (state.eigrpInterfaces || []).find(i => i.id === id);
  19303. if (!iface) return;
  19304. document.getElementById('eigrp-interface-modal-title').innerText = `Edit EIGRP Interface: ${iface.interface}`;
  19305. document.getElementById('modal-eigrp-iface-id').value = iface.id;
  19306. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19307. if (instSel) {
  19308. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19309. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19310. instSel.value = iface.instance || 'all';
  19311. }
  19312. const dl = document.getElementById('eigrp-iface-datalist');
  19313. if (dl && state.interfaces) {
  19314. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19315. }
  19316. document.getElementById('modal-eigrp-iface-interface').value = iface.interface || '*';
  19317. document.getElementById('modal-eigrp-iface-hello').value = iface.hello_interval || 5;
  19318. document.getElementById('modal-eigrp-iface-hold').value = iface.hold_time || 15;
  19319. document.getElementById('modal-eigrp-iface-auth-mode').value = iface.auth_mode || 'none';
  19320. document.getElementById('modal-eigrp-iface-auth-key').value = iface.auth_key || '';
  19321. toggleEigrpAuthKey();
  19322. document.getElementById('modal-eigrp-iface-passive').checked = !!iface.passive;
  19323. document.getElementById('modal-eigrp-iface-split-horizon').checked = iface.split_horizon !== false;
  19324. document.getElementById('modal-eigrp-iface-comment').value = iface.comment || '';
  19325. document.getElementById('modal-eigrp-iface-enabled').checked = !iface.disabled;
  19326. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19327. }
  19328. function closeEigrpInterfaceModal() {
  19329. document.getElementById('eigrp-interface-modal')?.classList.add('hidden');
  19330. }
  19331. async function submitEigrpInterface(e) {
  19332. e.preventDefault();
  19333. const payload = {
  19334. id: document.getElementById('modal-eigrp-iface-id').value.trim() || undefined,
  19335. instance: document.getElementById('modal-eigrp-iface-instance').value,
  19336. interface: document.getElementById('modal-eigrp-iface-interface').value.trim(),
  19337. hello_interval: parseInt(document.getElementById('modal-eigrp-iface-hello').value, 10) || 5,
  19338. hold_time: parseInt(document.getElementById('modal-eigrp-iface-hold').value, 10) || 15,
  19339. passive: document.getElementById('modal-eigrp-iface-passive').checked,
  19340. split_horizon: document.getElementById('modal-eigrp-iface-split-horizon').checked,
  19341. auth_mode: document.getElementById('modal-eigrp-iface-auth-mode').value,
  19342. auth_key: document.getElementById('modal-eigrp-iface-auth-key').value.trim(),
  19343. comment: document.getElementById('modal-eigrp-iface-comment').value.trim(),
  19344. disabled: !document.getElementById('modal-eigrp-iface-enabled').checked
  19345. };
  19346. try {
  19347. const res = await fetch(`${API_BASE}/routing/eigrp/interfaces`, {
  19348. method: 'POST',
  19349. headers: { 'Content-Type': 'application/json' },
  19350. body: JSON.stringify(payload)
  19351. });
  19352. if (!res.ok) throw new Error(await res.text());
  19353. closeEigrpInterfaceModal();
  19354. showToast('Saved', `EIGRP interface saved`, 'success');
  19355. await loadDynamicRouting(false);
  19356. } catch (err) {
  19357. showToast('Error', err.message, 'error');
  19358. }
  19359. }
  19360. async function enableSelectedEigrpInterface() {
  19361. const id = state.selectedEigrpRow?.interfaces;
  19362. if (!id) return;
  19363. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  19364. await loadDynamicRouting(false);
  19365. }
  19366. async function disableSelectedEigrpInterface() {
  19367. const id = state.selectedEigrpRow?.interfaces;
  19368. if (!id) return;
  19369. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  19370. await loadDynamicRouting(false);
  19371. }
  19372. async function removeSelectedEigrpInterface() {
  19373. const id = state.selectedEigrpRow?.interfaces;
  19374. if (!id || !confirm('Are you sure you want to remove this EIGRP interface?')) return;
  19375. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}`, { method: 'DELETE' });
  19376. state.selectedEigrpRow.interfaces = null;
  19377. await loadDynamicRouting(false);
  19378. }
  19379. // --- EIGRP NEIGHBORS (LIVE) ---
  19380. function renderEigrpNeighbors() {
  19381. const tbody = document.getElementById('eigrp-neighbors-table-body');
  19382. if (!tbody) return;
  19383. const countEl = document.getElementById('eigrp-neighbors-footer-count');
  19384. const filter = (document.getElementById('filter-eigrp-neighbors')?.value || '').toLowerCase();
  19385. let list = state.eigrpNeighbors || [];
  19386. if (filter) {
  19387. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.interface || '').toLowerCase().includes(filter) || String(n.as || '').includes(filter));
  19388. }
  19389. if (countEl) countEl.innerText = list.length;
  19390. tbody.innerHTML = list.map((nbr, idx) => `
  19391. <tr class="hover:bg-[#1a2636] text-slate-300">
  19392. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19393. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${nbr.as || '-'}</td>
  19394. <td class="py-1.5 px-3 font-mono font-semibold text-purple-300">${escapeHtml(nbr.address || '')}</td>
  19395. <td class="py-1.5 px-3 font-mono text-white">${escapeHtml(nbr.interface || '')}</td>
  19396. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.hold_time || 0}s</td>
  19397. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '-')}</td>
  19398. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.srtt || 0}</td>
  19399. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.rto || 0}</td>
  19400. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.q_cnt || 0}</td>
  19401. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.seq_num || 0}</td>
  19402. </tr>
  19403. `).join('');
  19404. }
  19405. // --- EIGRP TOPOLOGY (LIVE) ---
  19406. function renderEigrpTopology() {
  19407. const tbody = document.getElementById('eigrp-topology-table-body');
  19408. if (!tbody) return;
  19409. const countEl = document.getElementById('eigrp-topology-footer-count');
  19410. const filter = (document.getElementById('filter-eigrp-topology')?.value || '').toLowerCase();
  19411. let list = state.eigrpTopology || [];
  19412. if (filter) {
  19413. 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));
  19414. }
  19415. if (countEl) countEl.innerText = list.length;
  19416. tbody.innerHTML = list.map((top, idx) => `
  19417. <tr class="hover:bg-[#1a2636] text-slate-300">
  19418. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19419. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${top.as || '-'}</td>
  19420. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(top.network || '')}</td>
  19421. <td class="py-1.5 px-3 font-mono text-slate-300">${top.successors || 1}</td>
  19422. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(top.fd || '-')}</td>
  19423. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(top.next_hop || '-')}</td>
  19424. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(top.interface || '-')}</td>
  19425. </tr>
  19426. `).join('');
  19427. }