app.js 933 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619
  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 =>
  6724. `${r.id}:${r.dst_address}:${r.gateway}:${r.interface}:${r.distance}:${r.routing_table}:${r.active}:${r.disabled}:${r.protocol}:${r.comment}:${r.check_gateway}:${r.check_target}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`
  6725. ).join(';');
  6726. if (tbody.dataset.sig === sig) {
  6727. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6728. }
  6729. tbody.dataset.sig = sig;
  6730. tbody.innerHTML = '';
  6731. routes.forEach(r => {
  6732. const tr = document.createElement('tr');
  6733. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6734. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6735. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6736. let flags = '';
  6737. if (r.dynamic) flags += 'D';
  6738. if (r.active) flags += 'A';
  6739. if (r.connect) flags += 'C';
  6740. if (r.static) flags += 'S';
  6741. if (r.ecmp) flags += 'E';
  6742. if (r.multicast) flags += 'M';
  6743. if (r.disabled) flags += 'X';
  6744. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6745. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6746. if (r.check_gateway === 'internet') {
  6747. if (r.health_status === 'online') {
  6748. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6749. healthCell = `
  6750. <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)">
  6751. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6752. <span>Internet OK (${ms}ms)</span>
  6753. </span>
  6754. `;
  6755. } else if (r.health_status === 'offline') {
  6756. healthCell = `
  6757. <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.">
  6758. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6759. <span>Internet Down</span>
  6760. </span>
  6761. `;
  6762. } else {
  6763. healthCell = `
  6764. <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">
  6765. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6766. <span>Checking...</span>
  6767. </span>
  6768. `;
  6769. }
  6770. } else if (r.check_gateway === 'ping') {
  6771. if (r.health_status === 'online') {
  6772. healthCell = `
  6773. <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">
  6774. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6775. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6776. </span>
  6777. `;
  6778. } else if (r.health_status === 'offline') {
  6779. healthCell = `
  6780. <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">
  6781. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6782. <span>Gateway Dead</span>
  6783. </span>
  6784. `;
  6785. }
  6786. }
  6787. const flagDescriptions = [];
  6788. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6789. if (r.active) flagDescriptions.push('Active (A)');
  6790. if (r.connect) flagDescriptions.push('Connected (C)');
  6791. if (r.static) flagDescriptions.push('Static (S)');
  6792. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6793. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6794. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6795. tr.innerHTML = `
  6796. <td class="py-2.5 px-3 text-center">
  6797. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6798. 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')
  6799. }" title="Flags: ${flagDescriptions.join(', ')}">
  6800. ${flags || '-'}
  6801. </span>
  6802. </td>
  6803. <td class="py-2.5 px-3">
  6804. <div class="flex items-center gap-1.5 flex-wrap">
  6805. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6806. ${r.ecmp ? `
  6807. <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)">
  6808. <span>⚡ ECMP</span>
  6809. </span>
  6810. ` : ''}
  6811. ${r.multicast ? `
  6812. <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">
  6813. <span>IGMP</span>
  6814. </span>
  6815. ` : ''}
  6816. </div>
  6817. </td>
  6818. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6819. <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>
  6820. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6821. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6822. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6823. <td class="py-2.5 px-3">${healthCell}</td>
  6824. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6825. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6826. ${r.static ? `
  6827. <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>
  6828. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6829. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6830. ` : `
  6831. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6832. `}
  6833. </td>
  6834. `;
  6835. tbody.appendChild(tr);
  6836. });
  6837. }
  6838. function openAddRouteModal() {
  6839. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6840. document.getElementById('route-modal-id').value = '';
  6841. document.getElementById('route-modal-old-dst').value = '';
  6842. document.getElementById('route-modal-old-gw').value = '';
  6843. document.getElementById('route-modal-old-distance').value = '';
  6844. document.getElementById('route-modal-old-table').value = '';
  6845. document.getElementById('route-modal-old-iface').value = '';
  6846. const dstInput = document.getElementById('route-modal-dst');
  6847. const gwInput = document.getElementById('route-modal-gw');
  6848. const distInput = document.getElementById('route-modal-distance');
  6849. const ifaceSelect = document.getElementById('route-modal-iface');
  6850. const tableSelect = document.getElementById('route-modal-table');
  6851. const commentInput = document.getElementById('route-modal-comment');
  6852. const disCheck = document.getElementById('route-modal-disabled');
  6853. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6854. dstInput.disabled = false;
  6855. dstInput.value = '0.0.0.0/0';
  6856. gwInput.disabled = false;
  6857. gwInput.value = '';
  6858. distInput.disabled = false;
  6859. distInput.value = '1';
  6860. ifaceSelect.disabled = false;
  6861. tableSelect.disabled = false;
  6862. commentInput.disabled = false;
  6863. commentInput.value = '';
  6864. disCheck.disabled = false;
  6865. disCheck.checked = false;
  6866. if (saveBtn) saveBtn.classList.remove('hidden');
  6867. const checkGw = document.getElementById('route-modal-check-gw');
  6868. if (checkGw) checkGw.value = 'internet';
  6869. const checkTarget = document.getElementById('route-modal-check-target');
  6870. if (checkTarget) checkTarget.value = '1.1.1.1';
  6871. const checkInterval = document.getElementById('route-modal-check-interval');
  6872. if (checkInterval) checkInterval.value = '5';
  6873. const checkThresh = document.getElementById('route-modal-check-threshold');
  6874. if (checkThresh) checkThresh.value = '3';
  6875. toggleRouteCheckModeUI();
  6876. populateInterfaceSelect('route-modal-iface');
  6877. // Populate tables
  6878. tableSelect.innerHTML = '';
  6879. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6880. const opt = document.createElement('option');
  6881. opt.value = t.name;
  6882. opt.innerText = t.name;
  6883. if (t.name === 'main') opt.selected = true;
  6884. tableSelect.appendChild(opt);
  6885. });
  6886. document.getElementById('route-modal').classList.remove('hidden');
  6887. }
  6888. function openEditRouteModal(id) {
  6889. const r = (state.routes || []).find(route => route.id === id);
  6890. if (!r) return;
  6891. const isStatic = !!r.static;
  6892. document.getElementById('route-modal-title').innerText = isStatic
  6893. ? `Edit Route: ${r.dst_address}`
  6894. : `Route Properties (Read Only): ${r.dst_address}`;
  6895. document.getElementById('route-modal-id').value = r.id;
  6896. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6897. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6898. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6899. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6900. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6901. const dstInput = document.getElementById('route-modal-dst');
  6902. const gwInput = document.getElementById('route-modal-gw');
  6903. const distInput = document.getElementById('route-modal-distance');
  6904. const ifaceSelect = document.getElementById('route-modal-iface');
  6905. const tableSelect = document.getElementById('route-modal-table');
  6906. const commentInput = document.getElementById('route-modal-comment');
  6907. const disCheck = document.getElementById('route-modal-disabled');
  6908. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6909. dstInput.value = r.dst_address;
  6910. gwInput.value = r.gateway || '';
  6911. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6912. commentInput.value = r.comment || '';
  6913. disCheck.checked = !!r.disabled;
  6914. const checkGw = document.getElementById('route-modal-check-gw');
  6915. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6916. const checkTarget = document.getElementById('route-modal-check-target');
  6917. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6918. const checkInterval = document.getElementById('route-modal-check-interval');
  6919. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6920. const checkThresh = document.getElementById('route-modal-check-threshold');
  6921. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6922. toggleRouteCheckModeUI();
  6923. dstInput.disabled = !isStatic;
  6924. gwInput.disabled = !isStatic;
  6925. distInput.disabled = !isStatic;
  6926. ifaceSelect.disabled = !isStatic;
  6927. tableSelect.disabled = !isStatic;
  6928. commentInput.disabled = !isStatic;
  6929. disCheck.disabled = !isStatic;
  6930. if (checkGw) checkGw.disabled = !isStatic;
  6931. if (checkTarget) checkTarget.disabled = !isStatic;
  6932. if (checkInterval) checkInterval.disabled = !isStatic;
  6933. if (checkThresh) checkThresh.disabled = !isStatic;
  6934. if (saveBtn) {
  6935. if (isStatic) {
  6936. saveBtn.classList.remove('hidden');
  6937. } else {
  6938. saveBtn.classList.add('hidden');
  6939. }
  6940. }
  6941. populateInterfaceSelect('route-modal-iface', r.interface);
  6942. tableSelect.innerHTML = '';
  6943. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6944. const opt = document.createElement('option');
  6945. opt.value = t.name;
  6946. opt.innerText = t.name;
  6947. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6948. tableSelect.appendChild(opt);
  6949. });
  6950. document.getElementById('route-modal').classList.remove('hidden');
  6951. }
  6952. function closeRouteModal() {
  6953. document.getElementById('route-modal').classList.add('hidden');
  6954. }
  6955. function setRouteCheckTarget(ip) {
  6956. const inp = document.getElementById('route-modal-check-target');
  6957. if (inp) inp.value = ip;
  6958. }
  6959. function toggleRouteCheckModeUI() {
  6960. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6961. const targetRow = document.getElementById('route-row-check-target');
  6962. const paramsRow = document.getElementById('route-row-check-params');
  6963. if (mode === 'none') {
  6964. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6965. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6966. } else if (mode === 'ping') {
  6967. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6968. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6969. } else { // internet
  6970. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6971. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6972. }
  6973. }
  6974. async function submitSaveRoute(e) {
  6975. e.preventDefault();
  6976. const id = document.getElementById('route-modal-id').value;
  6977. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6978. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6979. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6980. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6981. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6982. const dst = document.getElementById('route-modal-dst').value.trim();
  6983. const gw = document.getElementById('route-modal-gw').value.trim();
  6984. const table = document.getElementById('route-modal-table').value;
  6985. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6986. const iface = document.getElementById('route-modal-iface').value;
  6987. const comment = document.getElementById('route-modal-comment').value.trim();
  6988. const disabled = document.getElementById('route-modal-disabled').checked;
  6989. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6990. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6991. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6992. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6993. if (!dst) {
  6994. showToast('Error', 'Destination address is required', 'error');
  6995. return;
  6996. }
  6997. if (!gw && !iface) {
  6998. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6999. return;
  7000. }
  7001. const payload = {
  7002. id,
  7003. old_dst_address: oldDst,
  7004. old_gateway: oldGw,
  7005. old_routing_table: oldTable,
  7006. old_interface: oldIface,
  7007. dst_address: dst,
  7008. gateway: gw || iface,
  7009. routing_table: table,
  7010. distance,
  7011. interface: iface,
  7012. comment,
  7013. disabled,
  7014. check_gateway,
  7015. check_target,
  7016. check_interval,
  7017. check_threshold
  7018. };
  7019. if (oldDistStr !== undefined && oldDistStr !== '') {
  7020. payload.old_distance = parseInt(oldDistStr, 10);
  7021. }
  7022. try {
  7023. const res = await fetch(`${API_BASE}/routes`, {
  7024. method: 'POST',
  7025. headers: { 'Content-Type': 'application/json' },
  7026. body: JSON.stringify(payload)
  7027. });
  7028. if (res.ok) {
  7029. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7030. closeRouteModal();
  7031. const tbody = document.getElementById('routes-table-body');
  7032. if (tbody) tbody.dataset.sig = '';
  7033. loadRoutes();
  7034. } else {
  7035. const err = await res.json().catch(() => ({}));
  7036. showToast('Error', err.message || err.error || 'Failed to save route', 'error');
  7037. }
  7038. } catch (err) {
  7039. showToast('Error', err.message, 'error');
  7040. }
  7041. }
  7042. async function toggleRouteState(id, disabled) {
  7043. try {
  7044. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7045. method: 'POST',
  7046. headers: { 'Content-Type': 'application/json' },
  7047. body: JSON.stringify({ disabled })
  7048. });
  7049. if (res.ok) {
  7050. const tbody = document.getElementById('routes-table-body');
  7051. if (tbody) tbody.dataset.sig = '';
  7052. loadRoutes();
  7053. } else {
  7054. const err = await res.json().catch(() => ({}));
  7055. showToast('Error', err.message || err.error || 'Failed to update route state', 'error');
  7056. }
  7057. } catch (err) {
  7058. showToast('Error', err.message, 'error');
  7059. }
  7060. }
  7061. async function deleteRoute(id) {
  7062. if (!confirm('Are you sure you want to delete this route?')) return;
  7063. try {
  7064. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7065. if (res.ok) {
  7066. showToast('Deleted', 'Route removed', 'success');
  7067. const tbody = document.getElementById('routes-table-body');
  7068. if (tbody) tbody.dataset.sig = '';
  7069. loadRoutes();
  7070. } else {
  7071. const err = await res.json().catch(() => ({}));
  7072. showToast('Error', err.message || err.error || 'Failed to delete route', 'error');
  7073. }
  7074. } catch (err) {
  7075. showToast('Error', err.message, 'error');
  7076. }
  7077. }
  7078. // ----------------- Policy Rules (/ip route rule) -----------------
  7079. function renderPolicyRules() {
  7080. const tbody = document.getElementById('rules-table-body');
  7081. const empty = document.getElementById('rules-empty');
  7082. if (!tbody) return;
  7083. const showSystem = document.getElementById('prule-show-system')?.checked;
  7084. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7085. const countBadge = document.getElementById('rules-count-badge');
  7086. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7087. const bRules = document.getElementById('routes-badge-rules');
  7088. if (bRules) bRules.innerText = filtered.length;
  7089. if (filtered.length === 0) {
  7090. empty?.classList.remove('hidden');
  7091. tbody.innerHTML = '';
  7092. return;
  7093. }
  7094. empty?.classList.add('hidden');
  7095. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7096. if (tbody.dataset.sig === sig) return;
  7097. tbody.dataset.sig = sig;
  7098. tbody.innerHTML = '';
  7099. filtered.forEach(pr => {
  7100. const isSys = pr.is_default || pr.is_system;
  7101. const tr = document.createElement('tr');
  7102. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7103. tr.innerHTML = `
  7104. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7105. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7106. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7107. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7108. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7109. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7110. <td class="py-2.5 px-3 text-right font-sans">
  7111. ${!pr.is_default ? `
  7112. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7113. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7114. </td>
  7115. `;
  7116. tbody.appendChild(tr);
  7117. });
  7118. }
  7119. function openAddPolicyRuleModal() {
  7120. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7121. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7122. document.getElementById('prule-modal-mark').value = '';
  7123. document.getElementById('prule-modal-src').value = '';
  7124. document.getElementById('prule-modal-dst').value = '';
  7125. const sel = document.getElementById('prule-modal-table');
  7126. sel.innerHTML = '';
  7127. (state.routingTables || []).forEach(t => {
  7128. const opt = document.createElement('option');
  7129. opt.value = t.name;
  7130. opt.innerText = t.name;
  7131. sel.appendChild(opt);
  7132. });
  7133. document.getElementById('prule-modal').classList.remove('hidden');
  7134. }
  7135. function closePolicyRuleModal() {
  7136. document.getElementById('prule-modal').classList.add('hidden');
  7137. }
  7138. async function submitSavePolicyRule(e) {
  7139. e.preventDefault();
  7140. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7141. const mark = document.getElementById('prule-modal-mark').value.trim();
  7142. const src = document.getElementById('prule-modal-src').value.trim();
  7143. const dst = document.getElementById('prule-modal-dst').value.trim();
  7144. const table = document.getElementById('prule-modal-table').value;
  7145. const action = document.getElementById('prule-modal-action').value;
  7146. try {
  7147. const res = await fetch(`${API_BASE}/routing/rules`, {
  7148. method: 'POST',
  7149. headers: { 'Content-Type': 'application/json' },
  7150. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7151. });
  7152. if (res.ok) {
  7153. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7154. closePolicyRuleModal();
  7155. loadRoutes();
  7156. } else {
  7157. const err = await res.json();
  7158. showToast('Error', err.message, 'error');
  7159. }
  7160. } catch (err) {
  7161. showToast('Error', err.message, 'error');
  7162. }
  7163. }
  7164. async function deletePolicyRule(id) {
  7165. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7166. try {
  7167. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7168. if (res.ok) {
  7169. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7170. loadRoutes();
  7171. }
  7172. } catch (err) {
  7173. showToast('Error', err.message, 'error');
  7174. }
  7175. }
  7176. // ----------------- Routing Tables -----------------
  7177. function renderRoutingTables() {
  7178. const tbody = document.getElementById('tables-table-body');
  7179. if (!tbody) return;
  7180. const tables = state.routingTables || [];
  7181. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7182. if (tbody.dataset.sig === sig) return;
  7183. tbody.dataset.sig = sig;
  7184. tbody.innerHTML = '';
  7185. (state.routingTables || []).forEach(t => {
  7186. const tr = document.createElement('tr');
  7187. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7188. tr.innerHTML = `
  7189. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7190. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7191. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7192. `;
  7193. tbody.appendChild(tr);
  7194. });
  7195. }
  7196. function openAddTableModal() {
  7197. document.getElementById('table-modal-name').value = '';
  7198. document.getElementById('table-modal-id').value = '';
  7199. document.getElementById('table-modal-comment').value = '';
  7200. document.getElementById('table-modal').classList.remove('hidden');
  7201. }
  7202. function closeTableModal() {
  7203. document.getElementById('table-modal').classList.add('hidden');
  7204. }
  7205. async function submitSaveTable(e) {
  7206. e.preventDefault();
  7207. const name = document.getElementById('table-modal-name').value.trim();
  7208. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7209. const comment = document.getElementById('table-modal-comment').value.trim();
  7210. try {
  7211. const res = await fetch(`${API_BASE}/routing/tables`, {
  7212. method: 'POST',
  7213. headers: { 'Content-Type': 'application/json' },
  7214. body: JSON.stringify({ name, table_id: id, comment })
  7215. });
  7216. if (res.ok) {
  7217. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7218. closeTableModal();
  7219. loadRoutes();
  7220. } else {
  7221. const err = await res.json();
  7222. showToast('Error', err.message, 'error');
  7223. }
  7224. } catch (err) {
  7225. showToast('Error', err.message, 'error');
  7226. }
  7227. }
  7228. async function loadDebianConfig() {
  7229. const view = document.getElementById('debian-config-view');
  7230. view.innerText = 'Generating live configuration...';
  7231. try {
  7232. const res = await fetch(`${API_BASE}/debian/config`);
  7233. const data = await res.json();
  7234. view.innerText = data.content || '# Empty config';
  7235. } catch (err) {
  7236. view.innerText = 'Failed to generate Debian network config.';
  7237. }
  7238. }
  7239. async function saveDebianConfig() {
  7240. try {
  7241. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7242. const data = await res.json();
  7243. if (res.ok) {
  7244. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7245. loadDebianConfig();
  7246. }
  7247. } catch (err) {
  7248. showToast('Error', err.message, 'error');
  7249. }
  7250. }
  7251. function showToast(title, message, type = 'info') {
  7252. const container = document.getElementById('toast-container');
  7253. const toast = document.createElement('div');
  7254. const borderColors = {
  7255. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7256. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7257. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7258. };
  7259. 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}`;
  7260. toast.innerHTML = `
  7261. <div class="flex-1">
  7262. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7263. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7264. </div>
  7265. `;
  7266. container.appendChild(toast);
  7267. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7268. setTimeout(() => {
  7269. toast.classList.add('opacity-0', 'translate-y-2');
  7270. setTimeout(() => toast.remove(), 300);
  7271. }, 4000);
  7272. }
  7273. function formatTraffic(bytesPerSec) {
  7274. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7275. const kb = bytesPerSec / 1024;
  7276. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7277. const mb = kb / 1024;
  7278. return `${mb.toFixed(2)} MB/s`;
  7279. }
  7280. function toggleSidebar() {
  7281. const sb = document.getElementById('sidebar');
  7282. sb.classList.toggle('-translate-x-full');
  7283. }
  7284. // ======================== EoIP (Ethernet over IP) ========================
  7285. async function loadEoIP(populate = true) {
  7286. try {
  7287. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7288. const data = await res.json();
  7289. state.eoipTunnels = Array.isArray(data) ? data : [];
  7290. const badge = document.getElementById('eoip-count-badge');
  7291. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7292. const sideBadge = document.getElementById('badge-eoip-count');
  7293. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7294. renderEoIPTunnels();
  7295. } catch (err) {
  7296. console.error('Failed to load EoIP:', err);
  7297. }
  7298. }
  7299. function renderEoIPTunnels() {
  7300. const tbody = document.getElementById('eoip-table-body');
  7301. const empty = document.getElementById('eoip-empty');
  7302. if (!tbody) return;
  7303. tbody.innerHTML = '';
  7304. const tunnels = state.eoipTunnels || [];
  7305. if (tunnels.length === 0) {
  7306. empty?.classList.remove('hidden');
  7307. return;
  7308. }
  7309. empty?.classList.add('hidden');
  7310. tunnels.forEach(t => {
  7311. const tr = document.createElement('tr');
  7312. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7313. tr.innerHTML = `
  7314. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7315. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7316. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7317. <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>
  7318. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7319. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7320. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7321. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7322. <td class="py-2.5 px-3 font-mono text-[11px]">
  7323. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7324. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7325. </td>
  7326. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7327. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7328. <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>
  7329. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7330. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7331. </td>
  7332. `;
  7333. tbody.appendChild(tr);
  7334. });
  7335. }
  7336. function openAddEoIPModal() {
  7337. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7338. document.getElementById('eoip-modal-id').value = '';
  7339. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7340. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7341. document.getElementById('eoip-modal-remote').value = '';
  7342. document.getElementById('eoip-modal-ip').value = '';
  7343. document.getElementById('eoip-modal-local').value = '';
  7344. document.getElementById('eoip-modal-mac').value = '';
  7345. document.getElementById('eoip-modal-mtu').value = '1500';
  7346. document.getElementById('eoip-modal-comment').value = '';
  7347. document.getElementById('eoip-modal-clampmss').checked = true;
  7348. document.getElementById('eoip-modal-disabled').checked = false;
  7349. document.getElementById('eoip-modal').classList.remove('hidden');
  7350. }
  7351. function openEditEoIPModal(id) {
  7352. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7353. if (!t) return;
  7354. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7355. document.getElementById('eoip-modal-id').value = t.id;
  7356. document.getElementById('eoip-modal-name').value = t.name;
  7357. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7358. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7359. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7360. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7361. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7362. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7363. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7364. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7365. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7366. document.getElementById('eoip-modal').classList.remove('hidden');
  7367. }
  7368. function closeEoIPModal() {
  7369. document.getElementById('eoip-modal').classList.add('hidden');
  7370. }
  7371. async function submitSaveEoIP(e) {
  7372. e.preventDefault();
  7373. const id = document.getElementById('eoip-modal-id').value;
  7374. const name = document.getElementById('eoip-modal-name').value.trim();
  7375. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7376. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7377. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7378. const local = document.getElementById('eoip-modal-local').value.trim();
  7379. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7380. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7381. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7382. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7383. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7384. try {
  7385. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7386. method: 'POST',
  7387. headers: { 'Content-Type': 'application/json' },
  7388. body: JSON.stringify({
  7389. id,
  7390. name,
  7391. tunnel_id: tunnelId,
  7392. remote_address: remote,
  7393. ip_address: ipAddress,
  7394. local_address: local,
  7395. mac_address: mac,
  7396. mtu,
  7397. clamp_mss: clampMss,
  7398. comment,
  7399. disabled
  7400. })
  7401. });
  7402. if (res.ok) {
  7403. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7404. closeEoIPModal();
  7405. loadEoIP(false);
  7406. fetchData(false);
  7407. } else {
  7408. const err = await res.json();
  7409. showToast('Error', err.message, 'error');
  7410. }
  7411. } catch (err) {
  7412. showToast('Error', err.message, 'error');
  7413. }
  7414. }
  7415. async function toggleEoIPState(id, disabled) {
  7416. try {
  7417. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7418. method: 'POST',
  7419. headers: { 'Content-Type': 'application/json' },
  7420. body: JSON.stringify({ disabled })
  7421. });
  7422. if (res.ok) {
  7423. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7424. loadEoIP(false);
  7425. fetchData(false);
  7426. }
  7427. } catch (err) {
  7428. showToast('Error', err.message, 'error');
  7429. }
  7430. }
  7431. async function deleteEoIP(id) {
  7432. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7433. try {
  7434. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7435. if (res.ok) {
  7436. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7437. loadEoIP(false);
  7438. fetchData(false);
  7439. }
  7440. } catch (err) {
  7441. showToast('Error', err.message, 'error');
  7442. }
  7443. }
  7444. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7445. async function loadVXLAN(populate = true) {
  7446. try {
  7447. const [tunnelsRes, vtepsRes] = await Promise.all([
  7448. fetch(`${API_BASE}/vpn/vxlan`),
  7449. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7450. ]);
  7451. if (tunnelsRes.ok) {
  7452. state.vxlanTunnels = await tunnelsRes.json() || [];
  7453. }
  7454. if (vtepsRes.ok) {
  7455. state.vxlanVteps = await vtepsRes.json() || [];
  7456. }
  7457. renderVXLANTable();
  7458. renderVXLANVtepsTable();
  7459. const countBadge = document.getElementById('vxlan-count-badge');
  7460. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7461. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7462. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7463. const navBadge = document.getElementById('badge-vxlan-count');
  7464. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7465. } catch (err) {
  7466. console.error('Error loading VXLAN:', err);
  7467. }
  7468. }
  7469. function renderVXLANTable() {
  7470. const tbody = document.getElementById('vxlan-table-body');
  7471. const empty = document.getElementById('vxlan-empty');
  7472. if (!tbody || !empty) return;
  7473. tbody.innerHTML = '';
  7474. const tunnels = state.vxlanTunnels || [];
  7475. if (tunnels.length === 0) {
  7476. empty.classList.remove('hidden');
  7477. return;
  7478. }
  7479. empty.classList.add('hidden');
  7480. tunnels.forEach(t => {
  7481. const tr = document.createElement('tr');
  7482. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7483. let flag = '';
  7484. if (t.disabled) {
  7485. 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>';
  7486. } else if (t.running) {
  7487. 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>';
  7488. } else {
  7489. 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>';
  7490. }
  7491. const vtepCount = (t.vteps || []).length;
  7492. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7493. tr.innerHTML = `
  7494. <td class="py-2.5 px-3 text-center">${flag}</td>
  7495. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7496. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7497. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7498. <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>
  7499. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7500. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7501. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7502. <td class="py-2.5 px-3 font-mono">
  7503. <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>
  7504. </td>
  7505. <td class="py-2.5 px-3 font-mono text-[11px]">
  7506. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7507. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7508. </td>
  7509. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7510. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7511. <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>
  7512. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7513. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7514. </td>
  7515. `;
  7516. tbody.appendChild(tr);
  7517. });
  7518. }
  7519. function renderVXLANVtepsTable() {
  7520. const tbody = document.getElementById('vxlan-vteps-table-body');
  7521. const empty = document.getElementById('vxlan-vteps-empty');
  7522. if (!tbody || !empty) return;
  7523. tbody.innerHTML = '';
  7524. const vteps = state.vxlanVteps || [];
  7525. if (vteps.length === 0) {
  7526. empty.classList.remove('hidden');
  7527. return;
  7528. }
  7529. empty.classList.add('hidden');
  7530. vteps.forEach(v => {
  7531. const tr = document.createElement('tr');
  7532. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7533. tr.innerHTML = `
  7534. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7535. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7536. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7537. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7538. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7539. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7540. </td>
  7541. `;
  7542. tbody.appendChild(tr);
  7543. });
  7544. }
  7545. function openAddVXLANModal() {
  7546. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7547. document.getElementById('vxlan-modal-id').value = '';
  7548. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7549. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7550. document.getElementById('vxlan-modal-port').value = '4789';
  7551. document.getElementById('vxlan-modal-ip').value = '';
  7552. document.getElementById('vxlan-modal-parent').value = '';
  7553. document.getElementById('vxlan-modal-local').value = '';
  7554. document.getElementById('vxlan-modal-remote').value = '';
  7555. document.getElementById('vxlan-modal-group').value = '';
  7556. document.getElementById('vxlan-modal-mac').value = '';
  7557. document.getElementById('vxlan-modal-mtu').value = '1500';
  7558. document.getElementById('vxlan-modal-comment').value = '';
  7559. document.getElementById('vxlan-modal-learning').checked = true;
  7560. document.getElementById('vxlan-modal-disabled').checked = false;
  7561. document.getElementById('vxlan-modal').classList.remove('hidden');
  7562. }
  7563. function openEditVXLANModal(id) {
  7564. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7565. if (!t) return;
  7566. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7567. document.getElementById('vxlan-modal-id').value = t.id;
  7568. document.getElementById('vxlan-modal-name').value = t.name;
  7569. document.getElementById('vxlan-modal-vni').value = t.vni;
  7570. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7571. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7572. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7573. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7574. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7575. document.getElementById('vxlan-modal-group').value = t.group || '';
  7576. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7577. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7578. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7579. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7580. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7581. document.getElementById('vxlan-modal').classList.remove('hidden');
  7582. }
  7583. function closeVXLANModal() {
  7584. document.getElementById('vxlan-modal').classList.add('hidden');
  7585. }
  7586. async function submitSaveVXLAN(e) {
  7587. e.preventDefault();
  7588. const id = document.getElementById('vxlan-modal-id').value;
  7589. const name = document.getElementById('vxlan-modal-name').value.trim();
  7590. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7591. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7592. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7593. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7594. const local = document.getElementById('vxlan-modal-local').value.trim();
  7595. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7596. const group = document.getElementById('vxlan-modal-group').value.trim();
  7597. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7598. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7599. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7600. const learning = document.getElementById('vxlan-modal-learning').checked;
  7601. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7602. try {
  7603. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7604. method: 'POST',
  7605. headers: { 'Content-Type': 'application/json' },
  7606. body: JSON.stringify({
  7607. id,
  7608. name,
  7609. vni,
  7610. port,
  7611. ip_address: ipAddress,
  7612. parent_interface: parentInterface,
  7613. local_address: local,
  7614. remote_address: remote,
  7615. group,
  7616. mac_address: mac,
  7617. mtu,
  7618. learning,
  7619. comment,
  7620. disabled
  7621. })
  7622. });
  7623. if (res.ok) {
  7624. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7625. closeVXLANModal();
  7626. loadVXLAN(false);
  7627. fetchData(false);
  7628. } else {
  7629. const err = await res.json();
  7630. showToast('Error', err.message, 'error');
  7631. }
  7632. } catch (err) {
  7633. showToast('Error', err.message, 'error');
  7634. }
  7635. }
  7636. async function toggleVXLANState(id, disabled) {
  7637. try {
  7638. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7639. method: 'POST',
  7640. headers: { 'Content-Type': 'application/json' },
  7641. body: JSON.stringify({ disabled })
  7642. });
  7643. if (res.ok) {
  7644. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7645. loadVXLAN(false);
  7646. fetchData(false);
  7647. }
  7648. } catch (err) {
  7649. showToast('Error', err.message, 'error');
  7650. }
  7651. }
  7652. async function deleteVXLAN(id) {
  7653. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7654. try {
  7655. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7656. if (res.ok) {
  7657. showToast('Deleted', 'VXLAN interface removed', 'success');
  7658. loadVXLAN(false);
  7659. fetchData(false);
  7660. }
  7661. } catch (err) {
  7662. showToast('Error', err.message, 'error');
  7663. }
  7664. }
  7665. function openAddVXLANVtepModal(defaultIface = '') {
  7666. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7667. if (sel) {
  7668. sel.innerHTML = '';
  7669. const tunnels = state.vxlanTunnels || [];
  7670. tunnels.forEach(t => {
  7671. const opt = document.createElement('option');
  7672. opt.value = t.name;
  7673. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7674. if (defaultIface && t.name === defaultIface) {
  7675. opt.selected = true;
  7676. }
  7677. sel.appendChild(opt);
  7678. });
  7679. }
  7680. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7681. document.getElementById('vxlan-vtep-modal-port').value = '';
  7682. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7683. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7684. }
  7685. function closeVXLANVtepModal() {
  7686. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7687. }
  7688. async function submitSaveVXLANVtep(e) {
  7689. e.preventDefault();
  7690. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7691. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7692. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7693. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7694. try {
  7695. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7696. method: 'POST',
  7697. headers: { 'Content-Type': 'application/json' },
  7698. body: JSON.stringify({
  7699. interface: iface,
  7700. remote_ip: remote,
  7701. port,
  7702. comment
  7703. })
  7704. });
  7705. if (res.ok) {
  7706. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7707. closeVXLANVtepModal();
  7708. loadVXLAN(false);
  7709. fetchData(false);
  7710. } else {
  7711. const err = await res.json();
  7712. showToast('Error', err.message, 'error');
  7713. }
  7714. } catch (err) {
  7715. showToast('Error', err.message, 'error');
  7716. }
  7717. }
  7718. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7719. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7720. try {
  7721. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7722. method: 'DELETE'
  7723. });
  7724. if (res.ok) {
  7725. showToast('Deleted', 'Remote VTEP removed', 'success');
  7726. loadVXLAN(false);
  7727. fetchData(false);
  7728. }
  7729. } catch (err) {
  7730. showToast('Error', err.message, 'error');
  7731. }
  7732. }
  7733. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7734. const aeroRateSamples = new Map();
  7735. const aeroLiveRates = new Map();
  7736. async function loadAeroTUN(populate = true) {
  7737. try {
  7738. const [tunnelsRes, statsRes] = await Promise.all([
  7739. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7740. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7741. ]);
  7742. if (tunnelsRes.ok) {
  7743. const data = await tunnelsRes.json();
  7744. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7745. const now = Date.now();
  7746. for (const t of state.aerotunTunnels) {
  7747. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7748. 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) {
  7749. 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});
  7750. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7751. 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});
  7752. }
  7753. }
  7754. if (statsRes.ok) {
  7755. state.aerotunStats = await statsRes.json();
  7756. }
  7757. const countBadge = document.getElementById('aerotun-count-badge');
  7758. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7759. const sideBadge = document.getElementById('badge-aerotun-count');
  7760. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7761. renderAeroTUN();
  7762. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7763. } catch (err) {
  7764. console.error('Failed to load AeroTUN:', err);
  7765. }
  7766. }
  7767. function renderAeroTUN() {
  7768. const tbody = document.getElementById('aerotun-table-body');
  7769. const empty = document.getElementById('aerotun-empty');
  7770. // Update summary cards
  7771. const stats = state.aerotunStats || {};
  7772. const tunnels = state.aerotunTunnels || [];
  7773. const statActive = document.getElementById('aerotun-stat-active');
  7774. if (statActive) {
  7775. const activeCount = tunnels.filter(t => t.connected).length;
  7776. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7777. }
  7778. const statSaved = document.getElementById('aerotun-stat-saved');
  7779. if (statSaved) {
  7780. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7781. }
  7782. const statRatio = document.getElementById('aerotun-stat-ratio');
  7783. if (statRatio) {
  7784. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7785. }
  7786. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7787. if (statTraffic) {
  7788. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7789. }
  7790. if (!tbody) return;
  7791. tbody.innerHTML = '';
  7792. if (tunnels.length === 0) {
  7793. empty?.classList.remove('hidden');
  7794. return;
  7795. }
  7796. empty?.classList.add('hidden');
  7797. tunnels.forEach(t => {
  7798. const tr = document.createElement('tr');
  7799. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7800. const modeBadge = t.mode === 'server'
  7801. ? `<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>`
  7802. : `<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>`;
  7803. const endpointInfo = t.mode === 'server'
  7804. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7805. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7806. const compBadge = t.compression
  7807. ? `<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>`
  7808. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7809. const activePeer = t.connected && t.active_peer_endpoint
  7810. ? `<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>`
  7811. : `<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>`;
  7812. const rawRx = formatBytes(t.rx_bytes || 0);
  7813. const rawTx = formatBytes(t.tx_bytes || 0);
  7814. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7815. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7816. const rate = aeroLiveRates.get(t.id);
  7817. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7818. tr.innerHTML = `
  7819. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7820. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7821. <span>${escapeHtml(t.name)}</span>
  7822. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7823. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7824. </td>
  7825. <td class="py-2.5 px-3">${modeBadge}</td>
  7826. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7827. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7828. <td class="py-2.5 px-3">${compBadge}</td>
  7829. <td class="py-2.5 px-3">${activePeer}</td>
  7830. <td class="py-2.5 px-3 font-mono text-[11px]">
  7831. <span class="text-emerald-400">↓ ${rawRx}</span>
  7832. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7833. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7834. </td>
  7835. <td class="py-2.5 px-3 font-mono text-[11px]">
  7836. <span class="text-slate-400">↓ ${wireRx}</span>
  7837. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7838. </td>
  7839. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7840. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7841. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7842. ${t.running
  7843. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7844. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7845. }
  7846. <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>
  7847. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7848. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7849. </td>
  7850. `;
  7851. tbody.appendChild(tr);
  7852. });
  7853. }
  7854. async function openAeroTUNHealth(encodedID) {
  7855. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7856. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7857. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7858. document.getElementById('aerotun-compare-host').value=underlay;
  7859. document.getElementById('aerotun-compare-result').textContent='';
  7860. document.getElementById('aerotun-health-result').textContent = '';
  7861. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7862. await refreshAeroTUNHealth();
  7863. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7864. }
  7865. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7866. async function refreshAeroTUNHealth() {
  7867. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7868. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7869. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7870. try {
  7871. 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;
  7872. 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);
  7873. const d=t.drop_breakdown;
  7874. 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}`:''}`;
  7875. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7876. if(!events.length){node.textContent='No events recorded yet.';return}
  7877. 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)}
  7878. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7879. }
  7880. async function runAeroTUNHealthCheck() {
  7881. 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…';
  7882. 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()}
  7883. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7884. finally {button.disabled=false}
  7885. }
  7886. let aeroCompareRunning=false, aeroCompareCancel=false;
  7887. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7888. async function runAeroTUNComparison() {
  7889. if(aeroCompareRunning)return;
  7890. 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();
  7891. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7892. 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}
  7893. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7894. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7895. 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()};
  7896. const results=[];
  7897. try {
  7898. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7899. if(aeroCompareCancel)break;
  7900. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7901. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7902. 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;
  7903. 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}}
  7904. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7905. 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.`);
  7906. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7907. }
  7908. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7909. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7910. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7911. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7912. }
  7913. let aeroModalGeneration = 0;
  7914. let aeroIdentityDraft = '';
  7915. let aeroSaving = false;
  7916. let aeroPSKRequest = 0;
  7917. function discardAeroIdentityDraft(id) {
  7918. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7919. }
  7920. async function generateAeroTUNIdentity() {
  7921. const generation = aeroModalGeneration;
  7922. const retry = document.getElementById('aerotun-retry-identity');
  7923. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7924. retry.classList.add('hidden');
  7925. document.getElementById('aerotun-modal-public').value = '';
  7926. try {
  7927. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7928. if (!res.ok) throw new Error(await responseError(res));
  7929. const draft = await res.json();
  7930. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7931. aeroIdentityDraft = draft.draft_id;
  7932. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7933. updateAeroTUNSetupHint();
  7934. } catch (err) {
  7935. if (generation !== aeroModalGeneration) return;
  7936. retry.classList.remove('hidden');
  7937. updateAeroTUNSetupHint();
  7938. showToast('Identity Generation Failed', err.message, 'error');
  7939. }
  7940. }
  7941. function onAeroTUNModeChange() {
  7942. const mode = document.getElementById('aerotun-modal-mode').value;
  7943. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7944. const portInput = document.getElementById('aerotun-modal-port');
  7945. if (mode === 'server') {
  7946. if (!portInput.value) portInput.value = '51830';
  7947. endpointInput.placeholder = 'Optional / learned roaming peer';
  7948. } else {
  7949. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7950. if (!portInput.value) portInput.value = '';
  7951. }
  7952. }
  7953. function onAeroTUNPeerChange() {
  7954. const peer = document.getElementById('aerotun-modal-peer');
  7955. const allowed = document.getElementById('aerotun-modal-allowed');
  7956. const previous = peer.dataset.allowedDefault || '';
  7957. const host = peer.value.trim().split('/')[0];
  7958. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7959. if (allowed.value.trim() === previous) allowed.value = next;
  7960. peer.dataset.allowedDefault = next;
  7961. }
  7962. async function generateAeroTUNKey(automatic = false) {
  7963. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7964. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7965. try {
  7966. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7967. if (!res.ok) throw new Error(await responseError(res));
  7968. const data = await res.json();
  7969. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7970. input.value = data.key;
  7971. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7972. } catch (err) {
  7973. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7974. }
  7975. }
  7976. function updateAeroTUNSetupHint() {
  7977. const version = document.getElementById('aerotun-modal-protocol').value;
  7978. const key = document.getElementById('aerotun-modal-public').value;
  7979. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7980. const hint = document.getElementById('aerotun-setup-hint');
  7981. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7982. if (!hint) return;
  7983. 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.';
  7984. }
  7985. async function copyAeroTUNPublicKey() {
  7986. const input = document.getElementById('aerotun-modal-public');
  7987. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7988. try {
  7989. await navigator.clipboard.writeText(input.value);
  7990. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7991. } catch {
  7992. input.focus(); input.select();
  7993. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7994. }
  7995. }
  7996. async function copyAeroTUNPSK() {
  7997. const input = document.getElementById('aerotun-modal-psk');
  7998. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7999. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  8000. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  8001. }
  8002. function openAddAeroTUNModal() {
  8003. if (aeroSaving) return;
  8004. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8005. const tunnels = state.aerotunTunnels || [];
  8006. const usedNames = new Set(tunnels.map(t => t.name));
  8007. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  8008. 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++;
  8009. if (index >= 256) index = 0;
  8010. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  8011. document.getElementById('aerotun-modal-id').value = '';
  8012. document.getElementById('aerotun-modal-protocol').value='3';
  8013. document.getElementById('aerotun-modal-public').value='';
  8014. document.getElementById('aerotun-modal-peerkey').value='';
  8015. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  8016. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  8017. document.getElementById('aerotun-modal-mode').value = 'server';
  8018. document.getElementById('aerotun-modal-port').value = 51830 + index;
  8019. document.getElementById('aerotun-modal-endpoint').value = '';
  8020. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  8021. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  8022. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  8023. document.getElementById('aerotun-modal-psk').value = '';
  8024. document.getElementById('aerotun-modal-mtu').value = '1420';
  8025. document.getElementById('aerotun-modal-comment').value = '';
  8026. document.getElementById('aerotun-modal-compression').checked = false;
  8027. document.getElementById('aerotun-modal-defroute').checked = false;
  8028. document.getElementById('aerotun-modal-disabled').checked = true;
  8029. document.getElementById('aerotun-modal-psk').type = 'password';
  8030. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8031. onAeroTUNModeChange();
  8032. updateAeroTUNSetupHint();
  8033. document.getElementById('aerotun-modal').classList.remove('hidden');
  8034. generateAeroTUNKey(true);
  8035. generateAeroTUNIdentity();
  8036. }
  8037. function openEditAeroTUNModal(id) {
  8038. if (aeroSaving) return;
  8039. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8040. if (!t) return;
  8041. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8042. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8043. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8044. document.getElementById('aerotun-modal-id').value = t.id;
  8045. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8046. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8047. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8048. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8049. document.getElementById('aerotun-modal-name').value = t.name;
  8050. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8051. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8052. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8053. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8054. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8055. const peerHost = (t.peer_address || '').split('/')[0];
  8056. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8057. document.getElementById('aerotun-modal-psk').value = '';
  8058. document.getElementById('aerotun-modal-psk').type = 'password';
  8059. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8060. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8061. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8062. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8063. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8064. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8065. onAeroTUNModeChange();
  8066. updateAeroTUNSetupHint();
  8067. document.getElementById('aerotun-modal').classList.remove('hidden');
  8068. }
  8069. function closeAeroTUNModal() {
  8070. if (aeroSaving) return;
  8071. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8072. document.getElementById('aerotun-modal-psk').value = '';
  8073. document.getElementById('aerotun-modal').classList.add('hidden');
  8074. }
  8075. async function submitSaveAeroTUN(e) {
  8076. e.preventDefault();
  8077. if (aeroSaving) return;
  8078. const id = document.getElementById('aerotun-modal-id').value;
  8079. const name = document.getElementById('aerotun-modal-name').value.trim();
  8080. const mode = document.getElementById('aerotun-modal-mode').value;
  8081. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8082. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8083. const local = document.getElementById('aerotun-modal-local').value.trim();
  8084. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8085. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8086. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8087. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8088. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8089. const compression = document.getElementById('aerotun-modal-compression').checked;
  8090. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8091. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8092. if (mode === 'client' && !endpoint) {
  8093. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8094. return;
  8095. }
  8096. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8097. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8098. return;
  8099. }
  8100. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8101. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8102. return;
  8103. }
  8104. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8105. if (version === 3 && !id && !aeroIdentityDraft) {
  8106. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8107. return;
  8108. }
  8109. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8110. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8111. document.getElementById('aerotun-modal-allowed').focus();
  8112. return;
  8113. }
  8114. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8115. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8116. return;
  8117. }
  8118. if (!psk && !id) {
  8119. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8120. return;
  8121. }
  8122. aeroSaving = true;
  8123. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8124. if (submit) submit.disabled = true;
  8125. try {
  8126. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8127. method: 'POST',
  8128. headers: { 'Content-Type': 'application/json' },
  8129. body: JSON.stringify({
  8130. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8131. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8132. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8133. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8134. id,
  8135. name,
  8136. mode,
  8137. listen_port: port,
  8138. remote_endpoint: endpoint,
  8139. local_address: local,
  8140. peer_address: peer,
  8141. psk,
  8142. mtu,
  8143. compression,
  8144. default_route: defaultRoute,
  8145. comment,
  8146. disabled
  8147. })
  8148. });
  8149. if (res.ok) {
  8150. await res.json();
  8151. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8152. aeroIdentityDraft = '';
  8153. aeroSaving = false;
  8154. closeAeroTUNModal();
  8155. await loadAeroTUN(false);
  8156. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8157. fetchData(false);
  8158. } else {
  8159. const err = await responseError(res);
  8160. if (err.includes('configuration saved but tunnel failed to start')) {
  8161. aeroIdentityDraft = '';
  8162. aeroSaving = false;
  8163. closeAeroTUNModal();
  8164. await loadAeroTUN(false);
  8165. showToast('Saved, but not started', err, 'error');
  8166. } else showToast('Error Saving Tunnel', err, 'error');
  8167. }
  8168. } catch (err) {
  8169. showToast('Network Error', err.message, 'error');
  8170. } finally {
  8171. aeroSaving = false;
  8172. if (submit) submit.disabled = false;
  8173. }
  8174. }
  8175. async function startAeroTUNTunnel(id) {
  8176. try {
  8177. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8178. if (res.ok) {
  8179. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8180. loadAeroTUN(false);
  8181. fetchData(false);
  8182. } else {
  8183. const err = await res.text();
  8184. showToast('Failed to Start', err, 'error');
  8185. }
  8186. } catch (err) {
  8187. showToast('Error', err.message, 'error');
  8188. }
  8189. }
  8190. async function stopAeroTUNTunnel(id) {
  8191. try {
  8192. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8193. if (res.ok) {
  8194. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8195. loadAeroTUN(false);
  8196. fetchData(false);
  8197. } else {
  8198. const err = await res.text();
  8199. showToast('Failed to Stop', err, 'error');
  8200. }
  8201. } catch (err) {
  8202. showToast('Error', err.message, 'error');
  8203. }
  8204. }
  8205. async function toggleAeroTUNState(id, disabled) {
  8206. try {
  8207. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8208. method: 'POST',
  8209. headers: { 'Content-Type': 'application/json' },
  8210. body: JSON.stringify({ disabled })
  8211. });
  8212. if (res.ok) {
  8213. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8214. loadAeroTUN(false);
  8215. fetchData(false);
  8216. }
  8217. } catch (err) {
  8218. showToast('Error', err.message, 'error');
  8219. }
  8220. }
  8221. async function deleteAeroTUN(id) {
  8222. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8223. try {
  8224. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8225. if (res.ok) {
  8226. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8227. loadAeroTUN(false);
  8228. fetchData(false);
  8229. }
  8230. } catch (err) {
  8231. showToast('Error', err.message, 'error');
  8232. }
  8233. }
  8234. // ======================== PPP Central Hub & Servers ========================
  8235. function switchPPPSubTab(tab) {
  8236. state.pppSubTab = tab;
  8237. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8238. tabs.forEach(t => {
  8239. const panel = document.getElementById(`ppp-subtab-${t}`);
  8240. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8241. if (panel) {
  8242. if (t === tab) panel.classList.remove('hidden');
  8243. else panel.classList.add('hidden');
  8244. }
  8245. if (btn) {
  8246. if (t === tab) {
  8247. 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';
  8248. } else {
  8249. 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';
  8250. }
  8251. }
  8252. });
  8253. const addBtn = document.getElementById('ppp-primary-add-btn');
  8254. if (addBtn) {
  8255. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8256. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8257. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8258. else addBtn.innerHTML = '<span>Save Config</span>';
  8259. }
  8260. if (tab === 'active') loadPPPSessions();
  8261. }
  8262. function openCurrentPPPModal() {
  8263. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8264. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8265. else if (state.pppSubTab === 'active') loadPPPSessions();
  8266. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8267. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8268. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8269. }
  8270. async function loadPPP(populateDropdowns = true) {
  8271. await Promise.all([
  8272. loadPPPSecrets(),
  8273. loadPPPProfiles(),
  8274. loadPPPServers(),
  8275. loadPPPSessions()
  8276. ]);
  8277. }
  8278. async function loadPPPSecrets() {
  8279. try {
  8280. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8281. const data = await res.json();
  8282. state.pppSecrets = Array.isArray(data) ? data : [];
  8283. const b = document.getElementById('ppp-badge-secrets');
  8284. if (b) b.innerText = state.pppSecrets.length;
  8285. const b2 = document.getElementById('secrets-count-badge');
  8286. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8287. renderPPPSecrets();
  8288. } catch (err) {
  8289. console.error('Failed to load PPP secrets:', err);
  8290. }
  8291. }
  8292. function renderPPPSecrets() {
  8293. const tbody = document.getElementById('secrets-table-body');
  8294. const empty = document.getElementById('secrets-empty');
  8295. if (!tbody) return;
  8296. tbody.innerHTML = '';
  8297. const secrets = state.pppSecrets || [];
  8298. if (secrets.length === 0) {
  8299. empty?.classList.remove('hidden');
  8300. return;
  8301. }
  8302. empty?.classList.add('hidden');
  8303. secrets.forEach(s => {
  8304. const tr = document.createElement('tr');
  8305. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8306. tr.innerHTML = `
  8307. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8308. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8309. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8310. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8311. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8312. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8313. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8314. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8315. <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>
  8316. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8317. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8318. </td>
  8319. `;
  8320. tbody.appendChild(tr);
  8321. });
  8322. }
  8323. async function loadPPPProfiles() {
  8324. try {
  8325. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8326. const data = await res.json();
  8327. state.pppProfiles = Array.isArray(data) ? data : [];
  8328. const b = document.getElementById('ppp-badge-profiles');
  8329. if (b) b.innerText = state.pppProfiles.length;
  8330. const b2 = document.getElementById('profiles-count-badge');
  8331. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8332. // Populate profile selects across modals
  8333. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8334. selects.forEach(sid => {
  8335. const el = document.getElementById(sid);
  8336. if (!el) return;
  8337. const cur = el.value;
  8338. el.innerHTML = '';
  8339. state.pppProfiles.forEach(p => {
  8340. const opt = document.createElement('option');
  8341. opt.value = p.name;
  8342. opt.innerText = `${p.name} (${p.remote_address})`;
  8343. if (p.name === cur) opt.selected = true;
  8344. el.appendChild(opt);
  8345. });
  8346. });
  8347. renderPPPProfiles();
  8348. } catch (err) {
  8349. console.error('Failed to load PPP profiles:', err);
  8350. }
  8351. }
  8352. function renderPPPProfiles() {
  8353. const tbody = document.getElementById('profiles-table-body');
  8354. if (!tbody) return;
  8355. tbody.innerHTML = '';
  8356. (state.pppProfiles || []).forEach(p => {
  8357. const isDefault = p.name.startsWith('default');
  8358. const tr = document.createElement('tr');
  8359. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8360. tr.innerHTML = `
  8361. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8362. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8363. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8364. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8365. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8366. <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>
  8367. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8368. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8369. ${!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>`}
  8370. </td>
  8371. `;
  8372. tbody.appendChild(tr);
  8373. });
  8374. }
  8375. async function loadPPPServers() {
  8376. try {
  8377. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8378. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8379. fetch(`${API_BASE}/vpn/servers/pptp`),
  8380. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8381. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8382. ]);
  8383. if (pppoeRes.ok) {
  8384. state.pppoeServer = await pppoeRes.json();
  8385. const s = state.pppoeServer;
  8386. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8387. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8388. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8389. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8390. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8391. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8392. const pill = document.getElementById('pppoe-server-status-pill');
  8393. if (pill) {
  8394. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8395. 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';
  8396. }
  8397. setDotBadge('ppp-badge-pppoe-state', s.running);
  8398. }
  8399. if (pptpRes.ok) {
  8400. state.pptpServer = await pptpRes.json();
  8401. const s = state.pptpServer;
  8402. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8403. document.getElementById('pptp-server-port').value = s.port || 1723;
  8404. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8405. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8406. const pill = document.getElementById('pptp-server-status-pill');
  8407. if (pill) {
  8408. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8409. 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';
  8410. }
  8411. setDotBadge('ppp-badge-pptp-state', s.running);
  8412. }
  8413. if (l2tpRes.ok) {
  8414. state.l2tpServer = await l2tpRes.json();
  8415. const s = state.l2tpServer;
  8416. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8417. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8418. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8419. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8420. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8421. const pill = document.getElementById('l2tp-server-status-pill');
  8422. if (pill) {
  8423. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8424. 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';
  8425. }
  8426. setDotBadge('ppp-badge-l2tp-state', s.running);
  8427. }
  8428. if (ipsecRes.ok) {
  8429. state.ipsecServer = await ipsecRes.json();
  8430. const s = state.ipsecServer;
  8431. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8432. if (modalEn) modalEn.checked = !!s.enabled;
  8433. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8434. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8435. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8436. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8437. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8438. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8439. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8440. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8441. const pill = document.getElementById('modal-ipsec-server-status');
  8442. if (pill) {
  8443. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8444. 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';
  8445. }
  8446. }
  8447. } catch (err) {
  8448. console.error('Failed to load VPN servers:', err);
  8449. }
  8450. }
  8451. async function loadPPPSessions() {
  8452. try {
  8453. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8454. const data = await res.json();
  8455. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8456. const b = document.getElementById('ppp-badge-active');
  8457. if (b) b.innerText = state.pppActiveSessions.length;
  8458. const sideB = document.getElementById('badge-ppp-sessions');
  8459. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8460. renderPPPSessions();
  8461. } catch (err) {
  8462. console.error('Failed to load active PPP sessions:', err);
  8463. }
  8464. }
  8465. function renderPPPSessions() {
  8466. const tbody = document.getElementById('active-ppp-table-body');
  8467. const empty = document.getElementById('active-ppp-empty');
  8468. if (!tbody) return;
  8469. tbody.innerHTML = '';
  8470. const list = state.pppActiveSessions || [];
  8471. if (list.length === 0) {
  8472. empty?.classList.remove('hidden');
  8473. return;
  8474. }
  8475. empty?.classList.add('hidden');
  8476. list.forEach(s => {
  8477. const tr = document.createElement('tr');
  8478. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8479. tr.innerHTML = `
  8480. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8481. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8482. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8483. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8484. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8485. <td class="py-2.5 px-3 text-[11px]">
  8486. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8487. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8488. </td>
  8489. <td class="py-2.5 px-3 text-right font-sans">
  8490. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8491. </td>
  8492. `;
  8493. tbody.appendChild(tr);
  8494. });
  8495. }
  8496. async function disconnectPPPSession(iface) {
  8497. if (!confirm(`Disconnect session ${iface}?`)) return;
  8498. try {
  8499. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8500. if (res.ok) {
  8501. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8502. loadPPPSessions();
  8503. }
  8504. } catch (err) {
  8505. showToast('Error', err.message, 'error');
  8506. }
  8507. }
  8508. // PPP Secret Modal handlers
  8509. function openAddPPPSecretModal() {
  8510. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8511. document.getElementById('secret-modal-id').value = '';
  8512. document.getElementById('secret-modal-name').value = '';
  8513. document.getElementById('secret-modal-password').value = '';
  8514. document.getElementById('secret-modal-service').value = 'any';
  8515. document.getElementById('secret-modal-profile').value = 'default';
  8516. document.getElementById('secret-modal-local').value = '';
  8517. document.getElementById('secret-modal-remote').value = '';
  8518. document.getElementById('secret-modal-comment').value = '';
  8519. document.getElementById('secret-modal-disabled').checked = false;
  8520. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8521. }
  8522. function openEditPPPSecretModal(id) {
  8523. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8524. if (!s) return;
  8525. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8526. document.getElementById('secret-modal-id').value = s.id;
  8527. document.getElementById('secret-modal-name').value = s.name;
  8528. document.getElementById('secret-modal-password').value = s.password;
  8529. document.getElementById('secret-modal-service').value = s.service || 'any';
  8530. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8531. document.getElementById('secret-modal-local').value = s.local_address || '';
  8532. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8533. document.getElementById('secret-modal-comment').value = s.comment || '';
  8534. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8535. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8536. }
  8537. function closePPPSecretModal() {
  8538. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8539. }
  8540. async function submitSavePPPSecret(e) {
  8541. e.preventDefault();
  8542. const id = document.getElementById('secret-modal-id').value;
  8543. const name = document.getElementById('secret-modal-name').value.trim();
  8544. const password = document.getElementById('secret-modal-password').value.trim();
  8545. const service = document.getElementById('secret-modal-service').value;
  8546. const profile = document.getElementById('secret-modal-profile').value;
  8547. const local = document.getElementById('secret-modal-local').value.trim();
  8548. const remote = document.getElementById('secret-modal-remote').value.trim();
  8549. const comment = document.getElementById('secret-modal-comment').value.trim();
  8550. const disabled = document.getElementById('secret-modal-disabled').checked;
  8551. try {
  8552. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8553. method: 'POST',
  8554. headers: { 'Content-Type': 'application/json' },
  8555. body: JSON.stringify({
  8556. id,
  8557. name,
  8558. password,
  8559. service,
  8560. profile,
  8561. local_address: local,
  8562. remote_address: remote,
  8563. comment,
  8564. disabled
  8565. })
  8566. });
  8567. if (res.ok) {
  8568. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8569. closePPPSecretModal();
  8570. loadPPPSecrets();
  8571. } else {
  8572. const err = await res.json();
  8573. showToast('Error', err.message, 'error');
  8574. }
  8575. } catch (err) {
  8576. showToast('Error', err.message, 'error');
  8577. }
  8578. }
  8579. async function togglePPPSecretState(id, disabled) {
  8580. try {
  8581. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8582. method: 'POST',
  8583. headers: { 'Content-Type': 'application/json' },
  8584. body: JSON.stringify({ disabled })
  8585. });
  8586. if (res.ok) {
  8587. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8588. loadPPPSecrets();
  8589. }
  8590. } catch (err) {
  8591. showToast('Error', err.message, 'error');
  8592. }
  8593. }
  8594. async function deletePPPSecret(id) {
  8595. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8596. try {
  8597. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8598. if (res.ok) {
  8599. showToast('Deleted', 'Secret account removed', 'success');
  8600. loadPPPSecrets();
  8601. }
  8602. } catch (err) {
  8603. showToast('Error', err.message, 'error');
  8604. }
  8605. }
  8606. // PPP Profile Modal handlers
  8607. function openAddPPPProfileModal() {
  8608. document.getElementById('profile-modal-name').value = '';
  8609. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8610. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8611. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8612. document.getElementById('profile-modal-encryption').value = 'required';
  8613. document.getElementById('profile-modal-onlyone').checked = true;
  8614. document.getElementById('profile-modal-comment').value = '';
  8615. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8616. }
  8617. function closePPPProfileModal() {
  8618. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8619. }
  8620. async function submitSavePPPProfile(e) {
  8621. e.preventDefault();
  8622. const name = document.getElementById('profile-modal-name').value.trim();
  8623. const local = document.getElementById('profile-modal-local').value.trim();
  8624. const remote = document.getElementById('profile-modal-remote').value.trim();
  8625. const dns = document.getElementById('profile-modal-dns').value.trim();
  8626. const enc = document.getElementById('profile-modal-encryption').value;
  8627. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8628. const comment = document.getElementById('profile-modal-comment').value.trim();
  8629. try {
  8630. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8631. method: 'POST',
  8632. headers: { 'Content-Type': 'application/json' },
  8633. body: JSON.stringify({
  8634. id: name,
  8635. name,
  8636. local_address: local,
  8637. remote_address: remote,
  8638. dns_servers: dns,
  8639. use_encryption: enc,
  8640. only_one: onlyone,
  8641. comment
  8642. })
  8643. });
  8644. if (res.ok) {
  8645. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8646. closePPPProfileModal();
  8647. loadPPPProfiles();
  8648. } else {
  8649. const err = await res.json();
  8650. showToast('Error', err.message, 'error');
  8651. }
  8652. } catch (err) {
  8653. showToast('Error', err.message, 'error');
  8654. }
  8655. }
  8656. async function deletePPPProfile(name) {
  8657. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8658. try {
  8659. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8660. if (res.ok) {
  8661. showToast('Deleted', 'Profile removed', 'success');
  8662. loadPPPProfiles();
  8663. } else {
  8664. const err = await res.json();
  8665. showToast('Error', err.message, 'error');
  8666. }
  8667. } catch (err) {
  8668. showToast('Error', err.message, 'error');
  8669. }
  8670. }
  8671. // Server Config submissions
  8672. async function savePPPoEServerConfig(e) {
  8673. e.preventDefault();
  8674. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8675. const name = document.getElementById('pppoe-server-name').value.trim();
  8676. const iface = document.getElementById('pppoe-server-iface').value;
  8677. const profile = document.getElementById('pppoe-server-profile').value;
  8678. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8679. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8680. try {
  8681. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8682. method: 'POST',
  8683. headers: { 'Content-Type': 'application/json' },
  8684. body: JSON.stringify({
  8685. enabled,
  8686. service_name: name,
  8687. interface: iface,
  8688. default_profile: profile,
  8689. max_mtu: mtu,
  8690. max_mru: mtu,
  8691. one_session_per_host: onesession
  8692. })
  8693. });
  8694. if (res.ok) {
  8695. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8696. loadPPPServers();
  8697. fetchData(false);
  8698. } else {
  8699. const err = await res.json();
  8700. showToast('Error', err.message, 'error');
  8701. }
  8702. } catch (err) {
  8703. showToast('Error', err.message, 'error');
  8704. }
  8705. }
  8706. async function savePPTPServerConfig(e) {
  8707. e.preventDefault();
  8708. const enabled = document.getElementById('pptp-server-enabled').checked;
  8709. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8710. const profile = document.getElementById('pptp-server-profile').value;
  8711. const mppe = document.getElementById('pptp-server-mppe').checked;
  8712. try {
  8713. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8714. method: 'POST',
  8715. headers: { 'Content-Type': 'application/json' },
  8716. body: JSON.stringify({
  8717. enabled,
  8718. port,
  8719. default_profile: profile,
  8720. require_mppe: mppe
  8721. })
  8722. });
  8723. if (res.ok) {
  8724. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8725. loadPPPServers();
  8726. fetchData(false);
  8727. } else {
  8728. const err = await res.json();
  8729. showToast('Error', err.message, 'error');
  8730. }
  8731. } catch (err) {
  8732. showToast('Error', err.message, 'error');
  8733. }
  8734. }
  8735. async function saveL2TPServerConfig(e) {
  8736. e.preventDefault();
  8737. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8738. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8739. const profile = document.getElementById('l2tp-server-profile').value;
  8740. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8741. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8742. try {
  8743. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8744. method: 'POST',
  8745. headers: { 'Content-Type': 'application/json' },
  8746. body: JSON.stringify({
  8747. enabled,
  8748. port,
  8749. default_profile: profile,
  8750. use_ipsec: useipsec,
  8751. ipsec_secret: psk
  8752. })
  8753. });
  8754. if (res.ok) {
  8755. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8756. loadPPPServers();
  8757. fetchData(false);
  8758. } else {
  8759. const err = await res.json();
  8760. showToast('Error', err.message, 'error');
  8761. }
  8762. } catch (err) {
  8763. showToast('Error', err.message, 'error');
  8764. }
  8765. }
  8766. // IPSec Server Modal
  8767. function openIPSecServerModal() {
  8768. loadPPPServers();
  8769. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8770. }
  8771. function closeIPSecServerModal() {
  8772. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8773. }
  8774. async function submitSaveIPSecServer(e) {
  8775. e.preventDefault();
  8776. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8777. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8778. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8779. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8780. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8781. try {
  8782. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8783. method: 'POST',
  8784. headers: { 'Content-Type': 'application/json' },
  8785. body: JSON.stringify({
  8786. enabled,
  8787. preshared_key: psk,
  8788. pool_address: pool,
  8789. dns_servers: dns,
  8790. local_subnet: subnet
  8791. })
  8792. });
  8793. if (res.ok) {
  8794. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8795. closeIPSecServerModal();
  8796. loadPPPServers();
  8797. fetchData(false);
  8798. } else {
  8799. const err = await res.json();
  8800. showToast('Error', err.message, 'error');
  8801. }
  8802. } catch (err) {
  8803. showToast('Error', err.message, 'error');
  8804. }
  8805. }
  8806. // WireGuard Client Config Viewer
  8807. let currentWGClientConf = '';
  8808. async function openWGClientConfModal(iface, clientIP) {
  8809. try {
  8810. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8811. method: 'POST',
  8812. headers: { 'Content-Type': 'application/json' },
  8813. body: JSON.stringify({
  8814. interface: iface,
  8815. address: clientIP || '10.10.0.2/32',
  8816. dns: '1.1.1.1, 8.8.8.8'
  8817. })
  8818. });
  8819. if (res.ok) {
  8820. const data = await res.json();
  8821. currentWGClientConf = data.config;
  8822. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8823. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8824. } else {
  8825. const err = await res.json();
  8826. showToast('Error', err.message, 'error');
  8827. }
  8828. } catch (err) {
  8829. showToast('Error', err.message, 'error');
  8830. }
  8831. }
  8832. function closeWGClientConfModal() {
  8833. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8834. }
  8835. function copyWGClientConf() {
  8836. if (!currentWGClientConf) return;
  8837. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8838. }
  8839. function downloadWGClientConf() {
  8840. if (!currentWGClientConf) return;
  8841. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8842. const a = document.createElement('a');
  8843. a.href = URL.createObjectURL(blob);
  8844. a.download = 'wireguard-client.conf';
  8845. document.body.appendChild(a);
  8846. a.click();
  8847. document.body.removeChild(a);
  8848. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8849. }
  8850. // =========================================================================
  8851. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8852. // =========================================================================
  8853. state.activeDynSubTab = 'bgp-peers';
  8854. state.activeBgpSubTab = 'bgp-peers';
  8855. state.activeOspfTab = 'instances';
  8856. state.bgpInstance = null;
  8857. state.bgpPeers = [];
  8858. state.bgpNets = [];
  8859. state.bgpRoutes = [];
  8860. state.ospfInstance = null;
  8861. state.ospfInstances = [];
  8862. state.ospfAreas = [];
  8863. state.ospfAreaRanges = [];
  8864. state.ospfTemplates = [];
  8865. state.ospfLiveInterfaces = [];
  8866. state.ospfStaticNbrs = [];
  8867. state.ospfNeighbors = [];
  8868. state.ospfLSA = [];
  8869. state.ospfRoutes = [];
  8870. state.selectedOspfRow = {
  8871. instances: null,
  8872. areas: null,
  8873. 'area-ranges': null,
  8874. templates: null,
  8875. interfaces: null,
  8876. 'static-nbrs': null,
  8877. neighbors: null,
  8878. lsa: null,
  8879. };
  8880. state.ospfSort = {
  8881. instances: { col: 'name', asc: true },
  8882. areas: { col: 'name', asc: true },
  8883. ranges: { col: 'area', asc: true },
  8884. templates: { col: 'interfaces', asc: true },
  8885. live_ifaces: { col: 'interface', asc: true },
  8886. snbrs: { col: 'address', asc: true },
  8887. neighbors: { col: 'address', asc: true },
  8888. lsa: { col: 'instance', asc: true },
  8889. };
  8890. function switchBgpSubTab(subTab) {
  8891. state.activeBgpSubTab = subTab;
  8892. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8893. tabs.forEach(t => {
  8894. const el = document.getElementById(`dyn-subtab-${t}`);
  8895. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8896. if (el) el.classList.toggle('hidden', t !== subTab);
  8897. if (btn) {
  8898. if (t === subTab) {
  8899. 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';
  8900. } else {
  8901. 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';
  8902. }
  8903. }
  8904. });
  8905. }
  8906. function switchOspfTab(tabName) {
  8907. state.activeOspfTab = tabName;
  8908. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8909. tabs.forEach(t => {
  8910. const pane = document.getElementById(`ospf-pane-${t}`);
  8911. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8912. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8913. if (btn) {
  8914. if (t === tabName) {
  8915. 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';
  8916. } else {
  8917. 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';
  8918. }
  8919. }
  8920. });
  8921. }
  8922. function switchOspfSubTab(tab) {
  8923. // Legacy alias
  8924. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8925. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8926. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8927. else switchOspfTab('instances');
  8928. }
  8929. function switchDynSubTab(subTab) {
  8930. if (subTab.startsWith('bgp')) {
  8931. if (state.activeTab !== 'bgp') navigate('bgp');
  8932. switchBgpSubTab(subTab);
  8933. } else if (subTab.startsWith('ospf')) {
  8934. if (state.activeTab !== 'ospf') navigate('ospf');
  8935. switchOspfTab('instances');
  8936. }
  8937. }
  8938. async function loadDynamicRouting(showToastMsg = false) {
  8939. try {
  8940. const fetchSafeJson = async (url) => {
  8941. try {
  8942. const r = await fetch(url);
  8943. return r.ok ? await r.json() : null;
  8944. } catch (e) {
  8945. return null;
  8946. }
  8947. };
  8948. const [
  8949. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8950. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8951. commLists, asLists,
  8952. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  8953. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  8954. babelInsts, babelIfaces, babelLiveIfaces, babelNbrs, babelRoutes,
  8955. radvInsts, radvIfaces,
  8956. eigrpInsts, eigrpIfaces, eigrpNets, eigrpNbrs, eigrpTopology
  8957. ] = await Promise.all([
  8958. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8959. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8960. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8961. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8962. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8963. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8964. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8965. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8966. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8967. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8968. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8969. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8970. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8971. fetchSafeJson(`${API_BASE}/routing/filters`),
  8972. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8973. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`),
  8974. fetchSafeJson(`${API_BASE}/routing/rip/instances`),
  8975. fetchSafeJson(`${API_BASE}/routing/rip/interfaces`),
  8976. fetchSafeJson(`${API_BASE}/routing/rip/neighbors-live`),
  8977. fetchSafeJson(`${API_BASE}/routing/rip/routes`),
  8978. fetchSafeJson(`${API_BASE}/routing/bfd/instance`),
  8979. fetchSafeJson(`${API_BASE}/routing/bfd/interfaces`),
  8980. fetchSafeJson(`${API_BASE}/routing/bfd/peers`),
  8981. fetchSafeJson(`${API_BASE}/routing/bfd/sessions`),
  8982. fetchSafeJson(`${API_BASE}/routing/babel/instances`),
  8983. fetchSafeJson(`${API_BASE}/routing/babel/interfaces`),
  8984. fetchSafeJson(`${API_BASE}/routing/babel/interfaces-live`),
  8985. fetchSafeJson(`${API_BASE}/routing/babel/neighbors`),
  8986. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  8987. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  8988. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`),
  8989. fetchSafeJson(`${API_BASE}/routing/eigrp/instances`),
  8990. fetchSafeJson(`${API_BASE}/routing/eigrp/interfaces`),
  8991. fetchSafeJson(`${API_BASE}/routing/eigrp/networks`),
  8992. fetchSafeJson(`${API_BASE}/routing/eigrp/neighbors`),
  8993. fetchSafeJson(`${API_BASE}/routing/eigrp/topology`)
  8994. ]);
  8995. if (sum) state.dynSummary = sum;
  8996. if (bgpInst) state.bgpInstance = bgpInst;
  8997. if (bgpPeers) state.bgpPeers = bgpPeers;
  8998. if (bgpNets) state.bgpNets = bgpNets;
  8999. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  9000. if (ospfInsts) state.ospfInstances = ospfInsts;
  9001. if (ospfAreas) state.ospfAreas = ospfAreas;
  9002. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  9003. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  9004. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  9005. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  9006. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  9007. if (ospfLsa) state.ospfLSA = ospfLsa;
  9008. if (filters) state.routingFilters = filters;
  9009. if (commLists) state.routingCommunityLists = commLists;
  9010. if (asLists) state.routingASLists = asLists;
  9011. if (ripInsts) state.ripInstances = ripInsts;
  9012. if (ripIfaces) state.ripInterfaces = ripIfaces;
  9013. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  9014. if (ripRoutes) state.ripRoutes = ripRoutes;
  9015. if (bfdInst) state.bfdInstance = bfdInst;
  9016. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  9017. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  9018. if (bfdSessions) state.bfdSessions = bfdSessions;
  9019. if (babelInsts) state.babelInstances = babelInsts;
  9020. if (babelIfaces) state.babelInterfaces = babelIfaces;
  9021. if (babelLiveIfaces) state.babelInterfacesLive = babelLiveIfaces;
  9022. if (babelNbrs) state.babelNeighbors = babelNbrs;
  9023. if (babelRoutes) state.babelRoutes = babelRoutes;
  9024. if (radvInsts) state.radvInstances = radvInsts;
  9025. if (radvIfaces) state.radvInterfaces = radvIfaces;
  9026. if (eigrpInsts) state.eigrpInstances = eigrpInsts;
  9027. if (eigrpIfaces) state.eigrpInterfaces = eigrpIfaces;
  9028. if (eigrpNets) state.eigrpNetworks = eigrpNets;
  9029. if (eigrpNbrs) state.eigrpNeighbors = eigrpNbrs;
  9030. if (eigrpTopology) state.eigrpTopology = eigrpTopology;
  9031. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  9032. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  9033. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  9034. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  9035. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  9036. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  9037. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  9038. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  9039. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  9040. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9041. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9042. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9043. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9044. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9045. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9046. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9047. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9048. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9049. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9050. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9051. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9052. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9053. try { renderBabelLiveInterfaces(); } catch(e) { console.error('renderBabelLiveInterfaces error:', e); }
  9054. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9055. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9056. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9057. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9058. try { renderEigrpInstances(); } catch(e) { console.error('renderEigrpInstances error:', e); }
  9059. try { renderEigrpNetworks(); } catch(e) { console.error('renderEigrpNetworks error:', e); }
  9060. try { renderEigrpInterfaces(); } catch(e) { console.error('renderEigrpInterfaces error:', e); }
  9061. try { renderEigrpNeighbors(); } catch(e) { console.error('renderEigrpNeighbors error:', e); }
  9062. try { renderEigrpTopology(); } catch(e) { console.error('renderEigrpTopology error:', e); }
  9063. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9064. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9065. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9066. } catch (err) {
  9067. console.error('Failed to load dynamic routing:', err);
  9068. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9069. }
  9070. }
  9071. async function loadOspfAll() {
  9072. await loadDynamicRouting(true);
  9073. }
  9074. function renderBgpStatusPill() {
  9075. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9076. pills.forEach(pill => {
  9077. const inst = state.bgpInstance;
  9078. if (!inst || !inst.enabled) {
  9079. 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';
  9080. pill.innerText = 'BGP DISABLED';
  9081. } else if (inst.running) {
  9082. 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';
  9083. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9084. } else {
  9085. 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';
  9086. pill.innerText = 'BGP STARTING...';
  9087. }
  9088. });
  9089. }
  9090. function renderBgpPeers() {
  9091. const tbody = document.getElementById('bgp-peers-table-body');
  9092. if (!tbody) return;
  9093. const empty = document.getElementById('bgp-peers-empty');
  9094. const countBadge = document.getElementById('bgp-peers-count-badge');
  9095. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9096. const peers = state.bgpPeers || [];
  9097. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9098. if (navBadge) navBadge.innerText = peers.length;
  9099. if (peers.length === 0) {
  9100. tbody.innerHTML = '';
  9101. if (empty) empty.classList.remove('hidden');
  9102. return;
  9103. }
  9104. if (empty) empty.classList.add('hidden');
  9105. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9106. if (tbody.dataset.sig === sig) return;
  9107. tbody.dataset.sig = sig;
  9108. tbody.innerHTML = peers.map(p => {
  9109. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9110. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9111. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9112. let stateBadge = '';
  9113. if (p.disabled) {
  9114. 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>';
  9115. } else if (p.state === 'Established') {
  9116. 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>';
  9117. } else if (p.state === 'Connect' || p.state === 'Active') {
  9118. 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>`;
  9119. } else {
  9120. 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>`;
  9121. }
  9122. return `
  9123. <tr class="hover:bg-slate-800/40 transition">
  9124. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9125. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9126. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9127. <td class="py-2.5 px-3">
  9128. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9129. ${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>`}
  9130. </td>
  9131. <td class="py-2.5 px-3">${stateBadge}</td>
  9132. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9133. <td class="py-2.5 px-3 text-slate-300">
  9134. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9135. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9136. </td>
  9137. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9138. ${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> ` : ''}
  9139. ${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>` : ''}
  9140. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9141. </td>
  9142. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9143. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9144. <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'}">
  9145. ${p.disabled ? 'Enable' : 'Disable'}
  9146. </button>
  9147. <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">
  9148. Edit
  9149. </button>
  9150. <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">
  9151. Delete
  9152. </button>
  9153. </td>
  9154. </tr>
  9155. `;
  9156. }).join('');
  9157. }
  9158. function renderBgpNetworks() {
  9159. const tbody = document.getElementById('bgp-nets-table-body');
  9160. if (!tbody) return;
  9161. const empty = document.getElementById('bgp-nets-empty');
  9162. const countBadge = document.getElementById('bgp-nets-count-badge');
  9163. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9164. const nets = state.bgpNets || [];
  9165. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9166. if (navBadge) navBadge.innerText = nets.length;
  9167. if (nets.length === 0) {
  9168. tbody.innerHTML = '';
  9169. if (empty) empty.classList.remove('hidden');
  9170. return;
  9171. }
  9172. if (empty) empty.classList.add('hidden');
  9173. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9174. if (tbody.dataset.sig === sig) return;
  9175. tbody.dataset.sig = sig;
  9176. tbody.innerHTML = nets.map(n => `
  9177. <tr class="hover:bg-slate-800/40 transition">
  9178. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9179. <td class="py-2.5 px-3">
  9180. ${n.disabled
  9181. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9182. : '<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>'}
  9183. </td>
  9184. <td class="py-2.5 px-3">
  9185. ${n.disabled
  9186. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9187. : '<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>'}
  9188. </td>
  9189. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9190. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9191. <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">
  9192. Delete
  9193. </button>
  9194. </td>
  9195. </tr>
  9196. `).join('');
  9197. }
  9198. function renderBgpRoutes() {
  9199. const tbody = document.getElementById('bgp-routes-table-body');
  9200. if (!tbody) return;
  9201. const empty = document.getElementById('bgp-routes-empty');
  9202. const countBadge = document.getElementById('bgp-routes-count-badge');
  9203. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9204. const routes = state.bgpRoutes || [];
  9205. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9206. if (navBadge) navBadge.innerText = routes.length;
  9207. if (routes.length === 0) {
  9208. tbody.innerHTML = '';
  9209. if (empty) empty.classList.remove('hidden');
  9210. return;
  9211. }
  9212. if (empty) empty.classList.add('hidden');
  9213. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9214. if (tbody.dataset.sig === sig) return;
  9215. tbody.dataset.sig = sig;
  9216. tbody.innerHTML = routes.map(r => `
  9217. <tr class="hover:bg-slate-800/40 transition">
  9218. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9219. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9220. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9221. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9222. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9223. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9224. </tr>
  9225. `).join('');
  9226. }
  9227. // =========================================================================
  9228. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9229. // =========================================================================
  9230. function sortOspfTable(tab, col) {
  9231. if (!state.ospfSort) state.ospfSort = {};
  9232. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9233. if (state.ospfSort[tab].col === col) {
  9234. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9235. } else {
  9236. state.ospfSort[tab].col = col;
  9237. state.ospfSort[tab].asc = true;
  9238. }
  9239. const asc = state.ospfSort[tab].asc;
  9240. let list = [];
  9241. if (tab === 'instances') list = state.ospfInstances || [];
  9242. else if (tab === 'areas') list = state.ospfAreas || [];
  9243. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9244. else if (tab === 'templates') list = state.ospfTemplates || [];
  9245. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9246. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9247. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9248. else if (tab === 'lsa') list = state.ospfLSA || [];
  9249. list.sort((a, b) => {
  9250. let valA = a[col] ?? '';
  9251. let valB = b[col] ?? '';
  9252. if (typeof valA === 'number' && typeof valB === 'number') {
  9253. return asc ? valA - valB : valB - valA;
  9254. }
  9255. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9256. });
  9257. if (tab === 'instances') renderOspfInstances();
  9258. else if (tab === 'areas') renderOspfAreas();
  9259. else if (tab === 'ranges') renderOspfAreaRanges();
  9260. else if (tab === 'templates') renderOspfTemplates();
  9261. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9262. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9263. else if (tab === 'neighbors') renderOspfNeighbors();
  9264. else if (tab === 'lsa') renderOspfLSA();
  9265. }
  9266. function selectOspfRow(tab, id) {
  9267. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9268. state.selectedOspfRow[tab] = id;
  9269. if (tab === 'instances') {
  9270. renderOspfInstances();
  9271. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9272. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9273. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9274. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9275. if (btnEn) btnEn.disabled = false;
  9276. if (btnDis) btnDis.disabled = false;
  9277. if (btnRem) btnRem.disabled = false;
  9278. if (btnCom) btnCom.disabled = false;
  9279. } else if (tab === 'areas') {
  9280. renderOspfAreas();
  9281. const btnEn = document.getElementById('btn-ospf-area-enable');
  9282. const btnDis = document.getElementById('btn-ospf-area-disable');
  9283. const btnRem = document.getElementById('btn-ospf-area-remove');
  9284. const btnCom = document.getElementById('btn-ospf-area-comment');
  9285. if (btnEn) btnEn.disabled = false;
  9286. if (btnDis) btnDis.disabled = false;
  9287. if (btnRem) btnRem.disabled = false;
  9288. if (btnCom) btnCom.disabled = false;
  9289. } else if (tab === 'ranges') {
  9290. renderOspfAreaRanges();
  9291. const btnEn = document.getElementById('btn-ospf-range-enable');
  9292. const btnDis = document.getElementById('btn-ospf-range-disable');
  9293. const btnRem = document.getElementById('btn-ospf-range-remove');
  9294. const btnCom = document.getElementById('btn-ospf-range-comment');
  9295. if (btnEn) btnEn.disabled = false;
  9296. if (btnDis) btnDis.disabled = false;
  9297. if (btnRem) btnRem.disabled = false;
  9298. if (btnCom) btnCom.disabled = false;
  9299. } else if (tab === 'templates') {
  9300. renderOspfTemplates();
  9301. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9302. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9303. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9304. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9305. if (btnEn) btnEn.disabled = false;
  9306. if (btnDis) btnDis.disabled = false;
  9307. if (btnRem) btnRem.disabled = false;
  9308. if (btnCom) btnCom.disabled = false;
  9309. } else if (tab === 'snbrs') {
  9310. renderOspfStaticNbrs();
  9311. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9312. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9313. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9314. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9315. if (btnEn) btnEn.disabled = false;
  9316. if (btnDis) btnDis.disabled = false;
  9317. if (btnRem) btnRem.disabled = false;
  9318. if (btnCom) btnCom.disabled = false;
  9319. }
  9320. }
  9321. // TAB 1: INSTANCES
  9322. function renderOspfInstances() {
  9323. const tbody = document.getElementById('ospf-instances-table-body');
  9324. if (!tbody) return;
  9325. const countEl = document.getElementById('ospf-instances-footer-count');
  9326. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9327. let list = state.ospfInstances || [];
  9328. if (filter) {
  9329. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9330. }
  9331. if (countEl) countEl.innerText = list.length;
  9332. const selId = state.selectedOspfRow?.instances;
  9333. tbody.innerHTML = list.map((inst, idx) => {
  9334. const isSel = inst.id === selId;
  9335. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9336. const flagD = inst.disabled
  9337. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  9338. : (inst.running
  9339. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  9340. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  9341. const redist = [];
  9342. if (inst.redistribute_connected) redist.push('conn');
  9343. if (inst.redistribute_static) redist.push('static');
  9344. if (inst.redistribute_bgp) redist.push('bgp');
  9345. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9346. redist.push('default');
  9347. }
  9348. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9349. const origBadge = origDef === 'always'
  9350. ? '<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>'
  9351. : (origDef === 'if-installed'
  9352. ? '<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>'
  9353. : '<span class="text-slate-500 text-[10px]">never</span>');
  9354. return `
  9355. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9356. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9357. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  9358. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9359. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9360. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9361. </td>
  9362. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9363. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9364. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9365. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9366. <td class="py-1.5 px-3">${origBadge}</td>
  9367. </tr>
  9368. `;
  9369. }).join('');
  9370. }
  9371. // TAB 2: AREAS
  9372. function renderOspfAreas() {
  9373. const tbody = document.getElementById('ospf-areas-table-body');
  9374. if (!tbody) return;
  9375. const countEl = document.getElementById('ospf-areas-footer-count');
  9376. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9377. let list = state.ospfAreas || [];
  9378. if (filter) {
  9379. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9380. }
  9381. if (countEl) countEl.innerText = list.length;
  9382. const selId = state.selectedOspfRow?.areas;
  9383. tbody.innerHTML = list.map((a, idx) => {
  9384. const isSel = a.id === selId;
  9385. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9386. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9387. return `
  9388. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9389. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9390. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9391. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9392. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9393. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9394. </td>
  9395. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9396. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9397. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9398. </tr>
  9399. `;
  9400. }).join('');
  9401. }
  9402. // TAB 3: AREA RANGES
  9403. function renderOspfAreaRanges() {
  9404. const tbody = document.getElementById('ospf-ranges-table-body');
  9405. if (!tbody) return;
  9406. const countEl = document.getElementById('ospf-ranges-footer-count');
  9407. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9408. let list = state.ospfAreaRanges || [];
  9409. if (filter) {
  9410. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9411. }
  9412. if (countEl) countEl.innerText = list.length;
  9413. const selId = state.selectedOspfRow?.['area-ranges'];
  9414. tbody.innerHTML = list.map((r, idx) => {
  9415. const isSel = r.id === selId;
  9416. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9417. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9418. return `
  9419. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9420. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9421. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9422. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9423. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9424. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9425. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9426. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9427. </tr>
  9428. `;
  9429. }).join('');
  9430. }
  9431. // TAB 4: INTERFACE TEMPLATES
  9432. function renderOspfTemplates() {
  9433. const tbody = document.getElementById('ospf-templates-table-body');
  9434. if (!tbody) return;
  9435. const countEl = document.getElementById('ospf-templates-footer-count');
  9436. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9437. let list = state.ospfTemplates || [];
  9438. if (filter) {
  9439. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9440. }
  9441. if (countEl) countEl.innerText = list.length;
  9442. const selId = state.selectedOspfRow?.templates;
  9443. tbody.innerHTML = list.map((t, idx) => {
  9444. const isSel = t.id === selId;
  9445. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9446. const ifaces = t.interfaces || t.interface || 'all';
  9447. const nets = t.networks || t.network || '';
  9448. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9449. return `
  9450. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9451. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9452. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9453. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9454. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9455. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9456. </td>
  9457. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9458. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9459. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9460. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9461. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9462. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9463. </tr>
  9464. `;
  9465. }).join('');
  9466. }
  9467. // TAB 5: LIVE INTERFACES
  9468. function renderOspfLiveInterfaces() {
  9469. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9470. if (!tbody) return;
  9471. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9472. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9473. let list = state.ospfLiveInterfaces || [];
  9474. if (filter) {
  9475. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9476. }
  9477. if (countEl) countEl.innerText = list.length;
  9478. tbody.innerHTML = list.map(i => `
  9479. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9480. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9481. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9482. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9483. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9484. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9485. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9486. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9487. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9488. </tr>
  9489. `).join('');
  9490. }
  9491. // TAB 6: STATIC NEIGHBORS
  9492. function renderOspfStaticNbrs() {
  9493. const tbody = document.getElementById('ospf-snbrs-table-body');
  9494. if (!tbody) return;
  9495. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9496. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9497. let list = state.ospfStaticNbrs || [];
  9498. if (filter) {
  9499. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9500. }
  9501. if (countEl) countEl.innerText = list.length;
  9502. const selId = state.selectedOspfRow?.['static-nbrs'];
  9503. tbody.innerHTML = list.map((n, idx) => {
  9504. const isSel = n.id === selId;
  9505. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9506. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9507. return `
  9508. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9509. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9510. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9511. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9512. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9513. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9514. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9515. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9516. </tr>
  9517. `;
  9518. }).join('');
  9519. }
  9520. // TAB 7: LIVE NEIGHBORS
  9521. function renderOspfNeighbors() {
  9522. const tbody = document.getElementById('ospf-neighbors-table-body');
  9523. if (!tbody) return;
  9524. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9525. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9526. let list = state.ospfNeighbors || [];
  9527. if (filter) {
  9528. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9529. }
  9530. if (countEl) countEl.innerText = list.length;
  9531. tbody.innerHTML = list.map(n => `
  9532. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9533. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9534. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9535. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9536. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9537. </td>
  9538. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9539. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9540. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9541. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9542. </tr>
  9543. `).join('');
  9544. }
  9545. // TAB 8: LINK-STATE DATABASE (LSA)
  9546. function renderOspfLSA() {
  9547. const tbody = document.getElementById('ospf-lsa-table-body');
  9548. if (!tbody) return;
  9549. const countEl = document.getElementById('ospf-lsa-footer-count');
  9550. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9551. let list = state.ospfLSA || [];
  9552. if (filter) {
  9553. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9554. }
  9555. if (countEl) countEl.innerText = list.length;
  9556. tbody.innerHTML = list.map(l => `
  9557. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9558. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9559. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9560. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9561. </td>
  9562. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9563. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9564. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9565. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9566. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9567. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9568. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9569. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9570. </tr>
  9571. `).join('');
  9572. }
  9573. function renderOspfStatusPill() {
  9574. // Maintained for backward compatibility
  9575. const pill = document.getElementById('ospf-live-status-pill');
  9576. if (!pill) return;
  9577. 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';
  9578. pill.innerText = 'OSPF ACTIVE';
  9579. }
  9580. function renderOspfInterfaces() {
  9581. renderOspfTemplates();
  9582. }
  9583. function renderOspfRoutes() {
  9584. // Routes retained in background
  9585. }
  9586. // BGP Modals & Actions
  9587. function openBgpInstanceModal() {
  9588. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9589. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9590. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9591. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9592. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9593. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9594. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9595. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9596. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9597. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9598. }
  9599. function closeBgpInstanceModal() {
  9600. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9601. }
  9602. async function submitBgpInstance(e) {
  9603. e.preventDefault();
  9604. const payload = {
  9605. enabled: document.getElementById('modal-bgp-enabled').checked,
  9606. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9607. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9608. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9609. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9610. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9611. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9612. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9613. };
  9614. try {
  9615. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9616. method: 'POST',
  9617. headers: { 'Content-Type': 'application/json' },
  9618. body: JSON.stringify(payload)
  9619. });
  9620. if (res.ok) {
  9621. closeBgpInstanceModal();
  9622. showToast('Success', 'BGP instance configuration updated', 'success');
  9623. loadDynamicRouting();
  9624. } else {
  9625. const err = await res.json();
  9626. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9627. }
  9628. } catch (err) {
  9629. showToast('Error', err.message, 'error');
  9630. }
  9631. }
  9632. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9633. function switchBgpPeerModalTab(tab) {
  9634. // Normalize legacy tab names
  9635. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9636. if (tab === 'attributes') tab = 'networks';
  9637. const tabs = ['general', 'filters', 'networks'];
  9638. tabs.forEach(t => {
  9639. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9640. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9641. if (t === tab) {
  9642. if (pane) pane.classList.remove('hidden');
  9643. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9644. } else {
  9645. if (pane) pane.classList.add('hidden');
  9646. 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';
  9647. }
  9648. });
  9649. }
  9650. function addOutputNetworkRow(val = '') {
  9651. const container = document.getElementById('modal-bgp-output-networks-container');
  9652. if (!container) return;
  9653. const row = document.createElement('div');
  9654. row.className = 'flex items-center gap-2 output-net-row';
  9655. row.innerHTML = `
  9656. <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">
  9657. <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>
  9658. `;
  9659. container.appendChild(row);
  9660. }
  9661. function parseBgpTime(val) {
  9662. if (!val) return 0;
  9663. val = String(val).trim();
  9664. if (val.includes(':')) {
  9665. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9666. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9667. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9668. }
  9669. return parseInt(val, 10) || 0;
  9670. }
  9671. function formatBgpTime(secs) {
  9672. if (!secs || secs <= 0) return '30';
  9673. return String(secs);
  9674. }
  9675. function populateBgpRoutingTables() {
  9676. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9677. if (!sel) return;
  9678. const cur = sel.value || 'main';
  9679. sel.innerHTML = '<option value="main">main</option>';
  9680. (state.routingTables || []).forEach(t => {
  9681. if (t.name !== 'main') {
  9682. const opt = document.createElement('option');
  9683. opt.value = t.name;
  9684. opt.innerText = t.name;
  9685. sel.appendChild(opt);
  9686. }
  9687. });
  9688. sel.value = cur;
  9689. }
  9690. function populateBgpLocalAddrDatalist() {
  9691. const dlBgp = document.getElementById('bgp-peer-local-addr-datalist');
  9692. if (!dlBgp) return;
  9693. const addrs = [];
  9694. (state.interfaces || []).forEach(iface => {
  9695. if (iface.ip) addrs.push(iface.ip.split('/')[0]);
  9696. (iface.addresses || []).forEach(a => addrs.push(a.split('/')[0]));
  9697. });
  9698. dlBgp.innerHTML = Array.from(new Set(addrs.filter(Boolean))).map(ip => `<option value="${escapeHtml(ip)}">`).join('');
  9699. }
  9700. function openAddBgpPeerModal() {
  9701. document.getElementById('bgp-peer-form').reset();
  9702. document.getElementById('modal-bgp-peer-id').value = '';
  9703. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9704. populateBgpLocalAddrDatalist();
  9705. // General Tab
  9706. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9707. document.getElementById('modal-bgp-peer-name').value = '';
  9708. document.getElementById('modal-bgp-peer-comment').value = '';
  9709. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9710. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9711. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9712. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9713. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9714. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9715. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9716. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9717. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9718. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9719. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9720. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9721. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9722. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9723. // Filters Tab
  9724. populateFilterChainsDatalist();
  9725. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9726. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9727. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9728. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9729. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9730. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9731. // Advertised Networks Tab
  9732. const container = document.getElementById('modal-bgp-output-networks-container');
  9733. if (container) {
  9734. container.innerHTML = '';
  9735. addOutputNetworkRow('');
  9736. }
  9737. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9738. if (removeBtn) removeBtn.classList.add('hidden');
  9739. switchBgpPeerModalTab('general');
  9740. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9741. }
  9742. function populateFilterChainsDatalist() {
  9743. const dl = document.getElementById('filter-chains-list');
  9744. if (!dl) return;
  9745. const chains = new Set();
  9746. (state.routingFilters || []).forEach(f => {
  9747. if (f.chain) chains.add(f.chain);
  9748. });
  9749. if (chains.size === 0) {
  9750. chains.add('awmn');
  9751. chains.add('Internal');
  9752. chains.add('bgp-in');
  9753. chains.add('bgp-out');
  9754. }
  9755. dl.innerHTML = '';
  9756. chains.forEach(c => {
  9757. const opt = document.createElement('option');
  9758. opt.value = c;
  9759. dl.appendChild(opt);
  9760. });
  9761. }
  9762. function openEditBgpPeerModal(id) {
  9763. const p = (state.bgpPeers || []).find(item => item.id === id);
  9764. if (!p) return;
  9765. populateFilterChainsDatalist();
  9766. populateBgpLocalAddrDatalist();
  9767. document.getElementById('modal-bgp-peer-id').value = p.id;
  9768. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9769. // General Tab
  9770. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9771. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9772. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9773. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9774. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9775. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9776. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9777. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9778. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9779. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9780. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9781. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9782. // Passive mode
  9783. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9784. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9785. // Next-hop self
  9786. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9787. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9788. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9789. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9790. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9791. // Filters Tab
  9792. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9793. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9794. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9795. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9796. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9797. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9798. // Advertised Networks Tab
  9799. const container = document.getElementById('modal-bgp-output-networks-container');
  9800. if (container) {
  9801. container.innerHTML = '';
  9802. if (p.output_networks && p.output_networks.length > 0) {
  9803. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9804. } else {
  9805. addOutputNetworkRow('');
  9806. }
  9807. }
  9808. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9809. if (removeBtn) removeBtn.classList.remove('hidden');
  9810. switchBgpPeerModalTab('general');
  9811. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9812. }
  9813. function copyCurrentBgpPeer() {
  9814. document.getElementById('modal-bgp-peer-id').value = '';
  9815. const nameEl = document.getElementById('modal-bgp-peer-name');
  9816. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9817. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9818. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9819. if (removeBtn) removeBtn.classList.add('hidden');
  9820. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9821. }
  9822. function removeCurrentBgpPeer() {
  9823. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9824. if (!id) return;
  9825. deleteBgpPeer(id);
  9826. closeBgpPeerModal();
  9827. }
  9828. function closeBgpPeerModal() {
  9829. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9830. }
  9831. function getBgpPeerFormData() {
  9832. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9833. const outputNetworks = [];
  9834. netInputs.forEach(inp => {
  9835. const v = inp.value.trim();
  9836. if (v) outputNetworks.push(v);
  9837. });
  9838. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9839. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9840. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9841. const useBfd = document.getElementById('modal-bgp-peer-use-bfd')?.checked || false;
  9842. return {
  9843. id: document.getElementById('modal-bgp-peer-id').value,
  9844. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9845. enabled: enabled,
  9846. disabled: !enabled,
  9847. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9848. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9849. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9850. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9851. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9852. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9853. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9854. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9855. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9856. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9857. use_bfd: useBfd,
  9858. passive: isPassive,
  9859. connect: !isPassive,
  9860. listen: true,
  9861. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9862. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9863. nexthop_self: isNexthopSelf,
  9864. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9865. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9866. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9867. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9868. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9869. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9870. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9871. output_networks: outputNetworks
  9872. };
  9873. }
  9874. async function submitBgpPeer(e) {
  9875. if (e) e.preventDefault();
  9876. const payload = getBgpPeerFormData();
  9877. try {
  9878. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9879. method: 'POST',
  9880. headers: { 'Content-Type': 'application/json' },
  9881. body: JSON.stringify(payload)
  9882. });
  9883. if (res.ok) {
  9884. closeBgpPeerModal();
  9885. showToast('Success', 'BGP Connection saved', 'success');
  9886. loadDynamicRouting();
  9887. } else {
  9888. const err = await res.json();
  9889. showToast('Error', err.error || 'Failed to save peer', 'error');
  9890. }
  9891. } catch (err) {
  9892. showToast('Error', err.message, 'error');
  9893. }
  9894. }
  9895. async function applyBgpPeerModal(e) {
  9896. if (e) e.preventDefault();
  9897. const payload = getBgpPeerFormData();
  9898. try {
  9899. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9900. method: 'POST',
  9901. headers: { 'Content-Type': 'application/json' },
  9902. body: JSON.stringify(payload)
  9903. });
  9904. if (res.ok) {
  9905. const data = await res.json();
  9906. if (data.peer && data.peer.id) {
  9907. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9908. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9909. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9910. }
  9911. showToast('Applied', 'BGP Connection applied', 'success');
  9912. loadDynamicRouting();
  9913. } else {
  9914. const err = await res.json();
  9915. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9916. }
  9917. } catch (err) {
  9918. showToast('Error', err.message, 'error');
  9919. }
  9920. }
  9921. async function deleteBgpPeer(id) {
  9922. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9923. try {
  9924. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9925. if (res.ok) {
  9926. showToast('Deleted', 'BGP peer removed', 'success');
  9927. loadDynamicRouting();
  9928. }
  9929. } catch (err) {
  9930. showToast('Error', err.message, 'error');
  9931. }
  9932. }
  9933. async function toggleBgpPeerState(id, disabled) {
  9934. try {
  9935. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9936. method: 'POST',
  9937. headers: { 'Content-Type': 'application/json' },
  9938. body: JSON.stringify({ disabled })
  9939. });
  9940. if (res.ok) {
  9941. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9942. loadDynamicRouting();
  9943. }
  9944. } catch (err) {
  9945. showToast('Error', err.message, 'error');
  9946. }
  9947. }
  9948. function openAddBgpNetworkModal() {
  9949. document.getElementById('bgp-network-form').reset();
  9950. document.getElementById('modal-bgp-net-id').value = '';
  9951. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9952. }
  9953. function closeBgpNetworkModal() {
  9954. document.getElementById('bgp-network-modal').classList.add('hidden');
  9955. }
  9956. async function submitBgpNetwork(e) {
  9957. e.preventDefault();
  9958. const payload = {
  9959. id: document.getElementById('modal-bgp-net-id').value,
  9960. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9961. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9962. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9963. };
  9964. try {
  9965. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9966. method: 'POST',
  9967. headers: { 'Content-Type': 'application/json' },
  9968. body: JSON.stringify(payload)
  9969. });
  9970. if (res.ok) {
  9971. closeBgpNetworkModal();
  9972. showToast('Success', 'BGP network advertisement saved', 'success');
  9973. loadDynamicRouting();
  9974. } else {
  9975. const err = await res.json();
  9976. showToast('Error', err.error || 'Failed to save network', 'error');
  9977. }
  9978. } catch (err) {
  9979. showToast('Error', err.message, 'error');
  9980. }
  9981. }
  9982. async function deleteBgpNetwork(id) {
  9983. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9984. try {
  9985. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9986. if (res.ok) {
  9987. showToast('Deleted', 'Network advertisement removed', 'success');
  9988. loadDynamicRouting();
  9989. }
  9990. } catch (err) {
  9991. showToast('Error', err.message, 'error');
  9992. }
  9993. }
  9994. // =========================================================================
  9995. // DEBTIK v7 OSPF MODALS & ACTIONS
  9996. // =========================================================================
  9997. // --- 1. OSPF INSTANCE ---
  9998. function openOspfInstanceModal(id = null) {
  9999. const isEdit = !!id;
  10000. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  10001. id: '',
  10002. name: 'Default',
  10003. version: 2,
  10004. vrf: 'main',
  10005. router_id: '192.168.131.56',
  10006. routing_table: 'main',
  10007. enabled: true,
  10008. redistribute_connected: false,
  10009. redistribute_static: true,
  10010. redistribute_bgp: false,
  10011. comment: ''
  10012. };
  10013. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  10014. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  10015. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  10016. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  10017. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  10018. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  10019. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  10020. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  10021. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  10022. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  10023. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  10024. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  10025. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  10026. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  10027. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  10028. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  10029. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  10030. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  10031. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10032. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  10033. }
  10034. function toggleOspfDefaultModeUI() {
  10035. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  10036. const select = document.getElementById('modal-ospf-inst-originate-default');
  10037. if (!select) return;
  10038. if (isChecked) {
  10039. if (select.value === 'never') select.value = 'if-installed';
  10040. } else {
  10041. select.value = 'never';
  10042. }
  10043. }
  10044. function onOspfOriginateDefaultChange() {
  10045. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  10046. const chk = document.getElementById('modal-ospf-inst-redist-default');
  10047. if (chk) chk.checked = val !== 'never';
  10048. }
  10049. function openEditOspfInstanceModal(id) {
  10050. openOspfInstanceModal(id);
  10051. }
  10052. function closeOspfInstanceModal() {
  10053. document.getElementById('ospf-instance-modal').classList.add('hidden');
  10054. }
  10055. async function submitOspfInstance(e) {
  10056. if (e) e.preventDefault();
  10057. const payload = {
  10058. id: document.getElementById('modal-ospf-inst-id').value,
  10059. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  10060. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  10061. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  10062. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  10063. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10064. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10065. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10066. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10067. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10068. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10069. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10070. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10071. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10072. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0
  10073. };
  10074. try {
  10075. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10076. method: 'POST',
  10077. headers: { 'Content-Type': 'application/json' },
  10078. body: JSON.stringify(payload)
  10079. });
  10080. if (res.ok) {
  10081. closeOspfInstanceModal();
  10082. showToast('Saved', 'OSPF instance updated', 'success');
  10083. loadDynamicRouting();
  10084. } else {
  10085. const err = await res.json();
  10086. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10087. }
  10088. } catch (err) {
  10089. showToast('Error', err.message, 'error');
  10090. }
  10091. }
  10092. function applyOspfInstanceForm() {
  10093. submitOspfInstance(null);
  10094. }
  10095. function copyOspfInstance() {
  10096. document.getElementById('modal-ospf-inst-id').value = '';
  10097. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10098. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10099. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10100. }
  10101. async function deleteCurrentOspfInstance() {
  10102. const id = document.getElementById('modal-ospf-inst-id').value;
  10103. if (!id) return;
  10104. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10105. try {
  10106. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10107. if (res.ok) {
  10108. closeOspfInstanceModal();
  10109. showToast('Removed', 'OSPF instance deleted', 'success');
  10110. loadDynamicRouting();
  10111. }
  10112. } catch (err) {
  10113. showToast('Error', err.message, 'error');
  10114. }
  10115. }
  10116. async function enableSelectedOspfInstance() {
  10117. const id = state.selectedOspfRow?.instances;
  10118. if (!id) return;
  10119. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10120. method: 'POST',
  10121. headers: { 'Content-Type': 'application/json' },
  10122. body: JSON.stringify({ disabled: false })
  10123. });
  10124. loadDynamicRouting();
  10125. }
  10126. async function disableSelectedOspfInstance() {
  10127. const id = state.selectedOspfRow?.instances;
  10128. if (!id) return;
  10129. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10130. method: 'POST',
  10131. headers: { 'Content-Type': 'application/json' },
  10132. body: JSON.stringify({ disabled: true })
  10133. });
  10134. loadDynamicRouting();
  10135. }
  10136. async function removeSelectedOspfInstance() {
  10137. const id = state.selectedOspfRow?.instances;
  10138. if (!id) return;
  10139. if (!confirm('Delete selected OSPF instance?')) return;
  10140. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10141. loadDynamicRouting();
  10142. }
  10143. async function promptCommentOspfInstance() {
  10144. const id = state.selectedOspfRow?.instances;
  10145. if (!id) return;
  10146. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10147. if (!inst) return;
  10148. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10149. if (comment === null) return;
  10150. inst.comment = comment;
  10151. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10152. method: 'POST',
  10153. headers: { 'Content-Type': 'application/json' },
  10154. body: JSON.stringify(inst)
  10155. });
  10156. loadDynamicRouting();
  10157. }
  10158. // --- 2. OSPF AREA ---
  10159. function populateOspfAreaDropdowns() {
  10160. const instSelect = document.getElementById('modal-ospf-area-instance');
  10161. if (instSelect) {
  10162. const cur = instSelect.value;
  10163. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10164. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10165. if (cur) instSelect.value = cur;
  10166. }
  10167. }
  10168. function openOspfAreaModal(id = null) {
  10169. const isEdit = !!id;
  10170. populateOspfAreaDropdowns();
  10171. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10172. id: '',
  10173. name: 'Default',
  10174. instance: 'Default',
  10175. area_id: '0.0.0.0',
  10176. area_type: 'default',
  10177. default_cost: 1,
  10178. no_summaries: false,
  10179. disabled: false,
  10180. comment: ''
  10181. };
  10182. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10183. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10184. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10185. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10186. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10187. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10188. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10189. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10190. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10191. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10192. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10193. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10194. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10195. }
  10196. function openEditOspfAreaModal(id) {
  10197. openOspfAreaModal(id);
  10198. }
  10199. function closeOspfAreaModal() {
  10200. document.getElementById('ospf-area-modal').classList.add('hidden');
  10201. }
  10202. async function submitOspfArea(e) {
  10203. if (e) e.preventDefault();
  10204. const payload = {
  10205. id: document.getElementById('modal-ospf-area-id').value,
  10206. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10207. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10208. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10209. area_type: document.getElementById('modal-ospf-area-type').value,
  10210. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10211. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10212. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10213. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10214. };
  10215. try {
  10216. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10217. method: 'POST',
  10218. headers: { 'Content-Type': 'application/json' },
  10219. body: JSON.stringify(payload)
  10220. });
  10221. if (res.ok) {
  10222. closeOspfAreaModal();
  10223. showToast('Saved', 'OSPF area saved', 'success');
  10224. loadDynamicRouting();
  10225. } else {
  10226. const err = await res.json();
  10227. showToast('Error', err.error || 'Failed to save area', 'error');
  10228. }
  10229. } catch (err) {
  10230. showToast('Error', err.message, 'error');
  10231. }
  10232. }
  10233. function applyOspfAreaForm() {
  10234. submitOspfArea(null);
  10235. }
  10236. function copyOspfArea() {
  10237. document.getElementById('modal-ospf-area-id').value = '';
  10238. document.getElementById('modal-ospf-area-name').value += '-copy';
  10239. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10240. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10241. }
  10242. async function deleteCurrentOspfArea() {
  10243. const id = document.getElementById('modal-ospf-area-id').value;
  10244. if (!id) return;
  10245. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10246. try {
  10247. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10248. if (res.ok) {
  10249. closeOspfAreaModal();
  10250. showToast('Removed', 'OSPF area deleted', 'success');
  10251. loadDynamicRouting();
  10252. }
  10253. } catch (err) {
  10254. showToast('Error', err.message, 'error');
  10255. }
  10256. }
  10257. async function enableSelectedOspfArea() {
  10258. const id = state.selectedOspfRow?.areas;
  10259. if (!id) return;
  10260. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10261. method: 'POST',
  10262. headers: { 'Content-Type': 'application/json' },
  10263. body: JSON.stringify({ disabled: false })
  10264. });
  10265. loadDynamicRouting();
  10266. }
  10267. async function disableSelectedOspfArea() {
  10268. const id = state.selectedOspfRow?.areas;
  10269. if (!id) return;
  10270. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10271. method: 'POST',
  10272. headers: { 'Content-Type': 'application/json' },
  10273. body: JSON.stringify({ disabled: true })
  10274. });
  10275. loadDynamicRouting();
  10276. }
  10277. async function removeSelectedOspfArea() {
  10278. const id = state.selectedOspfRow?.areas;
  10279. if (!id) return;
  10280. if (!confirm('Delete selected OSPF area?')) return;
  10281. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10282. loadDynamicRouting();
  10283. }
  10284. async function promptCommentOspfArea() {
  10285. const id = state.selectedOspfRow?.areas;
  10286. if (!id) return;
  10287. const area = (state.ospfAreas || []).find(a => a.id === id);
  10288. if (!area) return;
  10289. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10290. if (comment === null) return;
  10291. area.comment = comment;
  10292. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10293. method: 'POST',
  10294. headers: { 'Content-Type': 'application/json' },
  10295. body: JSON.stringify(area)
  10296. });
  10297. loadDynamicRouting();
  10298. }
  10299. // --- 3. OSPF AREA RANGE ---
  10300. function populateAreaRangeDropdowns() {
  10301. const select = document.getElementById('modal-ospf-range-area');
  10302. if (select) {
  10303. const cur = select.value;
  10304. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10305. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10306. if (cur) select.value = cur;
  10307. }
  10308. }
  10309. function openOspfAreaRangeModal(id = null) {
  10310. const isEdit = !!id;
  10311. populateAreaRangeDropdowns();
  10312. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10313. id: '',
  10314. area: 'Default',
  10315. prefix: '',
  10316. cost: 1,
  10317. advertise: true,
  10318. disabled: false,
  10319. comment: ''
  10320. };
  10321. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10322. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10323. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10324. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10325. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10326. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10327. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10328. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10329. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10330. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10331. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10332. }
  10333. function openEditOspfAreaRangeModal(id) {
  10334. openOspfAreaRangeModal(id);
  10335. }
  10336. function closeOspfAreaRangeModal() {
  10337. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10338. }
  10339. async function submitOspfAreaRange(e) {
  10340. if (e) e.preventDefault();
  10341. const payload = {
  10342. id: document.getElementById('modal-ospf-range-id').value,
  10343. area: document.getElementById('modal-ospf-range-area').value,
  10344. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10345. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10346. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10347. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10348. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10349. };
  10350. try {
  10351. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10352. method: 'POST',
  10353. headers: { 'Content-Type': 'application/json' },
  10354. body: JSON.stringify(payload)
  10355. });
  10356. if (res.ok) {
  10357. closeOspfAreaRangeModal();
  10358. showToast('Saved', 'Area range saved', 'success');
  10359. loadDynamicRouting();
  10360. } else {
  10361. const err = await res.json();
  10362. showToast('Error', err.error || 'Failed to save area range', 'error');
  10363. }
  10364. } catch (err) {
  10365. showToast('Error', err.message, 'error');
  10366. }
  10367. }
  10368. function applyOspfAreaRangeForm() {
  10369. submitOspfAreaRange(null);
  10370. }
  10371. async function deleteCurrentOspfAreaRange() {
  10372. const id = document.getElementById('modal-ospf-range-id').value;
  10373. if (!id) return;
  10374. if (!confirm('Delete this area range?')) return;
  10375. try {
  10376. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10377. closeOspfAreaRangeModal();
  10378. showToast('Removed', 'Area range removed', 'success');
  10379. loadDynamicRouting();
  10380. } catch (err) {
  10381. showToast('Error', err.message, 'error');
  10382. }
  10383. }
  10384. async function enableSelectedOspfAreaRange() {
  10385. const id = state.selectedOspfRow?.['area-ranges'];
  10386. if (!id) return;
  10387. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10388. if (!r) return;
  10389. r.disabled = false;
  10390. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10391. loadDynamicRouting();
  10392. }
  10393. async function disableSelectedOspfAreaRange() {
  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. r.disabled = true;
  10399. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10400. loadDynamicRouting();
  10401. }
  10402. async function removeSelectedOspfAreaRange() {
  10403. const id = state.selectedOspfRow?.['area-ranges'];
  10404. if (!id) return;
  10405. if (!confirm('Delete selected area range?')) return;
  10406. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10407. loadDynamicRouting();
  10408. }
  10409. async function promptCommentOspfAreaRange() {
  10410. const id = state.selectedOspfRow?.['area-ranges'];
  10411. if (!id) return;
  10412. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10413. if (!r) return;
  10414. const comment = prompt('Enter comment for area range:', r.comment || '');
  10415. if (comment === null) return;
  10416. r.comment = comment;
  10417. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10418. loadDynamicRouting();
  10419. }
  10420. // --- 4. OSPF INTERFACE TEMPLATE ---
  10421. function switchOspfTemplateTab(tab) {
  10422. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10423. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10424. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10425. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10426. if (tab === 'general') {
  10427. if (tabGen) tabGen.classList.remove('hidden');
  10428. if (tabAuth) tabAuth.classList.add('hidden');
  10429. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10430. 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';
  10431. } else {
  10432. if (tabGen) tabGen.classList.add('hidden');
  10433. if (tabAuth) tabAuth.classList.remove('hidden');
  10434. 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';
  10435. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10436. }
  10437. }
  10438. function populateTemplateAreaDropdowns() {
  10439. const select = document.getElementById('modal-ospf-tmpl-area');
  10440. if (select) {
  10441. const cur = select.value;
  10442. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10443. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10444. if (cur) select.value = cur;
  10445. }
  10446. }
  10447. function openOspfTemplateModal(id = null) {
  10448. const isEdit = !!id;
  10449. populateTemplateAreaDropdowns();
  10450. switchOspfTemplateTab('general');
  10451. const dl = document.getElementById('ospf-tmpl-iface-datalist');
  10452. if (dl) {
  10453. dl.innerHTML = '<option value="*"><option value="all">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  10454. }
  10455. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10456. id: '',
  10457. interfaces: '',
  10458. area: 'Default',
  10459. networks: '',
  10460. network_type: 'broadcast',
  10461. cost: 1,
  10462. priority: 128,
  10463. passive: false,
  10464. hello_interval: 10,
  10465. dead_interval: 40,
  10466. auth: 'none',
  10467. auth_key: '',
  10468. disabled: false,
  10469. comment: ''
  10470. };
  10471. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10472. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10473. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10474. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10475. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10476. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10477. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10478. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10479. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10480. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10481. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10482. if (document.getElementById('modal-ospf-tmpl-bfd')) document.getElementById('modal-ospf-tmpl-bfd').checked = !!tmpl.use_bfd;
  10483. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10484. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10485. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10486. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10487. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10488. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10489. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10490. }
  10491. function openEditOspfTemplateModal(id) {
  10492. openOspfTemplateModal(id);
  10493. }
  10494. function closeOspfTemplateModal() {
  10495. document.getElementById('ospf-template-modal').classList.add('hidden');
  10496. }
  10497. async function submitOspfTemplate(e) {
  10498. if (e) e.preventDefault();
  10499. const payload = {
  10500. id: document.getElementById('modal-ospf-tmpl-id').value,
  10501. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10502. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10503. area: document.getElementById('modal-ospf-tmpl-area').value,
  10504. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10505. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10506. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10507. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10508. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10509. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10510. use_bfd: document.getElementById('modal-ospf-tmpl-bfd')?.checked || false,
  10511. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10512. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10513. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10514. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10515. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10516. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10517. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10518. };
  10519. try {
  10520. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10521. method: 'POST',
  10522. headers: { 'Content-Type': 'application/json' },
  10523. body: JSON.stringify(payload)
  10524. });
  10525. if (res.ok) {
  10526. closeOspfTemplateModal();
  10527. showToast('Saved', 'Interface template saved', 'success');
  10528. loadDynamicRouting();
  10529. } else {
  10530. const err = await res.json();
  10531. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10532. }
  10533. } catch (err) {
  10534. showToast('Error', err.message, 'error');
  10535. }
  10536. }
  10537. function applyOspfTemplateForm() {
  10538. submitOspfTemplate(null);
  10539. }
  10540. function copyOspfTemplate() {
  10541. document.getElementById('modal-ospf-tmpl-id').value = '';
  10542. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10543. showToast('Copied', 'Duplicated as new template', 'info');
  10544. }
  10545. async function deleteCurrentOspfTemplate() {
  10546. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10547. if (!id) return;
  10548. if (!confirm('Delete this interface template?')) return;
  10549. try {
  10550. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10551. closeOspfTemplateModal();
  10552. showToast('Removed', 'Interface template deleted', 'success');
  10553. loadDynamicRouting();
  10554. } catch (err) {
  10555. showToast('Error', err.message, 'error');
  10556. }
  10557. }
  10558. async function enableSelectedOspfTemplate() {
  10559. const id = state.selectedOspfRow?.templates;
  10560. if (!id) return;
  10561. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10562. method: 'POST',
  10563. headers: { 'Content-Type': 'application/json' },
  10564. body: JSON.stringify({ disabled: false })
  10565. });
  10566. loadDynamicRouting();
  10567. }
  10568. async function disableSelectedOspfTemplate() {
  10569. const id = state.selectedOspfRow?.templates;
  10570. if (!id) return;
  10571. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10572. method: 'POST',
  10573. headers: { 'Content-Type': 'application/json' },
  10574. body: JSON.stringify({ disabled: true })
  10575. });
  10576. loadDynamicRouting();
  10577. }
  10578. async function removeSelectedOspfTemplate() {
  10579. const id = state.selectedOspfRow?.templates;
  10580. if (!id) return;
  10581. if (!confirm('Delete selected interface template?')) return;
  10582. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10583. loadDynamicRouting();
  10584. }
  10585. async function promptCommentOspfTemplate() {
  10586. const id = state.selectedOspfRow?.templates;
  10587. if (!id) return;
  10588. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10589. if (!tmpl) return;
  10590. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10591. if (comment === null) return;
  10592. tmpl.comment = comment;
  10593. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10594. method: 'POST',
  10595. headers: { 'Content-Type': 'application/json' },
  10596. body: JSON.stringify(tmpl)
  10597. });
  10598. loadDynamicRouting();
  10599. }
  10600. // --- 5. OSPF STATIC NEIGHBOR ---
  10601. function populateStaticNbrAreaDropdowns() {
  10602. const select = document.getElementById('modal-ospf-snbr-area');
  10603. if (select) {
  10604. const cur = select.value;
  10605. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10606. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10607. if (cur) select.value = cur;
  10608. }
  10609. }
  10610. function openOspfStaticNbrModal(id = null) {
  10611. const isEdit = !!id;
  10612. populateStaticNbrAreaDropdowns();
  10613. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10614. id: '',
  10615. address: '',
  10616. area: 'Default',
  10617. poll_interval: 120,
  10618. cost: 1,
  10619. disabled: false,
  10620. comment: ''
  10621. };
  10622. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10623. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10624. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10625. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10626. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10627. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10628. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10629. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10630. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10631. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10632. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10633. }
  10634. function openEditOspfStaticNbrModal(id) {
  10635. openOspfStaticNbrModal(id);
  10636. }
  10637. function closeOspfStaticNbrModal() {
  10638. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10639. }
  10640. async function submitOspfStaticNbr(e) {
  10641. if (e) e.preventDefault();
  10642. const payload = {
  10643. id: document.getElementById('modal-ospf-snbr-id').value,
  10644. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10645. area: document.getElementById('modal-ospf-snbr-area').value,
  10646. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10647. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10648. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10649. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10650. };
  10651. try {
  10652. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10653. method: 'POST',
  10654. headers: { 'Content-Type': 'application/json' },
  10655. body: JSON.stringify(payload)
  10656. });
  10657. if (res.ok) {
  10658. closeOspfStaticNbrModal();
  10659. showToast('Saved', 'Static neighbor saved', 'success');
  10660. loadDynamicRouting();
  10661. } else {
  10662. const err = await res.json();
  10663. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10664. }
  10665. } catch (err) {
  10666. showToast('Error', err.message, 'error');
  10667. }
  10668. }
  10669. function applyOspfStaticNbrForm() {
  10670. submitOspfStaticNbr(null);
  10671. }
  10672. async function deleteCurrentOspfStaticNbr() {
  10673. const id = document.getElementById('modal-ospf-snbr-id').value;
  10674. if (!id) return;
  10675. if (!confirm('Delete this static neighbor?')) return;
  10676. try {
  10677. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10678. closeOspfStaticNbrModal();
  10679. showToast('Removed', 'Static neighbor removed', 'success');
  10680. loadDynamicRouting();
  10681. } catch (err) {
  10682. showToast('Error', err.message, 'error');
  10683. }
  10684. }
  10685. async function enableSelectedOspfStaticNbr() {
  10686. const id = state.selectedOspfRow?.['static-nbrs'];
  10687. if (!id) return;
  10688. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10689. loadDynamicRouting();
  10690. }
  10691. async function disableSelectedOspfStaticNbr() {
  10692. const id = state.selectedOspfRow?.['static-nbrs'];
  10693. if (!id) return;
  10694. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10695. loadDynamicRouting();
  10696. }
  10697. async function removeSelectedOspfStaticNbr() {
  10698. const id = state.selectedOspfRow?.['static-nbrs'];
  10699. if (!id) return;
  10700. if (!confirm('Delete selected static neighbor?')) return;
  10701. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10702. loadDynamicRouting();
  10703. }
  10704. async function promptCommentOspfStaticNbr() {
  10705. const id = state.selectedOspfRow?.['static-nbrs'];
  10706. if (!id) return;
  10707. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10708. if (!n) return;
  10709. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10710. if (comment === null) return;
  10711. n.comment = comment;
  10712. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10713. loadDynamicRouting();
  10714. }
  10715. // Backward-compat aliases
  10716. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10717. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10718. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10719. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10720. function deleteOspfInterface(id) {
  10721. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10722. }
  10723. function toggleOspfInterfaceState(id, disabled) {
  10724. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10725. method: 'POST',
  10726. headers: { 'Content-Type': 'application/json' },
  10727. body: JSON.stringify({ disabled })
  10728. }).then(() => loadDynamicRouting());
  10729. }
  10730. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10731. function deleteOspfArea(id) {
  10732. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10733. }
  10734. // ============================================================================
  10735. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10736. // ============================================================================
  10737. function switchBridgeSubTab(tab) {
  10738. state.bridgeSubTab = tab;
  10739. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10740. tabs.forEach(t => {
  10741. const panel = document.getElementById(`bridge-subtab-${t}`);
  10742. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10743. if (panel) {
  10744. if (t === tab) panel.classList.remove('hidden');
  10745. else panel.classList.add('hidden');
  10746. }
  10747. if (btn) {
  10748. if (t === tab) {
  10749. 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';
  10750. } else {
  10751. 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';
  10752. }
  10753. }
  10754. });
  10755. const addBtn = document.getElementById('bridge-top-action-btn');
  10756. if (addBtn) {
  10757. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10758. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10759. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10760. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10761. }
  10762. if (tab === 'hosts') loadBridgeHosts();
  10763. setTimeout(initTableSorting, 50);
  10764. }
  10765. function openCurrentBridgeModal() {
  10766. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10767. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10768. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10769. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10770. }
  10771. async function loadBridge() {
  10772. try {
  10773. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10774. fetch(`${API_BASE}/bridge/bridges`),
  10775. fetch(`${API_BASE}/bridge/ports`),
  10776. fetch(`${API_BASE}/bridge/vlans`),
  10777. fetch(`${API_BASE}/bridge/summary`),
  10778. fetch(`${API_BASE}/vpn/eoip`),
  10779. fetch(`${API_BASE}/vpn/vxlan`),
  10780. fetch(`${API_BASE}/vlans`)
  10781. ]);
  10782. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10783. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10784. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10785. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10786. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10787. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10788. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10789. // Badges & Stats
  10790. const bBridges = document.getElementById('bridge-badge-bridges');
  10791. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10792. const bPorts = document.getElementById('bridge-badge-ports');
  10793. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10794. const bVlans = document.getElementById('bridge-badge-vlans');
  10795. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10796. const bHosts = document.getElementById('bridge-badge-hosts');
  10797. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10798. const sBr = document.getElementById('bridge-stat-bridges');
  10799. if (sBr) sBr.innerText = (state.bridges || []).length;
  10800. const sPorts = document.getElementById('bridge-stat-ports');
  10801. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10802. const sHosts = document.getElementById('bridge-stat-hosts');
  10803. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10804. renderBridges();
  10805. renderBridgePorts();
  10806. renderBridgeVLANs();
  10807. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10808. } catch (err) {
  10809. console.error('Failed to load bridge subsystem:', err);
  10810. }
  10811. }
  10812. // ----------------- Bridges -----------------
  10813. function renderBridges() {
  10814. const tbody = document.getElementById('bridge-table-body');
  10815. const empty = document.getElementById('bridge-empty-bridges');
  10816. const countBadge = document.getElementById('bridge-count-badge');
  10817. if (!tbody) return;
  10818. tbody.innerHTML = '';
  10819. const bridges = state.bridges || [];
  10820. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10821. if (bridges.length === 0) {
  10822. empty?.classList.remove('hidden');
  10823. return;
  10824. }
  10825. empty?.classList.add('hidden');
  10826. bridges.forEach((b, idx) => {
  10827. const tr = document.createElement('tr');
  10828. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10829. // Format IP addresses pill list
  10830. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10831. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10832. ipsHtml = b.ip_addresses.map(ip => `
  10833. <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">
  10834. <span>${ip}</span>
  10835. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10836. </span>
  10837. `).join(' ');
  10838. }
  10839. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10840. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10841. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10842. tr.innerHTML = `
  10843. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10844. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10845. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10846. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10847. </td>
  10848. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10849. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10850. <td class="py-2.5 px-3">
  10851. <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>
  10852. </td>
  10853. <td class="py-2.5 px-3 text-center">
  10854. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10855. </td>
  10856. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10857. <td class="py-2.5 px-3">
  10858. <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>
  10859. </td>
  10860. <td class="py-2.5 px-3">
  10861. <div class="flex items-center gap-1.5 flex-wrap">
  10862. ${ipsHtml}
  10863. <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>
  10864. </div>
  10865. </td>
  10866. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10867. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10868. </td>
  10869. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10870. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10871. <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>
  10872. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10873. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10874. </td>
  10875. `;
  10876. tbody.appendChild(tr);
  10877. });
  10878. }
  10879. function openAddBridgeModal() {
  10880. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10881. document.getElementById('bridge-modal-id').value = '';
  10882. document.getElementById('bridge-modal-name').value = 'bridge1';
  10883. document.getElementById('bridge-modal-name').disabled = false;
  10884. document.getElementById('bridge-modal-mtu').value = '1500';
  10885. document.getElementById('bridge-modal-mac').value = '';
  10886. document.getElementById('bridge-modal-stp').value = 'stp';
  10887. document.getElementById('bridge-modal-priority').value = '32768';
  10888. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10889. document.getElementById('bridge-modal-pvid').value = '1';
  10890. document.getElementById('bridge-modal-fastforward').checked = true;
  10891. document.getElementById('bridge-modal-comment').value = '';
  10892. document.getElementById('bridge-modal-disabled').checked = false;
  10893. toggleBridgeModalVlanFiltering();
  10894. document.getElementById('bridge-modal').classList.remove('hidden');
  10895. }
  10896. function openEditBridgeModal(id) {
  10897. const b = (state.bridges || []).find(x => x.id === id);
  10898. if (!b) return;
  10899. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10900. document.getElementById('bridge-modal-id').value = b.id;
  10901. document.getElementById('bridge-modal-name').value = b.name;
  10902. document.getElementById('bridge-modal-name').disabled = true;
  10903. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10904. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10905. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10906. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10907. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10908. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10909. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10910. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10911. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10912. toggleBridgeModalVlanFiltering();
  10913. document.getElementById('bridge-modal').classList.remove('hidden');
  10914. }
  10915. function closeBridgeModal() {
  10916. document.getElementById('bridge-modal').classList.add('hidden');
  10917. }
  10918. function toggleBridgeModalVlanFiltering() {
  10919. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10920. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10921. if (pvidBox) {
  10922. if (chk) pvidBox.classList.remove('opacity-40');
  10923. else pvidBox.classList.add('opacity-40');
  10924. }
  10925. }
  10926. async function submitSaveBridge(e) {
  10927. e.preventDefault();
  10928. const id = document.getElementById('bridge-modal-id').value;
  10929. const name = document.getElementById('bridge-modal-name').value.trim();
  10930. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10931. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10932. const stp = document.getElementById('bridge-modal-stp').value;
  10933. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10934. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10935. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10936. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10937. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10938. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10939. try {
  10940. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10941. method: 'POST',
  10942. headers: { 'Content-Type': 'application/json' },
  10943. body: JSON.stringify({
  10944. id,
  10945. name,
  10946. mtu,
  10947. mac_address: mac,
  10948. stp,
  10949. priority,
  10950. vlan_filtering: vlanFiltering,
  10951. pvid,
  10952. fast_forward: fastForward,
  10953. comment,
  10954. disabled
  10955. })
  10956. });
  10957. if (res.ok) {
  10958. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10959. closeBridgeModal();
  10960. loadBridge();
  10961. fetchData(false);
  10962. } else {
  10963. const err = await res.json();
  10964. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10965. }
  10966. } catch (err) {
  10967. showToast('Error', err.message, 'error');
  10968. }
  10969. }
  10970. async function toggleBridgeState(id, disabled) {
  10971. try {
  10972. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10973. method: 'POST',
  10974. headers: { 'Content-Type': 'application/json' },
  10975. body: JSON.stringify({ disabled })
  10976. });
  10977. if (res.ok) {
  10978. loadBridge();
  10979. fetchData(false);
  10980. }
  10981. } catch (err) {
  10982. showToast('Error', err.message, 'error');
  10983. }
  10984. }
  10985. async function deleteBridge(id) {
  10986. const b = (state.bridges || []).find(x => x.id === id);
  10987. const name = b ? b.name : id;
  10988. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10989. try {
  10990. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10991. if (res.ok) {
  10992. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10993. loadBridge();
  10994. fetchData(false);
  10995. } else {
  10996. const err = await res.json();
  10997. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10998. }
  10999. } catch (err) {
  11000. showToast('Error', err.message, 'error');
  11001. }
  11002. }
  11003. // ----------------- Bridge IP Assignments -----------------
  11004. function openAddBridgeIPModal(id, name) {
  11005. document.getElementById('bridge-ip-modal-id').value = id;
  11006. document.getElementById('bridge-ip-modal-sub').innerText = name;
  11007. document.getElementById('bridge-ip-modal-cidr').value = '';
  11008. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  11009. }
  11010. function closeBridgeIPModal() {
  11011. document.getElementById('bridge-ip-modal').classList.add('hidden');
  11012. }
  11013. async function submitAddBridgeIP(e) {
  11014. e.preventDefault();
  11015. const id = document.getElementById('bridge-ip-modal-id').value;
  11016. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  11017. try {
  11018. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11019. method: 'POST',
  11020. headers: { 'Content-Type': 'application/json' },
  11021. body: JSON.stringify({ ip })
  11022. });
  11023. if (res.ok) {
  11024. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  11025. closeBridgeIPModal();
  11026. loadBridge();
  11027. fetchData(false);
  11028. } else {
  11029. const err = await res.json();
  11030. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  11031. }
  11032. } catch (err) {
  11033. showToast('Error', err.message, 'error');
  11034. }
  11035. }
  11036. async function deleteBridgeIP(id, ip) {
  11037. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  11038. try {
  11039. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11040. method: 'DELETE',
  11041. headers: { 'Content-Type': 'application/json' },
  11042. body: JSON.stringify({ ip })
  11043. });
  11044. if (res.ok) {
  11045. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  11046. loadBridge();
  11047. fetchData(false);
  11048. }
  11049. } catch (err) {
  11050. showToast('Error', err.message, 'error');
  11051. }
  11052. }
  11053. // ----------------- Bridge Ports -----------------
  11054. function renderBridgePorts() {
  11055. const tbody = document.getElementById('bridge-ports-table-body');
  11056. const empty = document.getElementById('bridge-empty-ports');
  11057. const countBadge = document.getElementById('bridge-ports-count-badge');
  11058. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  11059. if (!tbody) return;
  11060. tbody.innerHTML = '';
  11061. // Update filter select
  11062. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  11063. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  11064. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  11065. if (ports.length === 0) {
  11066. empty?.classList.remove('hidden');
  11067. return;
  11068. }
  11069. empty?.classList.add('hidden');
  11070. ports.forEach((p, idx) => {
  11071. const tr = document.createElement('tr');
  11072. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11073. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11074. tr.innerHTML = `
  11075. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11076. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11077. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11078. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11079. </td>
  11080. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11081. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11082. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11083. <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>
  11084. <td class="py-2.5 px-3">
  11085. ${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>'}
  11086. </td>
  11087. <td class="py-2.5 px-3">
  11088. <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>
  11089. </td>
  11090. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11091. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11092. <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>
  11093. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11094. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11095. </td>
  11096. `;
  11097. tbody.appendChild(tr);
  11098. });
  11099. }
  11100. function openAddBridgePortModal() {
  11101. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11102. document.getElementById('bridge-port-modal-id').value = '';
  11103. populateBridgeSelect('bridge-port-modal-bridge');
  11104. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11105. document.getElementById('bridge-port-modal-pvid').value = '1';
  11106. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11107. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11108. document.getElementById('bridge-port-modal-horizon').value = '0';
  11109. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11110. document.getElementById('bridge-port-modal-priority').value = '128';
  11111. document.getElementById('bridge-port-modal-learn').checked = true;
  11112. document.getElementById('bridge-port-modal-comment').value = '';
  11113. document.getElementById('bridge-port-modal-disabled').checked = false;
  11114. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11115. }
  11116. function openEditBridgePortModal(id) {
  11117. const p = (state.bridgePorts || []).find(x => x.id === id);
  11118. if (!p) return;
  11119. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11120. document.getElementById('bridge-port-modal-id').value = p.id;
  11121. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11122. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11123. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11124. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11125. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11126. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11127. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11128. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11129. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11130. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11131. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11132. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11133. }
  11134. function closeBridgePortModal() {
  11135. document.getElementById('bridge-port-modal').classList.add('hidden');
  11136. }
  11137. async function submitSaveBridgePort(e) {
  11138. e.preventDefault();
  11139. const id = document.getElementById('bridge-port-modal-id').value;
  11140. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11141. const iface = document.getElementById('bridge-port-modal-interface').value;
  11142. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11143. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11144. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11145. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11146. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11147. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11148. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11149. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11150. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11151. try {
  11152. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11153. method: 'POST',
  11154. headers: { 'Content-Type': 'application/json' },
  11155. body: JSON.stringify({
  11156. id,
  11157. bridge,
  11158. interface: iface,
  11159. pvid,
  11160. frame_types: frameTypes,
  11161. ingress_filtering: ingressFiltering,
  11162. horizon,
  11163. path_cost: pathCost,
  11164. priority,
  11165. learn,
  11166. comment,
  11167. disabled
  11168. })
  11169. });
  11170. if (res.ok) {
  11171. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11172. closeBridgePortModal();
  11173. loadBridge();
  11174. fetchData(false);
  11175. } else {
  11176. const err = await res.json();
  11177. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11178. }
  11179. } catch (err) {
  11180. showToast('Error', err.message, 'error');
  11181. }
  11182. }
  11183. async function toggleBridgePortState(id, disabled) {
  11184. try {
  11185. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11186. method: 'POST',
  11187. headers: { 'Content-Type': 'application/json' },
  11188. body: JSON.stringify({ disabled })
  11189. });
  11190. if (res.ok) {
  11191. loadBridge();
  11192. fetchData(false);
  11193. }
  11194. } catch (err) {
  11195. showToast('Error', err.message, 'error');
  11196. }
  11197. }
  11198. async function deleteBridgePort(id) {
  11199. const p = (state.bridgePorts || []).find(x => x.id === id);
  11200. const iface = p ? p.interface : id;
  11201. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11202. try {
  11203. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11204. if (res.ok) {
  11205. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11206. loadBridge();
  11207. fetchData(false);
  11208. }
  11209. } catch (err) {
  11210. showToast('Error', err.message, 'error');
  11211. }
  11212. }
  11213. // ----------------- Bridge VLANs -----------------
  11214. function renderBridgeVLANs() {
  11215. const tbody = document.getElementById('bridge-vlans-table-body');
  11216. const empty = document.getElementById('bridge-empty-vlans');
  11217. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11218. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11219. if (!tbody) return;
  11220. tbody.innerHTML = '';
  11221. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11222. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11223. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11224. if (vlans.length === 0) {
  11225. empty?.classList.remove('hidden');
  11226. return;
  11227. }
  11228. empty?.classList.add('hidden');
  11229. vlans.forEach((v, idx) => {
  11230. const tr = document.createElement('tr');
  11231. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11232. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11233. ? 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(' ')
  11234. : '<span class="text-slate-600">none</span>';
  11235. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11236. ? 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(' ')
  11237. : '<span class="text-slate-600">none</span>';
  11238. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11239. tr.innerHTML = `
  11240. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11241. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11242. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11243. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11244. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11245. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11246. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11247. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11248. <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>
  11249. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11250. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11251. </td>
  11252. `;
  11253. tbody.appendChild(tr);
  11254. });
  11255. }
  11256. function openAddBridgeVLANModal() {
  11257. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11258. document.getElementById('bridge-vlan-modal-id').value = '';
  11259. populateBridgeSelect('bridge-vlan-modal-bridge');
  11260. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11261. document.getElementById('bridge-vlan-modal-comment').value = '';
  11262. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11263. updateBridgeVlanPortCheckboxes();
  11264. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11265. }
  11266. function openEditBridgeVLANModal(id) {
  11267. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11268. if (!v) return;
  11269. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11270. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11271. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11272. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11273. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11274. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11275. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11276. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11277. }
  11278. function closeBridgeVlanModal() {
  11279. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11280. }
  11281. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11282. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11283. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11284. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11285. if (!taggedBox || !untaggedBox) return;
  11286. // Ports belonging to the selected bridge
  11287. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11288. if (memberPorts.length === 0) {
  11289. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11290. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11291. return;
  11292. }
  11293. taggedBox.innerHTML = memberPorts.map(p => `
  11294. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11295. <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">
  11296. <span>${p.interface}</span>
  11297. </label>
  11298. `).join('');
  11299. untaggedBox.innerHTML = memberPorts.map(p => `
  11300. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11301. <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">
  11302. <span>${p.interface}</span>
  11303. </label>
  11304. `).join('');
  11305. }
  11306. async function submitSaveBridgeVLAN(e) {
  11307. e.preventDefault();
  11308. const id = document.getElementById('bridge-vlan-modal-id').value;
  11309. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11310. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11311. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11312. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11313. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11314. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11315. try {
  11316. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11317. method: 'POST',
  11318. headers: { 'Content-Type': 'application/json' },
  11319. body: JSON.stringify({
  11320. id,
  11321. bridge,
  11322. vlan_ids: vlanIDs,
  11323. tagged,
  11324. untagged,
  11325. comment,
  11326. disabled
  11327. })
  11328. });
  11329. if (res.ok) {
  11330. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11331. closeBridgeVlanModal();
  11332. loadBridge();
  11333. } else {
  11334. const err = await res.json();
  11335. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11336. }
  11337. } catch (err) {
  11338. showToast('Error', err.message, 'error');
  11339. }
  11340. }
  11341. async function toggleBridgeVLANState(id, disabled) {
  11342. try {
  11343. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11344. method: 'POST',
  11345. headers: { 'Content-Type': 'application/json' },
  11346. body: JSON.stringify({ disabled })
  11347. });
  11348. if (res.ok) loadBridge();
  11349. } catch (err) {
  11350. showToast('Error', err.message, 'error');
  11351. }
  11352. }
  11353. async function deleteBridgeVLAN(id) {
  11354. if (!confirm('Delete this bridge VLAN entry?')) return;
  11355. try {
  11356. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11357. if (res.ok) {
  11358. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11359. loadBridge();
  11360. }
  11361. } catch (err) {
  11362. showToast('Error', err.message, 'error');
  11363. }
  11364. }
  11365. // ----------------- Hosts / MAC Table -----------------
  11366. async function loadBridgeHosts() {
  11367. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11368. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11369. try {
  11370. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11371. const res = await fetch(url);
  11372. if (res.ok) {
  11373. state.bridgeHosts = await res.json();
  11374. renderBridgeHosts();
  11375. }
  11376. } catch (err) {
  11377. console.error('Failed to load bridge hosts:', err);
  11378. }
  11379. }
  11380. function renderBridgeHosts() {
  11381. const tbody = document.getElementById('bridge-hosts-table-body');
  11382. const empty = document.getElementById('bridge-empty-hosts');
  11383. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11384. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11385. if (!tbody) return;
  11386. tbody.innerHTML = '';
  11387. const hosts = (state.bridgeHosts || []).filter(h => {
  11388. if (!search) return true;
  11389. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11390. });
  11391. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11392. if (hosts.length === 0) {
  11393. empty?.classList.remove('hidden');
  11394. return;
  11395. }
  11396. empty?.classList.add('hidden');
  11397. hosts.forEach(h => {
  11398. const tr = document.createElement('tr');
  11399. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11400. let flagBadges = '';
  11401. 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>';
  11402. 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>';
  11403. 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>';
  11404. tr.innerHTML = `
  11405. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11406. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11407. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11408. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11409. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11410. <td class="py-2.5 px-3">${flagBadges}</td>
  11411. `;
  11412. tbody.appendChild(tr);
  11413. });
  11414. }
  11415. async function flushBridgeHosts() {
  11416. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11417. if (!selBridge) {
  11418. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11419. return;
  11420. }
  11421. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11422. try {
  11423. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11424. method: 'POST',
  11425. headers: { 'Content-Type': 'application/json' },
  11426. body: JSON.stringify({ bridge: selBridge })
  11427. });
  11428. if (res.ok) {
  11429. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11430. loadBridgeHosts();
  11431. }
  11432. } catch (err) {
  11433. showToast('Error', err.message, 'error');
  11434. }
  11435. }
  11436. // ----------------- Helpers -----------------
  11437. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11438. const sel = document.getElementById(selectId);
  11439. if (!sel) return;
  11440. const prevVal = currentVal || sel.value;
  11441. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11442. (state.bridges || []).forEach(b => {
  11443. const opt = document.createElement('option');
  11444. opt.value = b.name;
  11445. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11446. if (b.name === prevVal) opt.selected = true;
  11447. sel.appendChild(opt);
  11448. });
  11449. }
  11450. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11451. const sel = document.getElementById(selectId);
  11452. if (!sel) return;
  11453. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11454. // 1. Physical Interfaces
  11455. const grpPhys = document.createElement('optgroup');
  11456. grpPhys.label = 'Physical Interfaces';
  11457. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11458. const opt = document.createElement('option');
  11459. opt.value = i.name;
  11460. opt.innerText = `${i.name} (${i.role || i.type})`;
  11461. if (i.name === currentVal) opt.selected = true;
  11462. grpPhys.appendChild(opt);
  11463. });
  11464. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11465. // 2. VLAN Sub-interfaces
  11466. const grpVlans = document.createElement('optgroup');
  11467. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11468. (state.vlans || []).forEach(v => {
  11469. const opt = document.createElement('option');
  11470. opt.value = v.name;
  11471. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11472. if (v.name === currentVal) opt.selected = true;
  11473. grpVlans.appendChild(opt);
  11474. });
  11475. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11476. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11477. const grpEoip = document.createElement('optgroup');
  11478. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11479. (state.eoipTunnels || []).forEach(t => {
  11480. const opt = document.createElement('option');
  11481. opt.value = t.name;
  11482. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11483. if (t.name === currentVal) opt.selected = true;
  11484. grpEoip.appendChild(opt);
  11485. });
  11486. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11487. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11488. const grpVxlan = document.createElement('optgroup');
  11489. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11490. (state.vxlanTunnels || []).forEach(t => {
  11491. const opt = document.createElement('option');
  11492. opt.value = t.name;
  11493. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11494. if (t.name === currentVal) opt.selected = true;
  11495. grpVxlan.appendChild(opt);
  11496. });
  11497. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11498. }
  11499. // -------------------------------------------------------------
  11500. // DebTik Routing Filters Management (/routing filter)
  11501. // -------------------------------------------------------------
  11502. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11503. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11504. if (!state.rfSort) state.rfSort = {};
  11505. function switchRoutingFilterTab(tab) {
  11506. state.activeRoutingFilterTab = tab;
  11507. const tabs = ['rules', 'community-lists', 'as-lists'];
  11508. tabs.forEach(t => {
  11509. const btn = document.getElementById(`tab-rf-${t}`);
  11510. const content = document.getElementById(`tab-content-rf-${t}`);
  11511. if (btn) {
  11512. if (t === tab) {
  11513. 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';
  11514. } else {
  11515. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11516. }
  11517. }
  11518. if (content) {
  11519. if (t === tab) content.classList.remove('hidden');
  11520. else content.classList.add('hidden');
  11521. }
  11522. });
  11523. const chainContainer = document.getElementById('rf-chain-filter-container');
  11524. if (chainContainer) {
  11525. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11526. else chainContainer.classList.add('hidden');
  11527. }
  11528. renderRoutingFilters();
  11529. }
  11530. function selectFilterRow(tab, id) {
  11531. if (state.selectedFilterRow[tab] === id) {
  11532. delete state.selectedFilterRow[tab];
  11533. } else {
  11534. state.selectedFilterRow[tab] = id;
  11535. }
  11536. if (tab === 'rules') renderRoutingFilterRules();
  11537. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11538. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11539. }
  11540. function openRoutingFilterNewModal() {
  11541. const tab = state.activeRoutingFilterTab || 'rules';
  11542. if (tab === 'rules') openAddRoutingFilterModal();
  11543. else if (tab === 'community-lists') openAddCommunityListModal();
  11544. else if (tab === 'as-lists') openAddASListModal();
  11545. }
  11546. function toggleSelectedRoutingFilter(disabled) {
  11547. const tab = state.activeRoutingFilterTab || 'rules';
  11548. const id = state.selectedFilterRow[tab];
  11549. if (!id) {
  11550. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11551. return;
  11552. }
  11553. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11554. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11555. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11556. }
  11557. function removeSelectedRoutingFilter() {
  11558. const tab = state.activeRoutingFilterTab || 'rules';
  11559. const id = state.selectedFilterRow[tab];
  11560. if (!id) {
  11561. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11562. return;
  11563. }
  11564. if (tab === 'rules') deleteRoutingFilter(id);
  11565. else if (tab === 'community-lists') deleteCommunityList(id);
  11566. else if (tab === 'as-lists') deleteASList(id);
  11567. }
  11568. function searchRoutingFilters(q) {
  11569. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11570. renderRoutingFilters();
  11571. }
  11572. function sortFilterTable(tab, col) {
  11573. if (!state.rfSort) state.rfSort = {};
  11574. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11575. if (state.rfSort[tab].col === col) {
  11576. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11577. } else {
  11578. state.rfSort[tab].col = col;
  11579. state.rfSort[tab].asc = true;
  11580. }
  11581. const asc = state.rfSort[tab].asc;
  11582. let list = [];
  11583. if (tab === 'rules') list = state.routingFilters || [];
  11584. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11585. else if (tab === 'as-lists') list = state.routingASLists || [];
  11586. list.sort((a, b) => {
  11587. let valA = a[col] ?? '';
  11588. let valB = b[col] ?? '';
  11589. if (col === 'flags') {
  11590. valA = a.disabled ? 'X' : 'A';
  11591. valB = b.disabled ? 'X' : 'A';
  11592. }
  11593. if (typeof valA === 'number' && typeof valB === 'number') {
  11594. return asc ? valA - valB : valB - valA;
  11595. }
  11596. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11597. });
  11598. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11599. allCols.forEach(c => {
  11600. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11601. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11602. });
  11603. if (tab === 'rules') renderRoutingFilterRules();
  11604. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11605. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11606. }
  11607. function renderRoutingFilters() {
  11608. const navBadge = document.getElementById('badge-filters-count');
  11609. const allRules = state.routingFilters || [];
  11610. if (navBadge) navBadge.innerText = allRules.length;
  11611. // Populate chain filter select options and datalist
  11612. const chainSelect = document.getElementById('routing-filter-chain-select');
  11613. const chainDatalist = document.getElementById('dl-routing-chains');
  11614. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11615. if (chainSelect) {
  11616. const currentVal = state.filterChainSelected || 'all';
  11617. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11618. uniqueChains.map(ch => {
  11619. const count = allRules.filter(r => r.chain === ch).length;
  11620. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11621. }).join('');
  11622. chainSelect.value = currentVal;
  11623. }
  11624. if (chainDatalist) {
  11625. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11626. }
  11627. renderRoutingFilterRules();
  11628. renderRoutingFilterCommunityLists();
  11629. renderRoutingFilterASLists();
  11630. }
  11631. function filterRoutingFiltersByChain(chain) {
  11632. state.filterChainSelected = chain;
  11633. renderRoutingFilters();
  11634. }
  11635. // -------------------------------------------------------------
  11636. // TAB 1: RULES (/routing filter rule)
  11637. // -------------------------------------------------------------
  11638. function renderRoutingFilterRules() {
  11639. const tbody = document.getElementById('routing-filter-rules-tbody');
  11640. if (!tbody) return;
  11641. const empty = document.getElementById('rf-rules-empty');
  11642. const statusCount = document.getElementById('rf-status-count');
  11643. let list = (state.routingFilters || []).slice();
  11644. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11645. list = list.filter(r => r.chain === state.filterChainSelected);
  11646. }
  11647. const q = state.rfSearchQuery;
  11648. if (q) {
  11649. list = list.filter(r =>
  11650. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11651. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11652. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11653. (r.comment && r.comment.toLowerCase().includes(q))
  11654. );
  11655. }
  11656. if (!state.rfSort?.['rules']) {
  11657. list.sort((a, b) => {
  11658. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11659. return (a.rule_order || 0) - (b.rule_order || 0);
  11660. });
  11661. }
  11662. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11663. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11664. }
  11665. if (list.length === 0) {
  11666. tbody.innerHTML = '';
  11667. if (empty) empty.classList.remove('hidden');
  11668. return;
  11669. }
  11670. if (empty) empty.classList.add('hidden');
  11671. tbody.innerHTML = list.map(r => {
  11672. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11673. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11674. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11675. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11676. let ruleDisplay = '';
  11677. if (r.rule && r.rule.trim() !== '') {
  11678. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11679. } else {
  11680. let conds = [];
  11681. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11682. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11683. let act = r.action || 'accept';
  11684. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11685. }
  11686. return `
  11687. <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'}">
  11688. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11689. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11690. <td class="py-2 px-3">
  11691. <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>
  11692. </td>
  11693. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11694. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11695. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11696. <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>
  11697. <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>
  11698. <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'}">
  11699. ${r.disabled ? 'Enable' : 'Disable'}
  11700. </button>
  11701. <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">
  11702. Edit
  11703. </button>
  11704. <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">
  11705. ✕
  11706. </button>
  11707. </td>
  11708. </tr>
  11709. `;
  11710. }).join('');
  11711. }
  11712. // -------------------------------------------------------------
  11713. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11714. // -------------------------------------------------------------
  11715. function renderRoutingFilterCommunityLists() {
  11716. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11717. if (!tbody) return;
  11718. const empty = document.getElementById('rf-comm-lists-empty');
  11719. const statusCount = document.getElementById('rf-status-count');
  11720. let list = (state.routingCommunityLists || []).slice();
  11721. const q = state.rfSearchQuery;
  11722. if (q) {
  11723. list = list.filter(cl =>
  11724. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11725. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11726. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11727. );
  11728. }
  11729. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11730. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11731. }
  11732. if (list.length === 0) {
  11733. tbody.innerHTML = '';
  11734. if (empty) empty.classList.remove('hidden');
  11735. return;
  11736. }
  11737. if (empty) empty.classList.add('hidden');
  11738. tbody.innerHTML = list.map(cl => {
  11739. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11740. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11741. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11742. const commBadges = (cl.communities || []).map(c =>
  11743. `<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>`
  11744. ).join(' ');
  11745. return `
  11746. <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'}">
  11747. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11748. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11749. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11750. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11751. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11752. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11753. <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'}">
  11754. ${cl.disabled ? 'Enable' : 'Disable'}
  11755. </button>
  11756. <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">
  11757. Edit
  11758. </button>
  11759. <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">
  11760. ✕
  11761. </button>
  11762. </td>
  11763. </tr>
  11764. `;
  11765. }).join('');
  11766. }
  11767. // -------------------------------------------------------------
  11768. // TAB 4: AS LISTS (/routing filter num-list)
  11769. // -------------------------------------------------------------
  11770. function renderRoutingFilterASLists() {
  11771. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11772. if (!tbody) return;
  11773. const empty = document.getElementById('rf-as-lists-empty');
  11774. const statusCount = document.getElementById('rf-status-count');
  11775. let list = (state.routingASLists || []).slice();
  11776. const q = state.rfSearchQuery;
  11777. if (q) {
  11778. list = list.filter(al =>
  11779. (al.name && al.name.toLowerCase().includes(q)) ||
  11780. (al.range && al.range.toLowerCase().includes(q)) ||
  11781. (al.comment && al.comment.toLowerCase().includes(q))
  11782. );
  11783. }
  11784. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11785. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11786. }
  11787. if (list.length === 0) {
  11788. tbody.innerHTML = '';
  11789. if (empty) empty.classList.remove('hidden');
  11790. return;
  11791. }
  11792. if (empty) empty.classList.add('hidden');
  11793. tbody.innerHTML = list.map(al => {
  11794. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11795. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11796. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11797. return `
  11798. <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'}">
  11799. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11800. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11801. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11802. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11803. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11804. <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'}">
  11805. ${al.disabled ? 'Enable' : 'Disable'}
  11806. </button>
  11807. <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">
  11808. Edit
  11809. </button>
  11810. <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">
  11811. ✕
  11812. </button>
  11813. </td>
  11814. </tr>
  11815. `;
  11816. }).join('');
  11817. }
  11818. // -------------------------------------------------------------
  11819. // SNIPPETS & WIZARD HELPERS
  11820. // -------------------------------------------------------------
  11821. function insertRuleSnippet(type) {
  11822. const textarea = document.getElementById('modal-rf-rule');
  11823. if (!textarea) return;
  11824. let snippet = '';
  11825. switch (type) {
  11826. case 'accept-default':
  11827. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11828. break;
  11829. case 'drop-rfc1918':
  11830. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11831. break;
  11832. case 'len-24':
  11833. snippet = 'if (dst-len > 24) { reject; }';
  11834. break;
  11835. case 'local-pref-150':
  11836. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11837. break;
  11838. case 'as-prepend-2':
  11839. snippet = 'set bgp-path-prepend 2; accept;';
  11840. break;
  11841. case 'set-comm':
  11842. snippet = 'set bgp-communities.add 65000:100; accept;';
  11843. break;
  11844. case 'match-comm':
  11845. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11846. break;
  11847. case 'reject-all':
  11848. snippet = 'reject;';
  11849. break;
  11850. }
  11851. if (!snippet) return;
  11852. if (!textarea.value.trim()) {
  11853. textarea.value = snippet;
  11854. } else {
  11855. textarea.value = textarea.value.trim() + '\n' + snippet;
  11856. }
  11857. }
  11858. function generateScriptFromWizard() {
  11859. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11860. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11861. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11862. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11863. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11864. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11865. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11866. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11867. const conds = [];
  11868. if (pfx) {
  11869. if (pfxLen) {
  11870. if (pfxLen.includes('-')) {
  11871. const parts = pfxLen.split('-');
  11872. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11873. } else {
  11874. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11875. }
  11876. } else {
  11877. conds.push(`dst in ${pfx}`);
  11878. }
  11879. }
  11880. if (proto && proto !== 'any') {
  11881. conds.push(`protocol ${proto}`);
  11882. }
  11883. if (asp) {
  11884. conds.push(`bgp-as-path "${asp}"`);
  11885. }
  11886. if (comm) {
  11887. conds.push(`bgp-communities includes ${comm}`);
  11888. }
  11889. const actions = [];
  11890. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11891. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11892. if (act && act !== 'passthrough') {
  11893. actions.push(`${act};`);
  11894. }
  11895. let code = '';
  11896. if (conds.length > 0) {
  11897. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11898. } else {
  11899. code = actions.join(' ');
  11900. }
  11901. const textarea = document.getElementById('modal-rf-rule');
  11902. if (textarea) textarea.value = code;
  11903. }
  11904. // -------------------------------------------------------------
  11905. // MODAL CRUD: RULES (/routing filter rule)
  11906. // -------------------------------------------------------------
  11907. function openAddRoutingFilterModal(defaultChain = '') {
  11908. const form = document.getElementById('routing-filter-form');
  11909. if (form) form.reset();
  11910. const idEl = document.getElementById('modal-rf-id');
  11911. if (idEl) idEl.value = '';
  11912. const titleEl = document.getElementById('modal-rf-title');
  11913. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11914. const chainEl = document.getElementById('modal-rf-chain');
  11915. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11916. const orderEl = document.getElementById('modal-rf-order');
  11917. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11918. const ruleEl = document.getElementById('modal-rf-rule');
  11919. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11920. const disEl = document.getElementById('modal-rf-disabled');
  11921. if (disEl) disEl.checked = false;
  11922. const modal = document.getElementById('modal-routing-filter');
  11923. if (modal) modal.classList.remove('hidden');
  11924. }
  11925. function openEditRoutingFilterModal(id) {
  11926. const r = (state.routingFilters || []).find(item => item.id === id);
  11927. if (!r) return;
  11928. const idEl = document.getElementById('modal-rf-id');
  11929. if (idEl) idEl.value = r.id;
  11930. const titleEl = document.getElementById('modal-rf-title');
  11931. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11932. const chainEl = document.getElementById('modal-rf-chain');
  11933. if (chainEl) chainEl.value = r.chain || '';
  11934. const orderEl = document.getElementById('modal-rf-order');
  11935. if (orderEl) orderEl.value = r.rule_order || 10;
  11936. const ruleEl = document.getElementById('modal-rf-rule');
  11937. if (ruleEl) {
  11938. if (r.rule) {
  11939. ruleEl.value = r.rule;
  11940. } else {
  11941. let conds = [];
  11942. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11943. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11944. let act = r.action || 'accept';
  11945. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11946. }
  11947. }
  11948. const comEl = document.getElementById('modal-rf-comment');
  11949. if (comEl) comEl.value = r.comment || '';
  11950. const disEl = document.getElementById('modal-rf-disabled');
  11951. if (disEl) disEl.checked = !!r.disabled;
  11952. const modal = document.getElementById('modal-routing-filter');
  11953. if (modal) modal.classList.remove('hidden');
  11954. }
  11955. function closeRoutingFilterModal() {
  11956. const modal = document.getElementById('modal-routing-filter');
  11957. if (modal) modal.classList.add('hidden');
  11958. }
  11959. async function submitRoutingFilter(e) {
  11960. if (e) e.preventDefault();
  11961. const payload = {
  11962. id: document.getElementById('modal-rf-id').value,
  11963. chain: document.getElementById('modal-rf-chain').value.trim(),
  11964. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11965. rule: document.getElementById('modal-rf-rule').value.trim(),
  11966. comment: document.getElementById('modal-rf-comment').value.trim(),
  11967. disabled: document.getElementById('modal-rf-disabled').checked
  11968. };
  11969. try {
  11970. const res = await fetch(`${API_BASE}/routing/filters`, {
  11971. method: 'POST',
  11972. headers: { 'Content-Type': 'application/json' },
  11973. body: JSON.stringify(payload)
  11974. });
  11975. if (res.ok) {
  11976. closeRoutingFilterModal();
  11977. showToast('Success', 'Routing filter rule saved', 'success');
  11978. loadDynamicRouting();
  11979. } else {
  11980. const err = await res.json();
  11981. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11982. }
  11983. } catch (err) {
  11984. showToast('Error', err.message, 'error');
  11985. }
  11986. }
  11987. async function applyRoutingFilterForm() {
  11988. const payload = {
  11989. id: document.getElementById('modal-rf-id').value,
  11990. chain: document.getElementById('modal-rf-chain').value.trim(),
  11991. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11992. rule: document.getElementById('modal-rf-rule').value.trim(),
  11993. comment: document.getElementById('modal-rf-comment').value.trim(),
  11994. disabled: document.getElementById('modal-rf-disabled').checked
  11995. };
  11996. try {
  11997. const res = await fetch(`${API_BASE}/routing/filters`, {
  11998. method: 'POST',
  11999. headers: { 'Content-Type': 'application/json' },
  12000. body: JSON.stringify(payload)
  12001. });
  12002. if (res.ok) {
  12003. const data = await res.json();
  12004. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  12005. showToast('Applied', 'Routing filter configuration applied', 'success');
  12006. loadDynamicRouting();
  12007. } else {
  12008. const err = await res.json();
  12009. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  12010. }
  12011. } catch (err) {
  12012. showToast('Error', err.message, 'error');
  12013. }
  12014. }
  12015. async function moveRoutingFilterOrder(id, delta) {
  12016. const list = state.routingFilters || [];
  12017. const idx = list.findIndex(r => r.id === id);
  12018. if (idx < 0) return;
  12019. const targetIdx = idx + delta;
  12020. if (targetIdx < 0 || targetIdx >= list.length) return;
  12021. const currentOrder = list[idx].rule_order || 10;
  12022. const targetOrder = list[targetIdx].rule_order || 20;
  12023. list[idx].rule_order = targetOrder;
  12024. list[targetIdx].rule_order = currentOrder;
  12025. try {
  12026. await fetch(`${API_BASE}/routing/filters`, {
  12027. method: 'POST',
  12028. headers: { 'Content-Type': 'application/json' },
  12029. body: JSON.stringify(list[idx])
  12030. });
  12031. await fetch(`${API_BASE}/routing/filters`, {
  12032. method: 'POST',
  12033. headers: { 'Content-Type': 'application/json' },
  12034. body: JSON.stringify(list[targetIdx])
  12035. });
  12036. loadDynamicRouting();
  12037. } catch (e) {
  12038. console.error('Reorder error:', e);
  12039. }
  12040. }
  12041. async function deleteRoutingFilter(id) {
  12042. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  12043. try {
  12044. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12045. if (res.ok) {
  12046. showToast('Deleted', 'Routing filter rule removed', 'info');
  12047. loadDynamicRouting();
  12048. } else {
  12049. const err = await res.json();
  12050. showToast('Error', err.error || 'Failed to delete rule', 'error');
  12051. }
  12052. } catch (err) {
  12053. showToast('Error', err.message, 'error');
  12054. }
  12055. }
  12056. async function toggleRoutingFilterState(id, disabled) {
  12057. try {
  12058. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  12059. method: 'POST',
  12060. headers: { 'Content-Type': 'application/json' },
  12061. body: JSON.stringify({ disabled })
  12062. });
  12063. if (res.ok) {
  12064. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12065. loadDynamicRouting();
  12066. } else {
  12067. const err = await res.json();
  12068. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  12069. }
  12070. } catch (err) {
  12071. showToast('Error', err.message, 'error');
  12072. }
  12073. }
  12074. // -------------------------------------------------------------
  12075. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12076. // -------------------------------------------------------------
  12077. function openAddCommunityListModal() {
  12078. document.getElementById('modal-rf-cl-id').value = '';
  12079. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12080. document.getElementById('modal-rf-cl-name').value = '';
  12081. document.getElementById('modal-rf-cl-communities').value = '';
  12082. document.getElementById('modal-rf-cl-regexp').value = '';
  12083. document.getElementById('modal-rf-cl-comment').value = '';
  12084. document.getElementById('modal-rf-cl-disabled').checked = false;
  12085. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12086. }
  12087. function openEditCommunityListModal(id) {
  12088. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12089. if (!cl) return;
  12090. document.getElementById('modal-rf-cl-id').value = cl.id;
  12091. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12092. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12093. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12094. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12095. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12096. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12097. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12098. }
  12099. function closeCommunityListModal() {
  12100. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12101. }
  12102. async function submitCommunityList(e) {
  12103. e.preventDefault();
  12104. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12105. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12106. const payload = {
  12107. id: document.getElementById('modal-rf-cl-id').value,
  12108. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12109. communities: comms,
  12110. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12111. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12112. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12113. };
  12114. try {
  12115. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12116. method: 'POST',
  12117. headers: { 'Content-Type': 'application/json' },
  12118. body: JSON.stringify(payload)
  12119. });
  12120. if (res.ok) {
  12121. closeCommunityListModal();
  12122. showToast('Success', 'Community list saved', 'success');
  12123. loadDynamicRouting();
  12124. } else {
  12125. const err = await res.json();
  12126. showToast('Error', err.error || 'Failed to save community list', 'error');
  12127. }
  12128. } catch (err) {
  12129. showToast('Error', err.message, 'error');
  12130. }
  12131. }
  12132. async function deleteCommunityList(id) {
  12133. if (!confirm('Are you sure you want to delete this community list?')) return;
  12134. try {
  12135. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12136. if (res.ok) {
  12137. showToast('Deleted', 'Community list removed', 'info');
  12138. loadDynamicRouting();
  12139. } else {
  12140. const err = await res.json();
  12141. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12142. }
  12143. } catch (err) {
  12144. showToast('Error', err.message, 'error');
  12145. }
  12146. }
  12147. async function toggleCommunityListState(id, disabled) {
  12148. try {
  12149. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12150. method: 'POST',
  12151. headers: { 'Content-Type': 'application/json' },
  12152. body: JSON.stringify({ disabled })
  12153. });
  12154. if (res.ok) {
  12155. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12156. loadDynamicRouting();
  12157. } else {
  12158. const err = await res.json();
  12159. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12160. }
  12161. } catch (err) {
  12162. showToast('Error', err.message, 'error');
  12163. }
  12164. }
  12165. // -------------------------------------------------------------
  12166. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12167. // -------------------------------------------------------------
  12168. function openAddASListModal() {
  12169. document.getElementById('modal-rf-al-id').value = '';
  12170. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12171. document.getElementById('modal-rf-al-name').value = '';
  12172. document.getElementById('modal-rf-al-range').value = '';
  12173. document.getElementById('modal-rf-al-comment').value = '';
  12174. document.getElementById('modal-rf-al-disabled').checked = false;
  12175. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12176. }
  12177. function openEditASListModal(id) {
  12178. const al = (state.routingASLists || []).find(item => item.id === id);
  12179. if (!al) return;
  12180. document.getElementById('modal-rf-al-id').value = al.id;
  12181. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12182. document.getElementById('modal-rf-al-name').value = al.name || '';
  12183. document.getElementById('modal-rf-al-range').value = al.range || '';
  12184. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12185. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12186. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12187. }
  12188. function closeASListModal() {
  12189. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12190. }
  12191. async function submitASList(e) {
  12192. e.preventDefault();
  12193. const payload = {
  12194. id: document.getElementById('modal-rf-al-id').value,
  12195. name: document.getElementById('modal-rf-al-name').value.trim(),
  12196. range: document.getElementById('modal-rf-al-range').value.trim(),
  12197. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12198. disabled: document.getElementById('modal-rf-al-disabled').checked
  12199. };
  12200. try {
  12201. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12202. method: 'POST',
  12203. headers: { 'Content-Type': 'application/json' },
  12204. body: JSON.stringify(payload)
  12205. });
  12206. if (res.ok) {
  12207. closeASListModal();
  12208. showToast('Success', 'AS number list saved', 'success');
  12209. loadDynamicRouting();
  12210. } else {
  12211. const err = await res.json();
  12212. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12213. }
  12214. } catch (err) {
  12215. showToast('Error', err.message, 'error');
  12216. }
  12217. }
  12218. async function deleteASList(id) {
  12219. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12220. try {
  12221. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12222. if (res.ok) {
  12223. showToast('Deleted', 'AS list removed', 'info');
  12224. loadDynamicRouting();
  12225. } else {
  12226. const err = await res.json();
  12227. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12228. }
  12229. } catch (err) {
  12230. showToast('Error', err.message, 'error');
  12231. }
  12232. }
  12233. async function toggleASListState(id, disabled) {
  12234. try {
  12235. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12236. method: 'POST',
  12237. headers: { 'Content-Type': 'application/json' },
  12238. body: JSON.stringify({ disabled })
  12239. });
  12240. if (res.ok) {
  12241. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12242. loadDynamicRouting();
  12243. } else {
  12244. const err = await res.json();
  12245. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12246. }
  12247. } catch (err) {
  12248. showToast('Error', err.message, 'error');
  12249. }
  12250. }
  12251. // ==========================================
  12252. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12253. // ==========================================
  12254. function loadToolsView() {
  12255. populateToolsInterfaces();
  12256. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12257. }
  12258. function populateToolsInterfaces() {
  12259. const pingSel = document.getElementById('tools-ping-iface');
  12260. const traceSel = document.getElementById('tools-tr-iface');
  12261. let opts = '<option value="">Auto (Default Route)</option>';
  12262. if (Array.isArray(state.interfaces)) {
  12263. state.interfaces.forEach(iface => {
  12264. if (iface.name) {
  12265. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12266. }
  12267. });
  12268. }
  12269. if (pingSel) {
  12270. const cur = pingSel.value;
  12271. pingSel.innerHTML = opts;
  12272. if (cur) pingSel.value = cur;
  12273. }
  12274. if (traceSel) {
  12275. const cur = traceSel.value;
  12276. traceSel.innerHTML = opts;
  12277. if (cur) traceSel.value = cur;
  12278. }
  12279. }
  12280. function switchToolsSubTab(subTab) {
  12281. state.activeToolsSubTab = subTab;
  12282. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12283. tabs.forEach(t => {
  12284. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12285. const view = document.getElementById(`tools-view-${t}`);
  12286. if (btn) {
  12287. if (t === subTab) {
  12288. 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';
  12289. } else {
  12290. 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';
  12291. }
  12292. }
  12293. if (view) {
  12294. if (t === subTab) {
  12295. view.classList.remove('hidden');
  12296. } else {
  12297. view.classList.add('hidden');
  12298. }
  12299. }
  12300. });
  12301. }
  12302. function setPortPreset(port) {
  12303. const input = document.getElementById('tools-port-num');
  12304. if (input) input.value = port;
  12305. }
  12306. let pingAbortController = null;
  12307. let tracerouteAbortController = null;
  12308. function clearPingTable() {
  12309. const tbody = document.getElementById('tools-ping-tbody');
  12310. if (tbody) tbody.innerHTML = '';
  12311. const rawEl = document.getElementById('tools-ping-raw');
  12312. if (rawEl) rawEl.innerText = '';
  12313. const sentEl = document.getElementById('tools-ping-stat-sent');
  12314. if (sentEl) sentEl.innerText = '0';
  12315. const recvEl = document.getElementById('tools-ping-stat-recv');
  12316. if (recvEl) recvEl.innerText = '0';
  12317. const lossEl = document.getElementById('tools-ping-stat-loss');
  12318. if (lossEl) lossEl.innerText = '0%';
  12319. const avgEl = document.getElementById('tools-ping-stat-avg');
  12320. if (avgEl) avgEl.innerText = '0 ms';
  12321. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12322. if (minMaxEl) minMaxEl.innerText = '-';
  12323. const badge = document.getElementById('tools-ping-status-badge');
  12324. if (badge) {
  12325. badge.className = '';
  12326. badge.innerText = '';
  12327. }
  12328. }
  12329. function clearTracerouteTable() {
  12330. const tbody = document.getElementById('tools-tr-tbody');
  12331. if (tbody) tbody.innerHTML = '';
  12332. const rawEl = document.getElementById('tools-tr-raw');
  12333. if (rawEl) rawEl.innerText = '';
  12334. const statHops = document.getElementById('tools-tr-hops-count');
  12335. if (statHops) statHops.innerText = '0 Hops';
  12336. }
  12337. function resetPingButton() {
  12338. const btn = document.getElementById('tools-ping-btn');
  12339. const btnText = document.getElementById('tools-ping-btn-text');
  12340. const spinner = document.getElementById('tools-ping-spinner');
  12341. if (btn) {
  12342. btn.disabled = false;
  12343. 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';
  12344. }
  12345. if (btnText) btnText.innerText = 'Start Ping';
  12346. if (spinner) spinner.classList.add('hidden');
  12347. }
  12348. function setPingRunningButton() {
  12349. const btn = document.getElementById('tools-ping-btn');
  12350. const btnText = document.getElementById('tools-ping-btn-text');
  12351. const spinner = document.getElementById('tools-ping-spinner');
  12352. if (btn) {
  12353. btn.disabled = false;
  12354. 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';
  12355. }
  12356. if (btnText) btnText.innerText = 'Stop Ping';
  12357. if (spinner) spinner.classList.remove('hidden');
  12358. }
  12359. function resetTracerouteButton() {
  12360. const btn = document.getElementById('tools-tr-btn');
  12361. const btnText = document.getElementById('tools-tr-btn-text');
  12362. const spinner = document.getElementById('tools-tr-spinner');
  12363. if (btn) {
  12364. btn.disabled = false;
  12365. 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';
  12366. }
  12367. if (btnText) btnText.innerText = 'Start Traceroute';
  12368. if (spinner) spinner.classList.add('hidden');
  12369. }
  12370. function setTracerouteRunningButton() {
  12371. const btn = document.getElementById('tools-tr-btn');
  12372. const btnText = document.getElementById('tools-tr-btn-text');
  12373. const spinner = document.getElementById('tools-tr-spinner');
  12374. if (btn) {
  12375. btn.disabled = false;
  12376. 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';
  12377. }
  12378. if (btnText) btnText.innerText = 'Stop Traceroute';
  12379. if (spinner) spinner.classList.remove('hidden');
  12380. }
  12381. async function executePing(e) {
  12382. if (e) e.preventDefault();
  12383. // If already running, clicking the button stops the stream!
  12384. if (pingAbortController) {
  12385. pingAbortController.abort();
  12386. pingAbortController = null;
  12387. resetPingButton();
  12388. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12389. return;
  12390. }
  12391. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12392. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12393. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12394. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12395. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12396. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12397. if (!target) {
  12398. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12399. return;
  12400. }
  12401. clearPingTable();
  12402. const resCard = document.getElementById('tools-ping-results');
  12403. if (resCard) resCard.classList.remove('hidden');
  12404. pingAbortController = new AbortController();
  12405. setPingRunningButton();
  12406. try {
  12407. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12408. method: 'POST',
  12409. headers: { 'Content-Type': 'application/json' },
  12410. body: JSON.stringify({
  12411. target,
  12412. count,
  12413. size,
  12414. timeout,
  12415. interface: iface,
  12416. dont_frag: dontFrag
  12417. }),
  12418. signal: pingAbortController.signal
  12419. });
  12420. if (!res.ok) {
  12421. const errText = await res.text();
  12422. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12423. resetPingButton();
  12424. pingAbortController = null;
  12425. return;
  12426. }
  12427. const reader = res.body.getReader();
  12428. const decoder = new TextDecoder('utf-8');
  12429. let buffer = '';
  12430. while (true) {
  12431. const { done, value } = await reader.read();
  12432. if (done) break;
  12433. buffer += decoder.decode(value, { stream: true });
  12434. const blocks = buffer.split('\n\n');
  12435. buffer = blocks.pop() || '';
  12436. for (const block of blocks) {
  12437. const trimmed = block.trim();
  12438. if (!trimmed) continue;
  12439. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12440. try {
  12441. const evt = JSON.parse(line);
  12442. handleLivePingEvent(evt);
  12443. } catch (parseErr) {
  12444. console.warn('Ping SSE parse error:', parseErr, line);
  12445. }
  12446. }
  12447. }
  12448. } catch (err) {
  12449. if (err.name === 'AbortError') {
  12450. // User aborted normally
  12451. } else {
  12452. showToast('Ping Error', err.message, 'error');
  12453. }
  12454. } finally {
  12455. pingAbortController = null;
  12456. resetPingButton();
  12457. }
  12458. }
  12459. function handleLivePingEvent(evt) {
  12460. const sentEl = document.getElementById('tools-ping-stat-sent');
  12461. const recvEl = document.getElementById('tools-ping-stat-recv');
  12462. const lossEl = document.getElementById('tools-ping-stat-loss');
  12463. const avgEl = document.getElementById('tools-ping-stat-avg');
  12464. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12465. const badge = document.getElementById('tools-ping-status-badge');
  12466. const tbody = document.getElementById('tools-ping-tbody');
  12467. const rawEl = document.getElementById('tools-ping-raw');
  12468. if (evt.raw && rawEl) {
  12469. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12470. rawEl.scrollTop = rawEl.scrollHeight;
  12471. }
  12472. if (evt.type === 'reply') {
  12473. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12474. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12475. if (lossEl && evt.packet_loss_pct !== undefined) {
  12476. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12477. lossEl.className = evt.packet_loss_pct === 0
  12478. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12479. : (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');
  12480. }
  12481. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12482. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12483. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12484. }
  12485. if (badge) {
  12486. if (evt.packet_loss_pct === 0) {
  12487. 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';
  12488. badge.innerText = '100% OK';
  12489. } else {
  12490. 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';
  12491. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12492. }
  12493. }
  12494. if (tbody) {
  12495. const tr = document.createElement('tr');
  12496. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12497. tr.innerHTML = `
  12498. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12499. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12500. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12501. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12502. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12503. <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>
  12504. `;
  12505. tbody.appendChild(tr);
  12506. }
  12507. } else if (evt.type === 'timeout') {
  12508. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12509. if (lossEl && evt.packet_loss_pct !== undefined) {
  12510. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12511. 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';
  12512. }
  12513. if (badge) {
  12514. 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';
  12515. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12516. }
  12517. if (tbody) {
  12518. const tr = document.createElement('tr');
  12519. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12520. tr.innerHTML = `
  12521. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12522. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12523. <td class="py-2 px-3 text-slate-600">--</td>
  12524. <td class="py-2 px-3 text-slate-600">--</td>
  12525. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12526. <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>
  12527. `;
  12528. tbody.appendChild(tr);
  12529. }
  12530. } else if (evt.type === 'unreach') {
  12531. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12532. if (lossEl && evt.packet_loss_pct !== undefined) {
  12533. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12534. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12535. }
  12536. if (badge) {
  12537. 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';
  12538. badge.innerText = 'UNREACHABLE';
  12539. }
  12540. if (tbody) {
  12541. const tr = document.createElement('tr');
  12542. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12543. tr.innerHTML = `
  12544. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12545. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12546. <td class="py-2 px-3 text-slate-600">--</td>
  12547. <td class="py-2 px-3 text-slate-600">--</td>
  12548. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12549. <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>
  12550. `;
  12551. tbody.appendChild(tr);
  12552. }
  12553. } else if (evt.type === 'stats') {
  12554. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12555. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12556. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12557. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12558. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12559. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12560. }
  12561. } else if (evt.type === 'done') {
  12562. 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');
  12563. }
  12564. }
  12565. async function executeTraceroute(e) {
  12566. if (e) e.preventDefault();
  12567. if (tracerouteAbortController) {
  12568. tracerouteAbortController.abort();
  12569. tracerouteAbortController = null;
  12570. resetTracerouteButton();
  12571. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12572. return;
  12573. }
  12574. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12575. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12576. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12577. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12578. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12579. if (!target) {
  12580. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12581. return;
  12582. }
  12583. clearTracerouteTable();
  12584. const resCard = document.getElementById('tools-tr-results');
  12585. if (resCard) resCard.classList.remove('hidden');
  12586. tracerouteAbortController = new AbortController();
  12587. setTracerouteRunningButton();
  12588. try {
  12589. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12590. method: 'POST',
  12591. headers: { 'Content-Type': 'application/json' },
  12592. body: JSON.stringify({
  12593. target,
  12594. max_hops: maxHops,
  12595. protocol,
  12596. interface: iface,
  12597. resolve
  12598. }),
  12599. signal: tracerouteAbortController.signal
  12600. });
  12601. if (!res.ok) {
  12602. const errText = await res.text();
  12603. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12604. resetTracerouteButton();
  12605. tracerouteAbortController = null;
  12606. return;
  12607. }
  12608. const reader = res.body.getReader();
  12609. const decoder = new TextDecoder('utf-8');
  12610. let buffer = '';
  12611. while (true) {
  12612. const { done, value } = await reader.read();
  12613. if (done) break;
  12614. buffer += decoder.decode(value, { stream: true });
  12615. const blocks = buffer.split('\n\n');
  12616. buffer = blocks.pop() || '';
  12617. for (const block of blocks) {
  12618. const trimmed = block.trim();
  12619. if (!trimmed) continue;
  12620. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12621. try {
  12622. const evt = JSON.parse(line);
  12623. handleLiveTracerouteEvent(evt);
  12624. } catch (parseErr) {
  12625. console.warn('Traceroute SSE parse error:', parseErr, line);
  12626. }
  12627. }
  12628. }
  12629. } catch (err) {
  12630. if (err.name === 'AbortError') {
  12631. // User aborted normally
  12632. } else {
  12633. showToast('Traceroute Error', err.message, 'error');
  12634. }
  12635. } finally {
  12636. tracerouteAbortController = null;
  12637. resetTracerouteButton();
  12638. }
  12639. }
  12640. function handleLiveTracerouteEvent(evt) {
  12641. const statHops = document.getElementById('tools-tr-hops-count');
  12642. const tbody = document.getElementById('tools-tr-tbody');
  12643. const rawEl = document.getElementById('tools-tr-raw');
  12644. if (evt.raw && rawEl) {
  12645. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12646. rawEl.scrollTop = rawEl.scrollHeight;
  12647. }
  12648. if (evt.hops_count !== undefined && statHops) {
  12649. statHops.innerText = `${evt.hops_count} Hops`;
  12650. }
  12651. if (evt.type === 'hop' && evt.hop && tbody) {
  12652. const h = evt.hop;
  12653. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12654. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12655. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12656. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12657. const tr = document.createElement('tr');
  12658. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12659. tr.innerHTML = `
  12660. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12661. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12662. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12663. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12664. <td class="py-2.5 px-3 text-right">
  12665. ${isTimeout
  12666. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12667. : '<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>'}
  12668. </td>
  12669. `;
  12670. tbody.appendChild(tr);
  12671. } else if (evt.type === 'done') {
  12672. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12673. }
  12674. }
  12675. async function executeMTR(e) {
  12676. if (e) e.preventDefault();
  12677. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12678. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12679. if (!target) {
  12680. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12681. return;
  12682. }
  12683. const btn = document.getElementById('tools-mtr-btn');
  12684. const spinner = document.getElementById('tools-mtr-spinner');
  12685. if (btn) btn.disabled = true;
  12686. if (spinner) spinner.classList.remove('hidden');
  12687. try {
  12688. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12689. method: 'POST',
  12690. headers: { 'Content-Type': 'application/json' },
  12691. body: JSON.stringify({ target, count: cycles })
  12692. });
  12693. const data = await res.json();
  12694. if (!res.ok) {
  12695. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12696. return;
  12697. }
  12698. const resCard = document.getElementById('tools-mtr-results');
  12699. if (resCard) resCard.classList.remove('hidden');
  12700. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12701. const statHops = document.getElementById('tools-mtr-hops-count');
  12702. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12703. const tbody = document.getElementById('tools-mtr-tbody');
  12704. if (tbody) {
  12705. if (hopsCount > 0) {
  12706. tbody.innerHTML = data.hops.map(h => {
  12707. 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');
  12708. return `
  12709. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12710. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12711. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12712. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12713. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12714. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12715. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12716. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12717. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12718. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12719. </tr>
  12720. `;
  12721. }).join('');
  12722. } else {
  12723. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12724. }
  12725. }
  12726. const rawEl = document.getElementById('tools-mtr-raw');
  12727. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12728. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12729. } catch (err) {
  12730. showToast('MTR Error', err.message, 'error');
  12731. } finally {
  12732. if (btn) btn.disabled = false;
  12733. if (spinner) spinner.classList.add('hidden');
  12734. }
  12735. }
  12736. async function executeDNS(e) {
  12737. if (e) e.preventDefault();
  12738. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12739. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12740. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12741. if (!domain) {
  12742. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12743. return;
  12744. }
  12745. const btn = document.getElementById('tools-dns-btn');
  12746. const spinner = document.getElementById('tools-dns-spinner');
  12747. if (btn) btn.disabled = true;
  12748. if (spinner) spinner.classList.remove('hidden');
  12749. try {
  12750. const res = await fetch(`${API_BASE}/tools/dns`, {
  12751. method: 'POST',
  12752. headers: { 'Content-Type': 'application/json' },
  12753. body: JSON.stringify({ domain, type, server })
  12754. });
  12755. const data = await res.json();
  12756. if (!res.ok) {
  12757. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12758. return;
  12759. }
  12760. const resCard = document.getElementById('tools-dns-results');
  12761. if (resCard) resCard.classList.remove('hidden');
  12762. const metaEl = document.getElementById('tools-dns-meta');
  12763. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12764. const tbody = document.getElementById('tools-dns-tbody');
  12765. if (tbody) {
  12766. if (Array.isArray(data.records) && data.records.length > 0) {
  12767. tbody.innerHTML = data.records.map(r => `
  12768. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12769. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12770. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12771. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12772. <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>
  12773. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12774. </tr>
  12775. `).join('');
  12776. } else {
  12777. 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>`;
  12778. }
  12779. }
  12780. const rawEl = document.getElementById('tools-dns-raw');
  12781. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12782. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12783. } catch (err) {
  12784. showToast('DNS Error', err.message, 'error');
  12785. } finally {
  12786. if (btn) btn.disabled = false;
  12787. if (spinner) spinner.classList.add('hidden');
  12788. }
  12789. }
  12790. async function executePortProbe(e) {
  12791. if (e) e.preventDefault();
  12792. const target = document.getElementById('tools-port-target')?.value?.trim();
  12793. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12794. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12795. if (!target || !port) {
  12796. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12797. return;
  12798. }
  12799. const btn = document.getElementById('tools-port-btn');
  12800. const spinner = document.getElementById('tools-port-spinner');
  12801. if (btn) btn.disabled = true;
  12802. if (spinner) spinner.classList.remove('hidden');
  12803. try {
  12804. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12805. method: 'POST',
  12806. headers: { 'Content-Type': 'application/json' },
  12807. body: JSON.stringify({ target, port, timeout })
  12808. });
  12809. const data = await res.json();
  12810. if (!res.ok) {
  12811. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12812. return;
  12813. }
  12814. const resCard = document.getElementById('tools-port-results');
  12815. if (resCard) resCard.classList.remove('hidden');
  12816. const banner = document.getElementById('tools-port-banner');
  12817. const icon = document.getElementById('tools-port-icon');
  12818. const title = document.getElementById('tools-port-title');
  12819. const sub = document.getElementById('tools-port-sub');
  12820. const latency = document.getElementById('tools-port-latency');
  12821. if (data.open) {
  12822. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12823. if (icon) {
  12824. 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';
  12825. icon.innerText = '✓';
  12826. }
  12827. if (title) {
  12828. title.className = 'text-sm font-bold text-emerald-300';
  12829. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12830. }
  12831. if (sub) {
  12832. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12833. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12834. }
  12835. if (latency) {
  12836. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12837. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12838. }
  12839. } else {
  12840. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12841. if (icon) {
  12842. 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';
  12843. icon.innerText = '✕';
  12844. }
  12845. if (title) {
  12846. title.className = 'text-sm font-bold text-rose-300';
  12847. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12848. }
  12849. if (sub) {
  12850. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12851. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12852. }
  12853. if (latency) {
  12854. latency.className = 'text-base font-bold font-mono text-slate-500';
  12855. latency.innerText = '--';
  12856. }
  12857. }
  12858. const rawEl = document.getElementById('tools-port-raw');
  12859. 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'}`);
  12860. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12861. } catch (err) {
  12862. showToast('Probe Error', err.message, 'error');
  12863. } finally {
  12864. if (btn) btn.disabled = false;
  12865. if (spinner) spinner.classList.add('hidden');
  12866. }
  12867. }
  12868. // ==========================================
  12869. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12870. // ==========================================
  12871. async function loadDHCPClients(showToastMsg = false) {
  12872. try {
  12873. const [clientsRes, sumRes] = await Promise.all([
  12874. fetch(`${API_BASE}/dhcp/clients`),
  12875. fetch(`${API_BASE}/dhcp/clients/summary`)
  12876. ]);
  12877. if (clientsRes.ok) {
  12878. state.dhcpClients = await clientsRes.json();
  12879. }
  12880. if (sumRes.ok) {
  12881. state.dhcpSummary = await sumRes.json();
  12882. }
  12883. renderDHCPClients();
  12884. updateDHCPSummaryCards();
  12885. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12886. if (bDhcp && state.dhcpSummary) {
  12887. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12888. }
  12889. if (showToastMsg) {
  12890. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12891. }
  12892. } catch (err) {
  12893. console.error('Failed to load DHCP clients:', err);
  12894. if (showToastMsg) {
  12895. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12896. }
  12897. }
  12898. }
  12899. function updateDHCPSummaryCards() {
  12900. const sum = state.dhcpSummary || {
  12901. total_clients: (state.dhcpClients || []).length,
  12902. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12903. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12904. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12905. };
  12906. const totalEl = document.getElementById('dhcp-stat-total');
  12907. const boundEl = document.getElementById('dhcp-stat-bound');
  12908. const searchEl = document.getElementById('dhcp-stat-searching');
  12909. const disEl = document.getElementById('dhcp-stat-disabled');
  12910. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12911. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12912. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12913. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12914. }
  12915. function renderDHCPClients() {
  12916. const tbody = document.getElementById('dhcp-clients-tbody');
  12917. const emptyState = document.getElementById('dhcp-clients-empty');
  12918. if (!tbody) return;
  12919. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12920. if (clients.length === 0) {
  12921. tbody.innerHTML = '';
  12922. if (emptyState) emptyState.classList.remove('hidden');
  12923. return;
  12924. }
  12925. if (emptyState) emptyState.classList.add('hidden');
  12926. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12927. if (tbody.dataset.sig === sig) return;
  12928. tbody.dataset.sig = sig;
  12929. tbody.innerHTML = clients.map(c => {
  12930. let statusBadge = '';
  12931. if (!c.enabled) {
  12932. 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>';
  12933. } else if (c.status === 'bound') {
  12934. 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>';
  12935. } else if (c.status === 'searching') {
  12936. 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>';
  12937. } else if (c.status === 'stopped') {
  12938. 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>';
  12939. } else {
  12940. 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>`;
  12941. }
  12942. 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>';
  12943. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12944. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12945. 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>';
  12946. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12947. // Option flags
  12948. const flags = [];
  12949. 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>');
  12950. 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>');
  12951. 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>');
  12952. 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>`);
  12953. return `
  12954. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12955. <td class="py-3 px-4">
  12956. <div class="flex items-center gap-2">
  12957. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12958. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12959. </div>
  12960. </td>
  12961. <td class="py-3 px-4">${statusBadge}</td>
  12962. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12963. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12964. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12965. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12966. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12967. <td class="py-3 px-4">
  12968. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12969. </td>
  12970. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12971. ${c.enabled ? `
  12972. <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>
  12973. <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>
  12974. <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>
  12975. ` : `
  12976. <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>
  12977. `}
  12978. <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>
  12979. <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>
  12980. </td>
  12981. </tr>
  12982. `;
  12983. }).join('');
  12984. }
  12985. function openDHCPClientModal(clientId = null) {
  12986. const modal = document.getElementById('modal-dhcp-client');
  12987. if (!modal) return;
  12988. const title = document.getElementById('modal-dhcp-title');
  12989. const idInput = document.getElementById('modal-dhcp-id');
  12990. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12991. const distInput = document.getElementById('modal-dhcp-distance');
  12992. const commentInput = document.getElementById('modal-dhcp-comment');
  12993. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12994. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12995. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12996. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12997. // Populate interfaces
  12998. if (ifaceSelect) {
  12999. let opts = '<option value="">Select interface...</option>';
  13000. const allIfaces = state.interfaces || [];
  13001. const allVlans = state.vlans || [];
  13002. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  13003. // Group 1: Physical & Bridge Interfaces
  13004. opts += '<optgroup label="Physical & Bridge Interfaces">';
  13005. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  13006. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  13007. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  13008. });
  13009. opts += '</optgroup>';
  13010. // Group 2: VLAN Interfaces
  13011. if (allVlans.length > 0) {
  13012. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  13013. allVlans.forEach(v => {
  13014. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  13015. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  13016. });
  13017. opts += '</optgroup>';
  13018. }
  13019. ifaceSelect.innerHTML = opts;
  13020. }
  13021. if (clientId) {
  13022. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  13023. if (client) {
  13024. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  13025. if (idInput) idInput.value = client.id;
  13026. if (ifaceSelect) {
  13027. ifaceSelect.value = client.interface;
  13028. ifaceSelect.disabled = true; // interface cannot be changed on edit
  13029. }
  13030. if (distInput) distInput.value = client.default_route_distance || 1;
  13031. if (commentInput) commentInput.value = client.comment || '';
  13032. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  13033. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  13034. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  13035. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  13036. }
  13037. } else {
  13038. if (title) title.innerText = 'Add DHCP Client';
  13039. if (idInput) idInput.value = '';
  13040. if (ifaceSelect) {
  13041. ifaceSelect.value = '';
  13042. ifaceSelect.disabled = false;
  13043. }
  13044. if (distInput) distInput.value = 1;
  13045. if (commentInput) commentInput.value = '';
  13046. if (defRouteCheck) defRouteCheck.checked = true;
  13047. if (peerDnsCheck) peerDnsCheck.checked = true;
  13048. if (peerNtpCheck) peerNtpCheck.checked = true;
  13049. if (enabledCheck) enabledCheck.checked = true;
  13050. }
  13051. modal.classList.remove('hidden');
  13052. }
  13053. function openDHCPClientModalForIface(ifaceName) {
  13054. openDHCPClientModal();
  13055. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13056. if (ifaceSelect && ifaceName) {
  13057. ifaceSelect.value = ifaceName;
  13058. }
  13059. }
  13060. function closeDHCPClientModal() {
  13061. const modal = document.getElementById('modal-dhcp-client');
  13062. if (modal) modal.classList.add('hidden');
  13063. }
  13064. async function submitSaveDHCPClient(e) {
  13065. if (e) e.preventDefault();
  13066. const id = document.getElementById('modal-dhcp-id')?.value;
  13067. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  13068. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  13069. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13070. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13071. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13072. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13073. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13074. if (!id && !iface) {
  13075. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13076. return;
  13077. }
  13078. try {
  13079. let res;
  13080. if (id) {
  13081. // PUT update
  13082. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13083. method: 'PUT',
  13084. headers: { 'Content-Type': 'application/json' },
  13085. body: JSON.stringify({
  13086. enabled,
  13087. add_default_route: defRoute,
  13088. default_route_distance: distance,
  13089. use_peer_dns: peerDns,
  13090. use_peer_ntp: peerNtp,
  13091. comment
  13092. })
  13093. });
  13094. } else {
  13095. // POST create
  13096. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13097. method: 'POST',
  13098. headers: { 'Content-Type': 'application/json' },
  13099. body: JSON.stringify({
  13100. interface: iface,
  13101. enabled,
  13102. add_default_route: defRoute,
  13103. default_route_distance: distance,
  13104. use_peer_dns: peerDns,
  13105. use_peer_ntp: peerNtp,
  13106. comment
  13107. })
  13108. });
  13109. }
  13110. const data = await res.json();
  13111. if (!res.ok) {
  13112. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13113. return;
  13114. }
  13115. closeDHCPClientModal();
  13116. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13117. await loadDHCPClients();
  13118. fetchData(); // refresh interfaces list with new lease/status
  13119. } catch (err) {
  13120. showToast('Error', err.message, 'error');
  13121. }
  13122. }
  13123. async function toggleDHCPClientState(id, enabled) {
  13124. try {
  13125. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13126. method: 'POST',
  13127. headers: { 'Content-Type': 'application/json' },
  13128. body: JSON.stringify({ enabled })
  13129. });
  13130. const data = await res.json();
  13131. if (!res.ok) {
  13132. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13133. return;
  13134. }
  13135. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13136. await loadDHCPClients();
  13137. fetchData();
  13138. } catch (err) {
  13139. showToast('Error', err.message, 'error');
  13140. }
  13141. }
  13142. async function renewDHCPClient(id) {
  13143. try {
  13144. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13145. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13146. method: 'POST'
  13147. });
  13148. const data = await res.json();
  13149. if (!res.ok) {
  13150. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13151. return;
  13152. }
  13153. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13154. setTimeout(() => {
  13155. loadDHCPClients();
  13156. fetchData();
  13157. }, 1500);
  13158. } catch (err) {
  13159. showToast('Error', err.message, 'error');
  13160. }
  13161. }
  13162. async function releaseDHCPClient(id) {
  13163. try {
  13164. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13165. method: 'POST'
  13166. });
  13167. const data = await res.json();
  13168. if (!res.ok) {
  13169. showToast('Error', data.error || 'Failed to release lease', 'error');
  13170. return;
  13171. }
  13172. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13173. await loadDHCPClients();
  13174. fetchData();
  13175. } catch (err) {
  13176. showToast('Error', err.message, 'error');
  13177. }
  13178. }
  13179. async function deleteDHCPClient(id, ifaceName) {
  13180. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13181. return;
  13182. }
  13183. try {
  13184. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13185. method: 'DELETE'
  13186. });
  13187. const data = await res.json();
  13188. if (!res.ok) {
  13189. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13190. return;
  13191. }
  13192. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13193. await loadDHCPClients();
  13194. fetchData();
  13195. } catch (err) {
  13196. showToast('Error', err.message, 'error');
  13197. }
  13198. }
  13199. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13200. async function loadDHCPServer(populate = true) {
  13201. try {
  13202. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13203. fetch(`${API_BASE}/dhcp-server/summary`),
  13204. fetch(`${API_BASE}/dhcp-server/servers`),
  13205. fetch(`${API_BASE}/dhcp-server/networks`),
  13206. fetch(`${API_BASE}/dhcp-server/leases`),
  13207. fetch(`${API_BASE}/dhcp-server/options`)
  13208. ]);
  13209. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13210. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13211. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13212. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13213. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13214. const sum = state.dhcpServerSummary || {};
  13215. const srvs = state.dhcpServers || [];
  13216. const nets = state.dhcpNetworks || [];
  13217. const leases = state.dhcpLeases || [];
  13218. const opts = state.dhcpOptions || [];
  13219. // KPI Cards
  13220. const statActive = document.getElementById('dhcp-server-stat-active');
  13221. if (statActive) {
  13222. const activeCount = srvs.filter(s => s.running).length;
  13223. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13224. }
  13225. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13226. if (statLeases) {
  13227. statLeases.innerText = leases.length;
  13228. }
  13229. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13230. if (statLeasesSub) {
  13231. const dyn = leases.filter(l => l.dynamic).length;
  13232. const st = leases.filter(l => !l.dynamic).length;
  13233. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13234. }
  13235. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13236. if (statNetworks) {
  13237. statNetworks.innerText = nets.length;
  13238. }
  13239. // Subtab Badges
  13240. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13241. if (bSrv) bSrv.innerText = srvs.length;
  13242. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13243. if (bNet) bNet.innerText = nets.length;
  13244. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13245. if (bLease) bLease.innerText = leases.length;
  13246. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13247. if (bOpt) bOpt.innerText = opts.length;
  13248. // Sidebar Badge
  13249. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13250. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13251. renderCurrentDHCPServerTab();
  13252. } catch (err) {
  13253. console.error('Failed to load DHCP Server:', err);
  13254. }
  13255. }
  13256. function switchDHCPServerTab(tab) {
  13257. state.dhcpServerTab = tab;
  13258. const tabs = ['servers', 'networks', 'leases', 'options'];
  13259. tabs.forEach(t => {
  13260. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13261. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13262. if (panel) {
  13263. if (t === tab) panel.classList.remove('hidden');
  13264. else panel.classList.add('hidden');
  13265. }
  13266. if (btn) {
  13267. if (t === tab) {
  13268. 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';
  13269. } else {
  13270. 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';
  13271. }
  13272. }
  13273. });
  13274. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13275. if (addBtn) {
  13276. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13277. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13278. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13279. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13280. }
  13281. renderCurrentDHCPServerTab();
  13282. }
  13283. function handleDHCPServerPrimaryAdd() {
  13284. const tab = state.dhcpServerTab || 'servers';
  13285. if (tab === 'servers') openAddDHCPServerModal();
  13286. else if (tab === 'networks') openAddDHCPNetworkModal();
  13287. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13288. else if (tab === 'options') openAddDHCPOptionModal();
  13289. }
  13290. function renderCurrentDHCPServerTab() {
  13291. const tab = state.dhcpServerTab || 'servers';
  13292. if (tab === 'servers') renderDHCPServers();
  13293. else if (tab === 'networks') renderDHCPNetworks();
  13294. else if (tab === 'leases') renderDHCPLeases();
  13295. else if (tab === 'options') renderDHCPOptions();
  13296. }
  13297. function renderDHCPServers() {
  13298. const tbody = document.getElementById('dhcp-server-tbody');
  13299. const empty = document.getElementById('dhcp-server-empty');
  13300. if (!tbody) return;
  13301. const servers = state.dhcpServers || [];
  13302. if (servers.length === 0) {
  13303. tbody.innerHTML = '';
  13304. empty?.classList.remove('hidden');
  13305. return;
  13306. }
  13307. empty?.classList.add('hidden');
  13308. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13309. if (tbody.dataset.sig === sig) return;
  13310. tbody.dataset.sig = sig;
  13311. tbody.innerHTML = '';
  13312. servers.forEach(s => {
  13313. const tr = document.createElement('tr');
  13314. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13315. tr.innerHTML = `
  13316. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13317. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13318. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13319. <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>
  13320. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13321. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13322. <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>
  13323. <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>
  13324. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13325. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13326. <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>
  13327. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13328. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13329. </td>
  13330. `;
  13331. tbody.appendChild(tr);
  13332. });
  13333. }
  13334. function renderDHCPNetworks() {
  13335. const tbody = document.getElementById('dhcp-networks-tbody');
  13336. const empty = document.getElementById('dhcp-networks-empty');
  13337. if (!tbody) return;
  13338. tbody.innerHTML = '';
  13339. const networks = state.dhcpNetworks || [];
  13340. if (networks.length === 0) {
  13341. empty?.classList.remove('hidden');
  13342. return;
  13343. }
  13344. empty?.classList.add('hidden');
  13345. networks.forEach(n => {
  13346. const tr = document.createElement('tr');
  13347. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13348. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13349. const optionsChips = (n.dhcp_options || []).map(optId => {
  13350. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13351. if (!opt) return '';
  13352. 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>`;
  13353. }).filter(Boolean).join('');
  13354. tr.innerHTML = `
  13355. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13356. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13357. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13358. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13359. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13360. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13361. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13362. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13363. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13364. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13365. </td>
  13366. `;
  13367. tbody.appendChild(tr);
  13368. });
  13369. }
  13370. function renderDHCPLeases() {
  13371. const tbody = document.getElementById('dhcp-leases-tbody');
  13372. const empty = document.getElementById('dhcp-leases-empty');
  13373. if (!tbody) return;
  13374. tbody.innerHTML = '';
  13375. const leases = state.dhcpLeases || [];
  13376. if (leases.length === 0) {
  13377. empty?.classList.remove('hidden');
  13378. return;
  13379. }
  13380. empty?.classList.add('hidden');
  13381. leases.forEach(l => {
  13382. const tr = document.createElement('tr');
  13383. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13384. 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>';
  13385. const statusBadge = l.status === 'bound'
  13386. ? '<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>'
  13387. : l.status === 'static'
  13388. ? '<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>'
  13389. : '<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>';
  13390. const makeStaticBtn = l.dynamic
  13391. ? `<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>`
  13392. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13393. tr.innerHTML = `
  13394. <td class="py-2.5 px-3 text-center">${flag}</td>
  13395. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13396. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13397. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13398. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13399. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13400. <td class="py-2.5 px-3">${statusBadge}</td>
  13401. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13402. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13403. ${makeStaticBtn}
  13404. </td>
  13405. `;
  13406. tbody.appendChild(tr);
  13407. });
  13408. }
  13409. function renderDHCPOptions() {
  13410. const tbody = document.getElementById('dhcp-options-tbody');
  13411. const empty = document.getElementById('dhcp-options-empty');
  13412. if (!tbody) return;
  13413. tbody.innerHTML = '';
  13414. const options = state.dhcpOptions || [];
  13415. if (options.length === 0) {
  13416. empty?.classList.remove('hidden');
  13417. return;
  13418. }
  13419. empty?.classList.add('hidden');
  13420. options.forEach(o => {
  13421. const tr = document.createElement('tr');
  13422. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13423. tr.innerHTML = `
  13424. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13425. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13426. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13427. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13428. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13429. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13430. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13431. </td>
  13432. `;
  13433. tbody.appendChild(tr);
  13434. });
  13435. }
  13436. // ==================== MODALS & ACTIONS: SERVER ====================
  13437. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13438. const sel = document.getElementById(elemId);
  13439. if (!sel) return;
  13440. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13441. const networks = state.dhcpNetworks || [];
  13442. networks.forEach(n => {
  13443. const opt = document.createElement('option');
  13444. opt.value = n.address;
  13445. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13446. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13447. opt.selected = true;
  13448. }
  13449. sel.appendChild(opt);
  13450. });
  13451. }
  13452. function onDHCPServerNetworkChange() {
  13453. const netSel = document.getElementById('dhcp-server-modal-network');
  13454. if (!netSel) return;
  13455. const netVal = netSel.value;
  13456. if (!netVal) return;
  13457. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13458. if (!poolInput) return;
  13459. // Auto-calculate suggested address pool based on subnet CIDR
  13460. const parts = netVal.split('/');
  13461. const ip = parts[0];
  13462. const cidr = parseInt(parts[1] || '24', 10);
  13463. if (cidr === 24) {
  13464. const octets = ip.split('.');
  13465. if (octets.length === 4) {
  13466. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13467. poolInput.value = `${base}.10-${base}.254`;
  13468. }
  13469. }
  13470. }
  13471. function openAddDHCPServerModal() {
  13472. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13473. document.getElementById('dhcp-server-modal-id').value = '';
  13474. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13475. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13476. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13477. document.getElementById('dhcp-server-modal-comment').value = '';
  13478. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13479. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13480. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13481. const networks = state.dhcpNetworks || [];
  13482. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13483. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13484. if (defaultNet) {
  13485. onDHCPServerNetworkChange();
  13486. }
  13487. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13488. }
  13489. function openEditDHCPServerModal(id) {
  13490. const s = (state.dhcpServers || []).find(item => item.id === id);
  13491. if (!s) return;
  13492. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13493. document.getElementById('dhcp-server-modal-id').value = s.id;
  13494. document.getElementById('dhcp-server-modal-name').value = s.name;
  13495. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13496. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13497. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13498. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13499. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13500. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13501. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13502. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13503. }
  13504. function closeDHCPServerModal() {
  13505. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13506. }
  13507. async function submitSaveDHCPServer(e) {
  13508. e.preventDefault();
  13509. const id = document.getElementById('dhcp-server-modal-id').value;
  13510. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13511. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13512. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13513. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13514. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13515. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13516. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13517. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13518. try {
  13519. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13520. method: 'POST',
  13521. headers: { 'Content-Type': 'application/json' },
  13522. body: JSON.stringify({
  13523. id,
  13524. name,
  13525. interface: iface,
  13526. network,
  13527. address_pool: pool,
  13528. lease_time: leaseTime,
  13529. authoritative,
  13530. disabled,
  13531. comment
  13532. })
  13533. });
  13534. if (res.ok) {
  13535. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13536. closeDHCPServerModal();
  13537. loadDHCPServer(false);
  13538. fetchData(false);
  13539. } else {
  13540. const err = await res.text();
  13541. showToast('Error', err, 'error');
  13542. }
  13543. } catch (err) {
  13544. showToast('Error', err.message, 'error');
  13545. }
  13546. }
  13547. async function toggleDHCPServerState(id, disabled) {
  13548. try {
  13549. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13550. method: 'POST',
  13551. headers: { 'Content-Type': 'application/json' },
  13552. body: JSON.stringify({ disabled })
  13553. });
  13554. if (res.ok) {
  13555. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13556. loadDHCPServer(false);
  13557. fetchData(false);
  13558. }
  13559. } catch (err) {
  13560. showToast('Error', err.message, 'error');
  13561. }
  13562. }
  13563. async function deleteDHCPServer(id, name) {
  13564. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13565. try {
  13566. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13567. if (res.ok) {
  13568. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13569. loadDHCPServer(false);
  13570. fetchData(false);
  13571. }
  13572. } catch (err) {
  13573. showToast('Error', err.message, 'error');
  13574. }
  13575. }
  13576. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13577. function openAddDHCPNetworkModal() {
  13578. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13579. document.getElementById('dhcp-network-modal-id').value = '';
  13580. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13581. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13582. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13583. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13584. document.getElementById('dhcp-network-modal-netmask').value = '';
  13585. document.getElementById('dhcp-network-modal-comment').value = '';
  13586. renderDHCPNetworkOptionsCheckboxes([]);
  13587. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13588. }
  13589. function openEditDHCPNetworkModal(id) {
  13590. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13591. if (!n) return;
  13592. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13593. document.getElementById('dhcp-network-modal-id').value = n.id;
  13594. document.getElementById('dhcp-network-modal-address').value = n.address;
  13595. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13596. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13597. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13598. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13599. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13600. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13601. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13602. }
  13603. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13604. const container = document.getElementById('dhcp-network-modal-options-list');
  13605. if (!container) return;
  13606. container.innerHTML = '';
  13607. const opts = state.dhcpOptions || [];
  13608. if (opts.length === 0) {
  13609. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13610. return;
  13611. }
  13612. opts.forEach(o => {
  13613. const isChecked = selectedIds.includes(o.id);
  13614. const label = document.createElement('label');
  13615. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13616. label.innerHTML = `
  13617. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13618. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13619. `;
  13620. container.appendChild(label);
  13621. });
  13622. }
  13623. function closeDHCPNetworkModal() {
  13624. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13625. }
  13626. async function submitSaveDHCPNetwork(e) {
  13627. e.preventDefault();
  13628. const id = document.getElementById('dhcp-network-modal-id').value;
  13629. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13630. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13631. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13632. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13633. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13634. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13635. const selectedOpts = [];
  13636. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13637. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13638. try {
  13639. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13640. method: 'POST',
  13641. headers: { 'Content-Type': 'application/json' },
  13642. body: JSON.stringify({
  13643. id,
  13644. address,
  13645. gateway,
  13646. netmask,
  13647. dns_servers: dnsServers,
  13648. domain,
  13649. dhcp_options: selectedOpts,
  13650. comment
  13651. })
  13652. });
  13653. if (res.ok) {
  13654. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13655. closeDHCPNetworkModal();
  13656. loadDHCPServer(false);
  13657. fetchData(false);
  13658. } else {
  13659. const err = await res.text();
  13660. showToast('Error', err, 'error');
  13661. }
  13662. } catch (err) {
  13663. showToast('Error', err.message, 'error');
  13664. }
  13665. }
  13666. async function deleteDHCPNetwork(id, addr) {
  13667. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13668. try {
  13669. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13670. if (res.ok) {
  13671. showToast('Deleted', `Network ${addr} removed`, 'success');
  13672. loadDHCPServer(false);
  13673. fetchData(false);
  13674. }
  13675. } catch (err) {
  13676. showToast('Error', err.message, 'error');
  13677. }
  13678. }
  13679. // ==================== MODALS & ACTIONS: LEASES ====================
  13680. function openAddDHCPStaticLeaseModal() {
  13681. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13682. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13683. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13684. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13685. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13686. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13687. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13688. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13689. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13690. }
  13691. function closeDHCPStaticLeaseModal() {
  13692. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13693. }
  13694. async function submitSaveDHCPStaticLease(e) {
  13695. e.preventDefault();
  13696. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13697. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13698. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13699. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13700. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13701. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13702. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13703. try {
  13704. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13705. method: 'POST',
  13706. headers: { 'Content-Type': 'application/json' },
  13707. body: JSON.stringify({
  13708. id,
  13709. mac_address: mac,
  13710. address: ip,
  13711. hostname,
  13712. server,
  13713. comment,
  13714. disabled
  13715. })
  13716. });
  13717. if (res.ok) {
  13718. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13719. closeDHCPStaticLeaseModal();
  13720. loadDHCPServer(false);
  13721. fetchData(false);
  13722. } else {
  13723. const err = await res.text();
  13724. showToast('Error', err, 'error');
  13725. }
  13726. } catch (err) {
  13727. showToast('Error', err.message, 'error');
  13728. }
  13729. }
  13730. async function deleteDHCPStaticLease(id) {
  13731. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13732. try {
  13733. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13734. if (res.ok) {
  13735. showToast('Deleted', 'Static lease removed', 'success');
  13736. loadDHCPServer(false);
  13737. fetchData(false);
  13738. }
  13739. } catch (err) {
  13740. showToast('Error', err.message, 'error');
  13741. }
  13742. }
  13743. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13744. try {
  13745. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13746. method: 'POST',
  13747. headers: { 'Content-Type': 'application/json' },
  13748. body: JSON.stringify({
  13749. mac_address: mac,
  13750. address: ip,
  13751. hostname,
  13752. comment: comment || 'Converted to static'
  13753. })
  13754. });
  13755. if (res.ok) {
  13756. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13757. loadDHCPServer(false);
  13758. fetchData(false);
  13759. } else {
  13760. const err = await res.text();
  13761. showToast('Error', err, 'error');
  13762. }
  13763. } catch (err) {
  13764. showToast('Error', err.message, 'error');
  13765. }
  13766. }
  13767. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13768. function openAddDHCPOptionModal() {
  13769. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13770. document.getElementById('dhcp-option-modal-id').value = '';
  13771. document.getElementById('dhcp-option-modal-name').value = '';
  13772. document.getElementById('dhcp-option-modal-code').value = '';
  13773. document.getElementById('dhcp-option-modal-value').value = '';
  13774. document.getElementById('dhcp-option-modal-comment').value = '';
  13775. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13776. }
  13777. function openEditDHCPOptionModal(id) {
  13778. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13779. if (!o) return;
  13780. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13781. document.getElementById('dhcp-option-modal-id').value = o.id;
  13782. document.getElementById('dhcp-option-modal-name').value = o.name;
  13783. document.getElementById('dhcp-option-modal-code').value = o.code;
  13784. document.getElementById('dhcp-option-modal-value').value = o.value;
  13785. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13786. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13787. }
  13788. function closeDHCPOptionModal() {
  13789. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13790. }
  13791. async function submitSaveDHCPOption(e) {
  13792. e.preventDefault();
  13793. const id = document.getElementById('dhcp-option-modal-id').value;
  13794. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13795. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13796. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13797. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13798. try {
  13799. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13800. method: 'POST',
  13801. headers: { 'Content-Type': 'application/json' },
  13802. body: JSON.stringify({ id, name, code, value, comment })
  13803. });
  13804. if (res.ok) {
  13805. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13806. closeDHCPOptionModal();
  13807. loadDHCPServer(false);
  13808. fetchData(false);
  13809. } else {
  13810. const err = await res.text();
  13811. showToast('Error', err, 'error');
  13812. }
  13813. } catch (err) {
  13814. showToast('Error', err.message, 'error');
  13815. }
  13816. }
  13817. async function deleteDHCPOption(id, name) {
  13818. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13819. try {
  13820. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13821. if (res.ok) {
  13822. showToast('Deleted', `Option ${name} removed`, 'success');
  13823. loadDHCPServer(false);
  13824. fetchData(false);
  13825. }
  13826. } catch (err) {
  13827. showToast('Error', err.message, 'error');
  13828. }
  13829. }
  13830. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13831. function openDHCPServerSetupModal() {
  13832. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13833. onDHCPWizardIfaceChange();
  13834. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13835. }
  13836. function closeDHCPServerSetupModal() {
  13837. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13838. }
  13839. function onDHCPWizardIfaceChange() {
  13840. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13841. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13842. let ip = '192.168.88.1';
  13843. let prefix = '24';
  13844. if (iface && iface.ip_address) {
  13845. const parts = iface.ip_address.split('/');
  13846. ip = parts[0];
  13847. if (parts.length > 1) prefix = parts[1];
  13848. }
  13849. // Calculate subnet base (e.g. 192.168.88.0/24)
  13850. const ipParts = ip.split('.');
  13851. if (ipParts.length === 4) {
  13852. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13853. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13854. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13855. document.getElementById('dhcp-wizard-gateway').value = ip;
  13856. document.getElementById('dhcp-wizard-pool').value = pool;
  13857. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13858. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13859. }
  13860. }
  13861. async function submitDHCPServerSetupWizard(e) {
  13862. e.preventDefault();
  13863. const iface = document.getElementById('dhcp-wizard-iface').value;
  13864. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13865. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13866. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13867. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13868. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13869. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13870. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13871. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13872. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13873. try {
  13874. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13875. method: 'POST',
  13876. headers: { 'Content-Type': 'application/json' },
  13877. body: JSON.stringify({
  13878. interface: iface,
  13879. address_space: space,
  13880. gateway: gw,
  13881. address_pool: pool,
  13882. dns_servers: dnsServers,
  13883. lease_time: leaseTime,
  13884. ntp_servers: ntpServers,
  13885. next_server: tftp
  13886. })
  13887. });
  13888. if (res.ok) {
  13889. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13890. closeDHCPServerSetupModal();
  13891. loadDHCPServer(false);
  13892. fetchData(false);
  13893. } else {
  13894. const err = await res.text();
  13895. showToast('Error', err, 'error');
  13896. }
  13897. } catch (err) {
  13898. showToast('Error', err.message, 'error');
  13899. }
  13900. }
  13901. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13902. const sel = document.getElementById(elemId);
  13903. if (!sel) return;
  13904. sel.innerHTML = '<option value="">Select interface...</option>';
  13905. const ifaces = state.interfaces || [];
  13906. ifaces.forEach(i => {
  13907. if (i.name === 'lo') return;
  13908. const opt = document.createElement('option');
  13909. opt.value = i.name;
  13910. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13911. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13912. if (i.name === selectedVal) opt.selected = true;
  13913. sel.appendChild(opt);
  13914. });
  13915. }
  13916. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13917. function initTableSorting() {
  13918. document.querySelectorAll('table').forEach(setupSortableTable);
  13919. }
  13920. function setupSortableTable(table) {
  13921. const thead = table.querySelector('thead');
  13922. const tbody = table.querySelector('tbody');
  13923. if (!thead || !tbody) return;
  13924. const headerRows = thead.querySelectorAll('tr');
  13925. if (headerRows.length === 0) return;
  13926. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13927. ths.forEach((th, colIdx) => {
  13928. if (th._sortBound) return;
  13929. th._sortBound = true;
  13930. const rawText = th.innerText.trim().toLowerCase();
  13931. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13932. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13933. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13934. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13935. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13936. return;
  13937. }
  13938. th.classList.add('table-sortable', 'group');
  13939. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13940. let icon = th.querySelector('.table-sort-icon');
  13941. if (!icon) {
  13942. icon = document.createElement('span');
  13943. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13944. icon.innerHTML = '⇅';
  13945. th.appendChild(icon);
  13946. }
  13947. th.addEventListener('click', (e) => {
  13948. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13949. handleHeaderClick(table, th, colIdx);
  13950. });
  13951. });
  13952. if (!tbody._sortObserved) {
  13953. tbody._sortObserved = true;
  13954. let sortDebounceTimer = null;
  13955. const observer = new MutationObserver((mutations) => {
  13956. if (tbody._isSorting) return;
  13957. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13958. if (!hasChildChanges) return;
  13959. clearTimeout(sortDebounceTimer);
  13960. sortDebounceTimer = setTimeout(() => {
  13961. if (tbody._isSorting) return;
  13962. if (table._activeSort && table._activeSort.dir !== 'none') {
  13963. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13964. } else {
  13965. tagOriginalRowOrder(tbody);
  13966. }
  13967. }, 50);
  13968. });
  13969. tbody._sortObserver = observer;
  13970. observer.observe(tbody, { childList: true });
  13971. }
  13972. tagOriginalRowOrder(tbody);
  13973. }
  13974. function tagOriginalRowOrder(tbody) {
  13975. let idx = 0;
  13976. Array.from(tbody.children).forEach(tr => {
  13977. if (!tr.querySelector('td[colspan]')) {
  13978. if (!tr.hasAttribute('data-orig-idx')) {
  13979. tr.setAttribute('data-orig-idx', idx++);
  13980. }
  13981. }
  13982. });
  13983. }
  13984. function handleHeaderClick(table, th, colIdx) {
  13985. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13986. let newDir = 'asc';
  13987. if (currentSort.colIdx === colIdx) {
  13988. if (currentSort.dir === 'asc') newDir = 'desc';
  13989. else if (currentSort.dir === 'desc') newDir = 'none';
  13990. else newDir = 'asc';
  13991. } else {
  13992. newDir = 'asc';
  13993. }
  13994. table._activeSort = { colIdx, dir: newDir };
  13995. updateHeaderIcons(table, colIdx, newDir);
  13996. applyTableSort(table, colIdx, newDir, true);
  13997. }
  13998. function updateHeaderIcons(table, activeColIdx, dir) {
  13999. const thead = table.querySelector('thead');
  14000. if (!thead) return;
  14001. const ths = thead.querySelectorAll('th');
  14002. ths.forEach((th, idx) => {
  14003. const icon = th.querySelector('.table-sort-icon');
  14004. if (!icon) return;
  14005. if (idx === activeColIdx && dir !== 'none') {
  14006. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  14007. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  14008. th.classList.add('table-sorted-active');
  14009. } else {
  14010. icon.innerHTML = '⇅';
  14011. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  14012. th.classList.remove('table-sorted-active');
  14013. }
  14014. });
  14015. }
  14016. function applyTableSort(table, colIdx, dir, userInitiated) {
  14017. const tbody = table.querySelector('tbody');
  14018. if (!tbody || tbody.children.length <= 1) return;
  14019. tbody._isSorting = true;
  14020. tagOriginalRowOrder(tbody);
  14021. // Group parent rows and any attached drawer/sub-rows
  14022. const groups = [];
  14023. let currentGroup = null;
  14024. Array.from(tbody.children).forEach(tr => {
  14025. if (tr.querySelector('td[colspan]')) {
  14026. if (currentGroup) {
  14027. currentGroup.subRows.push(tr);
  14028. } else {
  14029. groups.push({ mainRow: tr, subRows: [] });
  14030. }
  14031. } else {
  14032. currentGroup = { mainRow: tr, subRows: [] };
  14033. groups.push(currentGroup);
  14034. }
  14035. });
  14036. if (dir === 'none') {
  14037. groups.sort((a, b) => {
  14038. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14039. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14040. return idxA - idxB;
  14041. });
  14042. } else {
  14043. groups.sort((a, b) => {
  14044. const cellA = a.mainRow.children[colIdx];
  14045. const cellB = b.mainRow.children[colIdx];
  14046. const res = compareTableCells(cellA, cellB);
  14047. return dir === 'asc' ? res : -res;
  14048. });
  14049. }
  14050. // Check if rows are already in correct order to avoid modifying DOM
  14051. let alreadyOrdered = true;
  14052. let childIdx = 0;
  14053. for (const g of groups) {
  14054. if (tbody.children[childIdx] !== g.mainRow) {
  14055. alreadyOrdered = false;
  14056. break;
  14057. }
  14058. childIdx++;
  14059. for (const sub of g.subRows) {
  14060. if (tbody.children[childIdx] !== sub) {
  14061. alreadyOrdered = false;
  14062. break;
  14063. }
  14064. childIdx++;
  14065. }
  14066. }
  14067. if (alreadyOrdered) {
  14068. tbody._isSorting = false;
  14069. return;
  14070. }
  14071. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14072. if (tbody._sortObserver) {
  14073. tbody._sortObserver.disconnect();
  14074. }
  14075. // Re-append rows in sorted order
  14076. groups.forEach(g => {
  14077. tbody.appendChild(g.mainRow);
  14078. g.subRows.forEach(sub => tbody.appendChild(sub));
  14079. });
  14080. // Drain any queued mutations and re-connect observer
  14081. if (tbody._sortObserver) {
  14082. tbody._sortObserver.takeRecords();
  14083. tbody._sortObserver.observe(tbody, { childList: true });
  14084. }
  14085. tbody._isSorting = false;
  14086. }
  14087. function getCellRawText(cell) {
  14088. if (!cell) return '';
  14089. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14090. const input = cell.querySelector('input, select');
  14091. if (input) {
  14092. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14093. return input.value;
  14094. }
  14095. return cell.innerText.trim();
  14096. }
  14097. function parseTrafficToNumber(str) {
  14098. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14099. if (!m) return null;
  14100. const num = parseFloat(m[1].replace(/,/g, ''));
  14101. if (isNaN(num)) return null;
  14102. const unit = m[2].toUpperCase();
  14103. let mult = 1;
  14104. if (unit.startsWith('K')) mult = 1024;
  14105. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14106. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14107. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14108. return num * mult;
  14109. }
  14110. function parseIpToNumber(str) {
  14111. const clean = str.replace(/^[!~]/, '').trim();
  14112. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14113. if (!m) return null;
  14114. const o1 = parseInt(m[1], 10);
  14115. const o2 = parseInt(m[2], 10);
  14116. const o3 = parseInt(m[3], 10);
  14117. const o4 = parseInt(m[4], 10);
  14118. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14119. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14120. }
  14121. function parseCompoundPackets(str) {
  14122. const m = str.match(/^([\d,]+)p/);
  14123. if (!m) return null;
  14124. return parseInt(m[1].replace(/,/g, ''), 10);
  14125. }
  14126. function compareTableCells(cellA, cellB) {
  14127. const a = getCellRawText(cellA);
  14128. const b = getCellRawText(cellB);
  14129. if (a === '' && b !== '') return 1;
  14130. if (b === '' && a !== '') return -1;
  14131. if (a === b) return 0;
  14132. // 1. IP Addresses / CIDR
  14133. const ipA = parseIpToNumber(a);
  14134. const ipB = parseIpToNumber(b);
  14135. if (ipA !== null && ipB !== null) return ipA - ipB;
  14136. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14137. const pktA = parseCompoundPackets(a);
  14138. const pktB = parseCompoundPackets(b);
  14139. if (pktA !== null && pktB !== null) return pktA - pktB;
  14140. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14141. const trafA = parseTrafficToNumber(a);
  14142. const trafB = parseTrafficToNumber(b);
  14143. if (trafA !== null && trafB !== null) return trafA - trafB;
  14144. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14145. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14146. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14147. const numA = Number(cleanNumA);
  14148. const numB = Number(cleanNumB);
  14149. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14150. return numA - numB;
  14151. }
  14152. // 5. Natural case-insensitive string compare
  14153. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14154. }
  14155. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14156. async function loadVRRP(showToastNotification = false) {
  14157. try {
  14158. const [instRes, sumRes] = await Promise.all([
  14159. fetch(`${API_BASE}/vrrp/instances`),
  14160. fetch(`${API_BASE}/vrrp/summary`)
  14161. ]);
  14162. if (instRes.ok) {
  14163. state.vrrpInstances = await instRes.json();
  14164. renderVRRP();
  14165. }
  14166. if (sumRes.ok) {
  14167. state.vrrpSummary = await sumRes.json();
  14168. renderVRRPSummary();
  14169. }
  14170. if (showToastNotification) {
  14171. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14172. }
  14173. } catch (err) {
  14174. console.error('Failed to load VRRP:', err);
  14175. }
  14176. }
  14177. function renderVRRPSummary() {
  14178. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14179. const elTotal = document.getElementById('vrrp-stat-total');
  14180. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14181. const elMaster = document.getElementById('vrrp-stat-master');
  14182. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14183. const elBackup = document.getElementById('vrrp-stat-backup');
  14184. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14185. const bCount = document.getElementById('badge-vrrp-count');
  14186. if (bCount) bCount.innerText = s.total_instances || 0;
  14187. const dot = document.getElementById('badge-vrrp-dot');
  14188. if (dot) {
  14189. if (s.master_instances > 0) {
  14190. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14191. } else if (s.backup_instances > 0) {
  14192. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14193. } else {
  14194. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14195. }
  14196. }
  14197. }
  14198. function renderVRRP() {
  14199. const tbody = document.getElementById('vrrp-table-tbody');
  14200. const empty = document.getElementById('vrrp-table-empty');
  14201. if (!tbody) return;
  14202. tbody.innerHTML = '';
  14203. const instances = state.vrrpInstances || [];
  14204. if (instances.length === 0) {
  14205. empty?.classList.remove('hidden');
  14206. return;
  14207. }
  14208. empty?.classList.add('hidden');
  14209. instances.forEach(inst => {
  14210. const tr = document.createElement('tr');
  14211. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14212. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14213. 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>`;
  14214. if (inst.disabled) {
  14215. 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>`;
  14216. } else if (inst.state === 'MASTER') {
  14217. 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>`;
  14218. } else if (inst.state === 'BACKUP') {
  14219. 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>`;
  14220. } else if (inst.state === 'FAULT') {
  14221. 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>`;
  14222. }
  14223. // Render State Badge
  14224. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14225. if (!inst.disabled) {
  14226. if (inst.state === 'MASTER') {
  14227. 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>`;
  14228. } else if (inst.state === 'BACKUP') {
  14229. 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>`;
  14230. } else if (inst.state === 'FAULT') {
  14231. 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>`;
  14232. }
  14233. }
  14234. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14235. tr.innerHTML = `
  14236. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14237. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14238. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14239. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14240. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14241. <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>
  14242. <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>
  14243. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14244. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14245. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14246. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14247. <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>
  14248. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14249. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14250. </td>
  14251. `;
  14252. tbody.appendChild(tr);
  14253. });
  14254. }
  14255. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14256. const sel = document.getElementById(elemId);
  14257. if (!sel) return;
  14258. sel.innerHTML = '<option value="">Select interface...</option>';
  14259. const ifaces = state.interfaces || [];
  14260. ifaces.forEach(i => {
  14261. const opt = document.createElement('option');
  14262. opt.value = i.name;
  14263. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14264. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14265. sel.appendChild(opt);
  14266. });
  14267. }
  14268. function openAddVRRPModal() {
  14269. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14270. document.getElementById('modal-vrrp-id').value = '';
  14271. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14272. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14273. document.getElementById('modal-vrrp-priority').value = 100;
  14274. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14275. document.getElementById('modal-vrrp-version').value = '3';
  14276. document.getElementById('modal-vrrp-interval').value = 1;
  14277. document.getElementById('modal-vrrp-authtype').value = 'none';
  14278. document.getElementById('modal-vrrp-authpass').value = '';
  14279. document.getElementById('modal-vrrp-comment').value = '';
  14280. document.getElementById('modal-vrrp-preempt').checked = true;
  14281. document.getElementById('modal-vrrp-disabled').checked = false;
  14282. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14283. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14284. }
  14285. function openEditVRRPModal(id) {
  14286. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14287. if (!inst) return;
  14288. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14289. document.getElementById('modal-vrrp-id').value = inst.id;
  14290. document.getElementById('modal-vrrp-name').value = inst.name;
  14291. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14292. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14293. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14294. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14295. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14296. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14297. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14298. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14299. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14300. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14301. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14302. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14303. }
  14304. function closeVRRPModal() {
  14305. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14306. }
  14307. async function submitSaveVRRP(e) {
  14308. e.preventDefault();
  14309. const id = document.getElementById('modal-vrrp-id').value;
  14310. const name = document.getElementById('modal-vrrp-name').value.trim();
  14311. const iface = document.getElementById('modal-vrrp-iface').value;
  14312. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14313. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14314. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14315. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14316. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14317. const authType = document.getElementById('modal-vrrp-authtype').value;
  14318. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14319. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14320. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14321. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14322. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14323. try {
  14324. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14325. method: 'POST',
  14326. headers: { 'Content-Type': 'application/json' },
  14327. body: JSON.stringify({
  14328. id,
  14329. name,
  14330. interface: iface,
  14331. vrid,
  14332. priority,
  14333. virtual_ips: vips,
  14334. version,
  14335. interval,
  14336. auth_type: authType,
  14337. auth_password: authPass,
  14338. comment,
  14339. preempt,
  14340. disabled
  14341. })
  14342. });
  14343. if (res.ok) {
  14344. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14345. closeVRRPModal();
  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 deleteVRRP(id, name) {
  14357. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14358. try {
  14359. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14360. if (res.ok) {
  14361. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14362. loadVRRP(false);
  14363. fetchData(false);
  14364. } else {
  14365. const err = await res.text();
  14366. showToast('Error', err, 'error');
  14367. }
  14368. } catch (err) {
  14369. showToast('Error', err.message, 'error');
  14370. }
  14371. }
  14372. async function toggleVRRPState(id, disabled) {
  14373. try {
  14374. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14375. method: 'POST',
  14376. headers: { 'Content-Type': 'application/json' },
  14377. body: JSON.stringify({ disabled })
  14378. });
  14379. if (res.ok) {
  14380. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14381. loadVRRP(false);
  14382. fetchData(false);
  14383. } else {
  14384. const err = await res.text();
  14385. showToast('Error', err, 'error');
  14386. }
  14387. } catch (err) {
  14388. showToast('Error', err.message, 'error');
  14389. }
  14390. }
  14391. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14392. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14393. let docSortDebounce = null;
  14394. const docTableObserver = new MutationObserver((mutations) => {
  14395. let needsInit = false;
  14396. for (const m of mutations) {
  14397. for (const node of m.addedNodes) {
  14398. if (node.nodeType === 1) {
  14399. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14400. needsInit = true;
  14401. break;
  14402. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14403. needsInit = true;
  14404. break;
  14405. }
  14406. }
  14407. }
  14408. if (needsInit) break;
  14409. }
  14410. if (needsInit) {
  14411. clearTimeout(docSortDebounce);
  14412. docSortDebounce = setTimeout(initTableSorting, 100);
  14413. }
  14414. });
  14415. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14416. }
  14417. // =========================================================================
  14418. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14419. // =========================================================================
  14420. const bwtestState = {
  14421. running: false,
  14422. pollTimer: null,
  14423. eventSource: null,
  14424. chartPoints: [],
  14425. maxChartPoints: 60,
  14426. serverConfig: null,
  14427. peakTx: 0,
  14428. peakRx: 0,
  14429. targetDuration: 10,
  14430. lastSampleElapsed: -1,
  14431. sessionID: null
  14432. };
  14433. async function loadBwTestView() {
  14434. resizeBwTestCanvas();
  14435. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14436. }
  14437. async function fetchBwTestServerStatus() {
  14438. try {
  14439. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14440. if (!res.ok) return;
  14441. const s = await res.json();
  14442. bwtestState.serverConfig = s;
  14443. // Update indicator and badges
  14444. const indicator = document.getElementById('bwtest-server-indicator');
  14445. const badge = document.getElementById('bwtest-server-badge');
  14446. const sideBadge = document.getElementById('badge-bwtest-server');
  14447. if (s.enabled && s.running) {
  14448. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14449. if (badge) {
  14450. badge.innerText = `Port ${s.port} (Active)`;
  14451. badge.className = 'text-emerald-400 font-bold';
  14452. }
  14453. if (sideBadge) {
  14454. sideBadge.innerText = s.port;
  14455. 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';
  14456. }
  14457. } else {
  14458. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14459. if (badge) {
  14460. badge.innerText = `Disabled`;
  14461. badge.className = 'text-slate-500 font-bold';
  14462. }
  14463. if (sideBadge) {
  14464. sideBadge.innerText = 'Off';
  14465. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14466. }
  14467. }
  14468. // Modal fields
  14469. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14470. const serverModal = document.getElementById('modal-bwtest-server');
  14471. const editing = serverModal && !serverModal.classList.contains('hidden');
  14472. if (toggle && !editing) toggle.checked = !!s.enabled;
  14473. const portInp = document.getElementById('bwtest-server-port-input');
  14474. if (portInp && !editing) portInp.value = s.port || 2000;
  14475. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14476. if (actSess) actSess.innerText = s.active_sessions || 0;
  14477. const totServ = document.getElementById('bwtest-modal-total-served');
  14478. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14479. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14480. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14481. } catch (err) {
  14482. console.error('Failed to fetch BwTest server status:', err);
  14483. }
  14484. }
  14485. function openBwTestServerModal() {
  14486. const cfg = bwtestState.serverConfig;
  14487. if (cfg) {
  14488. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14489. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14490. }
  14491. fetchBwTestServerStatus();
  14492. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14493. }
  14494. function closeBwTestServerModal() {
  14495. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14496. }
  14497. async function submitBwTestServerSettings(e) {
  14498. e.preventDefault();
  14499. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14500. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14501. try {
  14502. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14503. method: 'POST',
  14504. headers: { 'Content-Type': 'application/json' },
  14505. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14506. });
  14507. if (!res.ok) {
  14508. const err = await res.json();
  14509. throw new Error(err.error || 'Failed to update server configuration');
  14510. }
  14511. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14512. closeBwTestServerModal();
  14513. fetchBwTestServerStatus();
  14514. } catch (err) {
  14515. showToast('Server Configuration Error', err.message, 'error');
  14516. }
  14517. }
  14518. function setBwTestTarget(target) {
  14519. const inp = document.getElementById('bwtest-input-target');
  14520. if (inp) inp.value = target;
  14521. }
  14522. function setBwTestProtocol(proto) {
  14523. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14524. if (hiddenInp) hiddenInp.value = proto;
  14525. const btnUdp = document.getElementById('bwtest-proto-udp');
  14526. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14527. const badge = document.getElementById('bwtest-proto-badge');
  14528. const pktField = document.getElementById('bwtest-field-pktsize');
  14529. 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';
  14530. 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';
  14531. 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';
  14532. if (proto === 'udp') {
  14533. if (btnUdp) {
  14534. btnUdp.className = activeUdpCls;
  14535. const dot = btnUdp.querySelector('span');
  14536. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14537. }
  14538. if (btnTcp) {
  14539. btnTcp.className = inactiveCls;
  14540. const dot = btnTcp.querySelector('span');
  14541. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14542. }
  14543. if (badge) {
  14544. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14545. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14546. }
  14547. if (pktField) pktField.classList.remove('opacity-40');
  14548. } else {
  14549. if (btnUdp) {
  14550. btnUdp.className = inactiveCls;
  14551. const dot = btnUdp.querySelector('span');
  14552. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14553. }
  14554. if (btnTcp) {
  14555. btnTcp.className = activeTcpCls;
  14556. const dot = btnTcp.querySelector('span');
  14557. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14558. }
  14559. if (badge) {
  14560. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14561. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14562. }
  14563. if (pktField) pktField.classList.add('opacity-40');
  14564. }
  14565. }
  14566. function setBwTestDirection(dir) {
  14567. const hiddenInp = document.getElementById('bwtest-input-direction');
  14568. if (hiddenInp) hiddenInp.value = dir;
  14569. const btnBoth = document.getElementById('bwtest-dir-both');
  14570. const btnTx = document.getElementById('bwtest-dir-tx');
  14571. const btnRx = document.getElementById('bwtest-dir-rx');
  14572. 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';
  14573. 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';
  14574. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14575. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14576. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14577. }
  14578. function setBwTestLimit(bps) {
  14579. const sel = document.getElementById('bwtest-input-limit');
  14580. if (sel) sel.value = String(bps);
  14581. }
  14582. async function checkActiveBwTest() {
  14583. try {
  14584. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14585. if (!res.ok) return;
  14586. const st = await res.json();
  14587. if (st.running) {
  14588. setBwTestRunningUI(true);
  14589. processBwTestStatus(st);
  14590. startBwTestTelemetry();
  14591. }
  14592. } catch (err) {
  14593. console.error('Failed to check active BwTest:', err);
  14594. }
  14595. }
  14596. async function startBwTest(e) {
  14597. if (e && e.preventDefault) e.preventDefault();
  14598. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14599. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14600. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14601. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14602. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14603. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14604. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14605. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14606. bwtestState.targetDuration = duration;
  14607. bwtestState.chartPoints = [];
  14608. bwtestState.peakTx = 0;
  14609. bwtestState.peakRx = 0;
  14610. bwtestState.lastSampleElapsed = -1;
  14611. bwtestState.sessionID = null;
  14612. // Clear UI elements
  14613. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14614. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14615. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14616. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14617. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14618. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14619. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14620. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14621. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14622. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14623. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14624. const tbody = document.getElementById('bwtest-samples-tbody');
  14625. if (tbody) tbody.innerHTML = '';
  14626. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14627. setBwTestRunningUI(true);
  14628. try {
  14629. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14630. method: 'POST',
  14631. headers: { 'Content-Type': 'application/json' },
  14632. body: JSON.stringify({
  14633. target,
  14634. port,
  14635. direction,
  14636. protocol,
  14637. bandwidth_limit,
  14638. packet_size,
  14639. streams,
  14640. duration
  14641. })
  14642. });
  14643. if (!res.ok) {
  14644. const err = await res.json();
  14645. throw new Error(err.error || 'Failed to start bandwidth test');
  14646. }
  14647. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14648. startBwTestTelemetry();
  14649. } catch (err) {
  14650. setBwTestRunningUI(false);
  14651. showToast('Start Failed', err.message, 'error');
  14652. }
  14653. }
  14654. function setBwTestRunningUI(running) {
  14655. bwtestState.running = running;
  14656. const startBtn = document.getElementById('bwtest-btn-start');
  14657. const stopBtn = document.getElementById('bwtest-btn-stop');
  14658. const badge = document.getElementById('bwtest-run-status-badge');
  14659. const ph = document.getElementById('bwtest-chart-placeholder');
  14660. if (running) {
  14661. if (startBtn) {
  14662. startBtn.disabled = true;
  14663. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14664. }
  14665. if (stopBtn) {
  14666. stopBtn.disabled = false;
  14667. stopBtn.classList.remove('opacity-40');
  14668. }
  14669. if (badge) {
  14670. badge.innerText = 'TESTING...';
  14671. 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';
  14672. }
  14673. if (ph) ph.style.display = 'none';
  14674. } else {
  14675. if (startBtn) {
  14676. startBtn.disabled = false;
  14677. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14678. }
  14679. if (stopBtn) {
  14680. stopBtn.disabled = true;
  14681. stopBtn.classList.add('opacity-40');
  14682. }
  14683. if (badge) {
  14684. badge.innerText = 'IDLE';
  14685. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14686. }
  14687. }
  14688. }
  14689. async function stopBwTest() {
  14690. try {
  14691. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14692. if (!res.ok) throw new Error(await responseError(res));
  14693. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14694. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14695. } catch (err) {
  14696. showToast('Stop Failed', err.message, 'error');
  14697. }
  14698. }
  14699. async function responseError(res) {
  14700. const text = await res.text();
  14701. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14702. catch { return text || `HTTP ${res.status}`; }
  14703. }
  14704. function processBwTestStatus(st) {
  14705. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14706. bwtestState.sessionID = st.session_id;
  14707. bwtestState.lastSampleElapsed = -1;
  14708. }
  14709. for (const sample of st.recent_samples || []) {
  14710. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14711. handleBwTestSample(sample);
  14712. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14713. }
  14714. }
  14715. if (!st.running) {
  14716. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14717. bwtestState.pollTimer = null;
  14718. setBwTestRunningUI(false);
  14719. handleBwTestFinish(st.summary, st.error);
  14720. }
  14721. }
  14722. function startBwTestTelemetry() {
  14723. if (!state.currentUser) return;
  14724. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14725. let busy = false;
  14726. const poll = async () => {
  14727. if (busy || !state.currentUser || document.hidden) return;
  14728. busy = true;
  14729. try {
  14730. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14731. if (!res.ok) throw new Error(await responseError(res));
  14732. processBwTestStatus(await res.json());
  14733. } catch (err) {
  14734. console.error('BwTest polling error:', err);
  14735. } finally { busy = false; }
  14736. };
  14737. bwtestState.pollTimer = setInterval(poll, 400);
  14738. poll();
  14739. }
  14740. function handleBwTestSample(s) {
  14741. if (!s) return;
  14742. const payloadHint = document.getElementById('bwtest-effective-payload');
  14743. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14744. const txMbps = s.tx_mbps || 0;
  14745. const rxMbps = s.rx_mbps || 0;
  14746. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14747. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14748. // KPI updates
  14749. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14750. if (elTx) {
  14751. elTx.innerText = txMbps.toFixed(2);
  14752. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14753. }
  14754. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14755. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14756. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14757. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14758. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14759. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14760. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14761. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14762. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14763. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14764. const elLoss = document.getElementById('bwtest-stat-loss');
  14765. if (elLoss) {
  14766. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14767. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14768. }
  14769. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14770. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14771. const elJitter = document.getElementById('bwtest-stat-jitter');
  14772. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14773. const elTime = document.getElementById('bwtest-stat-time');
  14774. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14775. const elData = document.getElementById('bwtest-stat-data');
  14776. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14777. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14778. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14779. // Append point to chart buffer
  14780. bwtestState.chartPoints.push({
  14781. elapsed: s.elapsed_sec || 0,
  14782. tx: txMbps,
  14783. rx: rxMbps
  14784. });
  14785. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14786. bwtestState.chartPoints.shift();
  14787. }
  14788. drawBwTestChart();
  14789. // Add row to breakdown table
  14790. const tbody = document.getElementById('bwtest-samples-tbody');
  14791. if (tbody) {
  14792. const tr = document.createElement('tr');
  14793. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14794. tr.innerHTML = `
  14795. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14796. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14797. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14798. <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>
  14799. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14800. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14801. `;
  14802. tbody.insertBefore(tr, tbody.firstChild);
  14803. const countEl = document.getElementById('bwtest-sample-count');
  14804. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14805. }
  14806. }
  14807. function handleBwTestFinish(summary, error) {
  14808. const badge = document.getElementById('bwtest-run-status-badge');
  14809. if (error) {
  14810. showToast('Benchmark Error', error, 'error');
  14811. if (badge) {
  14812. badge.innerText = 'ERROR';
  14813. 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';
  14814. }
  14815. } else if (summary) {
  14816. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14817. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14818. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14819. if (badge) {
  14820. badge.innerText = 'COMPLETED';
  14821. 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';
  14822. }
  14823. }
  14824. loadBwTestHistory();
  14825. fetchBwTestServerStatus();
  14826. }
  14827. function resizeBwTestCanvas() {
  14828. const canvas = document.getElementById('bwtest-chart');
  14829. if (!canvas || !canvas.parentElement) return;
  14830. const rect = canvas.parentElement.getBoundingClientRect();
  14831. const dpr = window.devicePixelRatio || 1;
  14832. canvas.width = rect.width * dpr;
  14833. canvas.height = rect.height * dpr;
  14834. const ctx = canvas.getContext('2d');
  14835. ctx.scale(dpr, dpr);
  14836. drawBwTestChart();
  14837. }
  14838. window.addEventListener('resize', () => {
  14839. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14840. });
  14841. function drawBwTestChart() {
  14842. const canvas = document.getElementById('bwtest-chart');
  14843. if (!canvas) return;
  14844. const ctx = canvas.getContext('2d');
  14845. const dpr = window.devicePixelRatio || 1;
  14846. const width = canvas.width / dpr;
  14847. const height = canvas.height / dpr;
  14848. ctx.clearRect(0, 0, width, height);
  14849. const points = bwtestState.chartPoints;
  14850. if (!points || points.length === 0) return;
  14851. // Determine scale ceiling
  14852. let maxRate = 10;
  14853. for (const p of points) {
  14854. if (p.tx > maxRate) maxRate = p.tx;
  14855. if (p.rx > maxRate) maxRate = p.rx;
  14856. }
  14857. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14858. const paddingLeft = 55;
  14859. const paddingBottom = 24;
  14860. const paddingTop = 12;
  14861. const paddingRight = 16;
  14862. const chartW = width - paddingLeft - paddingRight;
  14863. const chartH = height - paddingTop - paddingBottom;
  14864. // Grid Lines and Y-Axis labels
  14865. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14866. ctx.lineWidth = 1;
  14867. ctx.fillStyle = '#94a3b8';
  14868. ctx.font = '10px monospace';
  14869. ctx.textAlign = 'right';
  14870. const gridSteps = 4;
  14871. for (let i = 0; i <= gridSteps; i++) {
  14872. const val = (maxRate / gridSteps) * i;
  14873. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14874. ctx.beginPath();
  14875. ctx.moveTo(paddingLeft, y);
  14876. ctx.lineTo(width - paddingRight, y);
  14877. ctx.stroke();
  14878. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14879. }
  14880. // Draw TX Line (Cyan #22d3ee)
  14881. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14882. // Draw RX Line (Purple #a855f7)
  14883. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14884. }
  14885. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14886. if (points.length < 2) return;
  14887. const stepX = w / Math.max(points.length - 1, 1);
  14888. // Gradient area fill
  14889. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14890. grad.addColorStop(0, fillColor);
  14891. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14892. ctx.beginPath();
  14893. points.forEach((p, idx) => {
  14894. const x = left + idx * stepX;
  14895. const val = valFn(p);
  14896. const y = top + h - (val / maxVal) * h;
  14897. if (idx === 0) {
  14898. ctx.moveTo(x, y);
  14899. } else {
  14900. ctx.lineTo(x, y);
  14901. }
  14902. });
  14903. // Complete path for fill
  14904. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14905. ctx.lineTo(left, top + h);
  14906. ctx.closePath();
  14907. ctx.fillStyle = grad;
  14908. ctx.fill();
  14909. // Draw line stroke
  14910. ctx.beginPath();
  14911. ctx.lineWidth = 2.5;
  14912. ctx.strokeStyle = strokeColor;
  14913. points.forEach((p, idx) => {
  14914. const x = left + idx * stepX;
  14915. const val = valFn(p);
  14916. const y = top + h - (val / maxVal) * h;
  14917. if (idx === 0) {
  14918. ctx.moveTo(x, y);
  14919. } else {
  14920. ctx.lineTo(x, y);
  14921. }
  14922. });
  14923. ctx.stroke();
  14924. // Draw end point halo
  14925. const lastP = points[points.length - 1];
  14926. const lastX = left + (points.length - 1) * stepX;
  14927. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14928. ctx.fillStyle = strokeColor;
  14929. ctx.beginPath();
  14930. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14931. ctx.fill();
  14932. }
  14933. async function loadBwTestHistory() {
  14934. try {
  14935. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14936. if (!res.ok) return;
  14937. const list = await res.json();
  14938. renderBwTestHistory(Array.isArray(list) ? list : []);
  14939. } catch (err) {
  14940. console.error('Failed to load BwTest history:', err);
  14941. }
  14942. }
  14943. function renderBwTestHistory(list) {
  14944. const tbody = document.getElementById('bwtest-history-tbody');
  14945. if (!tbody) return;
  14946. if (list.length === 0) {
  14947. 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>`;
  14948. return;
  14949. }
  14950. tbody.innerHTML = '';
  14951. list.forEach(item => {
  14952. const s = item.summary || {};
  14953. const tr = document.createElement('tr');
  14954. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14955. const dirBadge = item.direction === 'both'
  14956. ? `<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>`
  14957. : item.direction === 'tx'
  14958. ? `<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>`
  14959. : `<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>`;
  14960. const protoBadge = item.protocol === 'tcp'
  14961. ? `<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>`
  14962. : `<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>`;
  14963. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14964. tr.innerHTML = `
  14965. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14966. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14967. <td class="py-2.5 px-4">${protoBadge}</td>
  14968. <td class="py-2.5 px-4">${dirBadge}</td>
  14969. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14970. <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>
  14971. <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>
  14972. <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>
  14973. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14974. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14975. `;
  14976. tbody.appendChild(tr);
  14977. });
  14978. }
  14979. // ======================== SETTINGS & ROUTER DNS ========================
  14980. state.settingsSubTab = 'dns';
  14981. state.dnsSettings = null;
  14982. state.dnsStaticRecords = [];
  14983. state.dnsStatus = null;
  14984. function switchSettingsSubTab(sub) {
  14985. state.settingsSubTab = sub;
  14986. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14987. const btnSys = document.getElementById('btn-settings-subtab-system');
  14988. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14989. const tabDns = document.getElementById('settings-subtab-dns');
  14990. const tabSys = document.getElementById('settings-subtab-system');
  14991. const tabBak = document.getElementById('settings-subtab-backup');
  14992. 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';
  14993. 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';
  14994. if (btnDns) btnDns.className = inactiveClass;
  14995. if (btnSys) btnSys.className = inactiveClass;
  14996. if (btnBak) btnBak.className = inactiveClass;
  14997. tabDns?.classList.add('hidden');
  14998. tabSys?.classList.add('hidden');
  14999. tabBak?.classList.add('hidden');
  15000. if (sub === 'dns') {
  15001. if (btnDns) btnDns.className = activeClass;
  15002. tabDns?.classList.remove('hidden');
  15003. loadDNSSettings();
  15004. } else if (sub === 'system') {
  15005. if (btnSys) btnSys.className = activeClass;
  15006. tabSys?.classList.remove('hidden');
  15007. loadSystemSettings();
  15008. } else if (sub === 'backup') {
  15009. if (btnBak) btnBak.className = activeClass;
  15010. tabBak?.classList.remove('hidden');
  15011. loadBackupList();
  15012. }
  15013. }
  15014. async function loadSettingsData(showLoading = false) {
  15015. if (state.settingsSubTab === 'system') {
  15016. await loadSystemSettings();
  15017. } else if (state.settingsSubTab === 'backup') {
  15018. await loadBackupList();
  15019. } else {
  15020. await loadDNSSettings();
  15021. }
  15022. }
  15023. async function loadDNSSettings() {
  15024. try {
  15025. const [settingsRes, staticRes, statusRes] = await Promise.all([
  15026. fetch(`${API_BASE}/dns/settings`),
  15027. fetch(`${API_BASE}/dns/static`),
  15028. fetch(`${API_BASE}/dns/status`)
  15029. ]);
  15030. if (settingsRes.ok) {
  15031. state.dnsSettings = await settingsRes.json();
  15032. populateDNSSettingsForm(state.dnsSettings);
  15033. }
  15034. if (staticRes.ok) {
  15035. state.dnsStaticRecords = await staticRes.json();
  15036. renderStaticDNSList();
  15037. }
  15038. if (statusRes.ok) {
  15039. state.dnsStatus = await statusRes.json();
  15040. updateDNSStatusView(state.dnsStatus);
  15041. }
  15042. } catch (err) {
  15043. console.error('Failed to load DNS settings:', err);
  15044. }
  15045. }
  15046. function populateDNSSettingsForm(s) {
  15047. if (!s) return;
  15048. const dnsForm = document.getElementById('form-dns-settings');
  15049. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  15050. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  15051. if (dynamicEl) {
  15052. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  15053. 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(' ');
  15054. } else {
  15055. dynamicEl.innerText = 'None';
  15056. }
  15057. }
  15058. // If user is actively typing or editing in the form, do not overwrite their inputs!
  15059. if (isEditing) return;
  15060. const serversInput = document.getElementById('dns-servers-input');
  15061. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  15062. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  15063. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  15064. const domainInput = document.getElementById('dns-domain-input');
  15065. if (domainInput) domainInput.value = s.domain || '';
  15066. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  15067. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  15068. }
  15069. function updateDNSStatusView(st) {
  15070. if (!st) return;
  15071. const preview = document.getElementById('dns-resolv-preview');
  15072. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15073. const pillText = document.getElementById('dns-live-status-text');
  15074. const pill = document.getElementById('dns-live-status-pill');
  15075. if (pill && pillText) {
  15076. if (st.service_running) {
  15077. 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';
  15078. pillText.innerText = 'DNS Service Active';
  15079. } else {
  15080. 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';
  15081. pillText.innerText = 'DNS Service Inactive';
  15082. }
  15083. }
  15084. }
  15085. function appendDNSPreset(preset) {
  15086. const input = document.getElementById('dns-servers-input');
  15087. if (!input) return;
  15088. const dnsForm = document.getElementById('form-dns-settings');
  15089. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15090. const current = input.value.trim();
  15091. if (!current) {
  15092. input.value = preset;
  15093. } else {
  15094. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15095. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15096. toAdd.forEach(ip => {
  15097. if (!existing.includes(ip)) existing.push(ip);
  15098. });
  15099. input.value = existing.join(', ');
  15100. }
  15101. }
  15102. async function saveDNSSettings(e) {
  15103. e.preventDefault();
  15104. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15105. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15106. if (servers.length === 0) {
  15107. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15108. return;
  15109. }
  15110. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15111. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15112. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15113. try {
  15114. const res = await fetch(`${API_BASE}/dns/settings`, {
  15115. method: 'POST',
  15116. headers: { 'Content-Type': 'application/json' },
  15117. body: JSON.stringify({
  15118. servers: servers,
  15119. cache_size: cacheSize,
  15120. domain: domain,
  15121. allow_remote_requests: allowRemote
  15122. })
  15123. });
  15124. const data = await res.json();
  15125. if (res.ok) {
  15126. const dnsForm = document.getElementById('form-dns-settings');
  15127. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15128. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15129. loadDNSSettings();
  15130. } else {
  15131. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15132. }
  15133. } catch (err) {
  15134. showToast('Error', err.message, 'error');
  15135. }
  15136. }
  15137. async function flushDNSCache() {
  15138. try {
  15139. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15140. if (res.ok) {
  15141. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15142. loadDNSSettings();
  15143. } else {
  15144. const err = await res.json();
  15145. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15146. }
  15147. } catch (err) {
  15148. showToast('Error', err.message, 'error');
  15149. }
  15150. }
  15151. function renderStaticDNSList() {
  15152. const tbody = document.getElementById('dns-static-tbody');
  15153. const empty = document.getElementById('dns-static-empty');
  15154. const badge = document.getElementById('dns-static-count-badge');
  15155. if (!tbody) return;
  15156. tbody.innerHTML = '';
  15157. const records = state.dnsStaticRecords || [];
  15158. if (badge) badge.innerText = `${records.length} Records`;
  15159. if (records.length === 0) {
  15160. empty?.classList.remove('hidden');
  15161. return;
  15162. }
  15163. empty?.classList.add('hidden');
  15164. records.forEach(rec => {
  15165. const tr = document.createElement('tr');
  15166. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15167. tr.innerHTML = `
  15168. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15169. <td class="py-2.5 px-4">
  15170. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15171. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15172. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15173. }">
  15174. ${rec.type || 'A'}
  15175. </span>
  15176. </td>
  15177. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15178. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15179. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15180. <td class="py-2.5 px-4">
  15181. <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'}">
  15182. ${rec.disabled ? 'Disabled' : 'Active'}
  15183. </span>
  15184. </td>
  15185. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15186. <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>
  15187. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15188. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15189. </td>
  15190. `;
  15191. tbody.appendChild(tr);
  15192. });
  15193. }
  15194. function openStaticDNSModal(id = null) {
  15195. const modal = document.getElementById('modal-static-dns');
  15196. const title = document.getElementById('modal-static-dns-title');
  15197. const form = document.getElementById('form-static-dns');
  15198. if (!modal || !form) return;
  15199. form.reset();
  15200. document.getElementById('modal-static-dns-id').value = '';
  15201. if (id) {
  15202. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15203. if (rec) {
  15204. if (title) title.innerText = 'Edit Static DNS Record';
  15205. document.getElementById('modal-static-dns-id').value = rec.id;
  15206. document.getElementById('modal-static-dns-name').value = rec.name;
  15207. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15208. document.getElementById('modal-static-dns-addr').value = rec.address;
  15209. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15210. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15211. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15212. }
  15213. } else {
  15214. if (title) title.innerText = 'Add Static DNS Record';
  15215. }
  15216. modal.classList.remove('hidden');
  15217. }
  15218. function closeStaticDNSModal() {
  15219. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15220. }
  15221. async function submitSaveStaticDNS(e) {
  15222. e.preventDefault();
  15223. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15224. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15225. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15226. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15227. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15228. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15229. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15230. if (!name || !address) {
  15231. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15232. return;
  15233. }
  15234. try {
  15235. const res = await fetch(`${API_BASE}/dns/static`, {
  15236. method: 'POST',
  15237. headers: { 'Content-Type': 'application/json' },
  15238. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15239. });
  15240. const data = await res.json();
  15241. if (res.ok) {
  15242. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15243. closeStaticDNSModal();
  15244. loadDNSSettings();
  15245. } else {
  15246. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15247. }
  15248. } catch (err) {
  15249. showToast('Error', err.message, 'error');
  15250. }
  15251. }
  15252. async function deleteStaticDNS(id) {
  15253. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15254. try {
  15255. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15256. if (res.ok) {
  15257. showToast('Deleted', 'Static DNS record deleted', 'success');
  15258. loadDNSSettings();
  15259. }
  15260. } catch (err) {
  15261. showToast('Error', err.message, 'error');
  15262. }
  15263. }
  15264. async function toggleStaticDNS(id, disabled) {
  15265. try {
  15266. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15267. method: 'POST',
  15268. headers: { 'Content-Type': 'application/json' },
  15269. body: JSON.stringify({ disabled })
  15270. });
  15271. if (res.ok) {
  15272. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15273. loadDNSSettings();
  15274. }
  15275. } catch (err) {
  15276. showToast('Error', err.message, 'error');
  15277. }
  15278. }
  15279. async function loadSystemSettings() {
  15280. try {
  15281. const sysForm = document.getElementById('form-system-settings');
  15282. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15283. const res = await fetch(`${API_BASE}/system/settings`);
  15284. if (res.ok) {
  15285. const data = await res.json();
  15286. if (!isEditing) {
  15287. const hostInput = document.getElementById('system-hostname-input');
  15288. if (hostInput) hostInput.value = data.hostname || '';
  15289. const tzInput = document.getElementById('system-timezone-input');
  15290. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15291. }
  15292. }
  15293. } catch (err) {
  15294. console.error('Failed to load system settings:', err);
  15295. }
  15296. }
  15297. async function saveSystemSettings(e) {
  15298. e.preventDefault();
  15299. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15300. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15301. try {
  15302. const res = await fetch(`${API_BASE}/system/settings`, {
  15303. method: 'POST',
  15304. headers: { 'Content-Type': 'application/json' },
  15305. body: JSON.stringify({ hostname, timezone })
  15306. });
  15307. const data = await res.json();
  15308. if (res.ok) {
  15309. const sysForm = document.getElementById('form-system-settings');
  15310. if (sysForm) sysForm.dataset.dirty = 'false';
  15311. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15312. const sideH = document.getElementById('side-hostname');
  15313. if (sideH) sideH.innerText = data.hostname;
  15314. } else {
  15315. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15316. }
  15317. } catch (err) {
  15318. showToast('Error', err.message, 'error');
  15319. }
  15320. }
  15321. // =============================================================================
  15322. // BACKUP & RESTORE MANAGER
  15323. // =============================================================================
  15324. state.selectedBackupFile = null;
  15325. state.inspectedBackupManifest = null;
  15326. state.pendingRestoreTarget = null;
  15327. state.backupsList = [];
  15328. async function exportBackupDownload() {
  15329. const btn = document.getElementById('btn-export-backup');
  15330. const commentInput = document.getElementById('backup-export-comment');
  15331. const comment = (commentInput?.value || '').trim();
  15332. const originalHtml = btn ? btn.innerHTML : '';
  15333. if (btn) {
  15334. btn.disabled = true;
  15335. 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...`;
  15336. }
  15337. try {
  15338. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15339. if (!res.ok) {
  15340. const err = await res.json().catch(() => ({}));
  15341. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15342. return;
  15343. }
  15344. const blob = await res.blob();
  15345. const disposition = res.headers.get('Content-Disposition') || '';
  15346. let filename = 'debtik-backup.zip';
  15347. const match = disposition.match(/filename="?([^";]+)"?/);
  15348. if (match && match[1]) {
  15349. filename = match[1];
  15350. }
  15351. const blobUrl = window.URL.createObjectURL(blob);
  15352. const a = document.createElement('a');
  15353. a.href = blobUrl;
  15354. a.download = filename;
  15355. document.body.appendChild(a);
  15356. a.click();
  15357. setTimeout(() => {
  15358. window.URL.revokeObjectURL(blobUrl);
  15359. a.remove();
  15360. }, 1000);
  15361. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15362. } catch (err) {
  15363. showToast('Export Error', err.message || 'Network error during download', 'error');
  15364. } finally {
  15365. if (btn) {
  15366. btn.disabled = false;
  15367. btn.innerHTML = originalHtml;
  15368. }
  15369. }
  15370. }
  15371. async function onBackupFileSelected(e) {
  15372. const file = e.target.files?.[0];
  15373. if (!file) return;
  15374. const label = document.getElementById('backup-file-label');
  15375. if (label) {
  15376. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15377. }
  15378. await inspectBackupFile(file);
  15379. }
  15380. async function inspectBackupFile(file) {
  15381. const preview = document.getElementById('backup-inspect-preview');
  15382. const restoreBtn = document.getElementById('btn-restore-backup');
  15383. const formData = new FormData();
  15384. formData.append('backup', file);
  15385. try {
  15386. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15387. method: 'POST',
  15388. body: formData
  15389. });
  15390. const data = await res.json();
  15391. if (!res.ok || !data.success || !data.manifest) {
  15392. if (preview) preview.classList.add('hidden');
  15393. if (restoreBtn) restoreBtn.disabled = true;
  15394. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15395. return;
  15396. }
  15397. const mf = data.manifest;
  15398. state.selectedBackupFile = file;
  15399. state.inspectedBackupManifest = mf;
  15400. const vEl = document.getElementById('backup-inspect-version');
  15401. const hEl = document.getElementById('backup-inspect-hostname');
  15402. const fEl = document.getElementById('backup-inspect-files');
  15403. const dEl = document.getElementById('backup-inspect-date');
  15404. const cEl = document.getElementById('backup-inspect-comment');
  15405. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15406. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15407. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15408. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15409. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15410. if (preview) preview.classList.remove('hidden');
  15411. if (restoreBtn) restoreBtn.disabled = false;
  15412. } catch (err) {
  15413. if (preview) preview.classList.add('hidden');
  15414. if (restoreBtn) restoreBtn.disabled = true;
  15415. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15416. }
  15417. }
  15418. function confirmRestoreBackup(localFilename = null) {
  15419. const modal = document.getElementById('modal-restore-confirm');
  15420. const details = document.getElementById('modal-restore-details');
  15421. const progress = document.getElementById('modal-restore-progress');
  15422. const cancelBtn = document.getElementById('btn-cancel-restore');
  15423. const execBtn = document.getElementById('btn-execute-restore');
  15424. if (progress) progress.classList.add('hidden');
  15425. if (cancelBtn) cancelBtn.disabled = false;
  15426. if (execBtn) {
  15427. execBtn.disabled = false;
  15428. execBtn.innerText = 'Yes, Restore & Reload';
  15429. }
  15430. if (localFilename) {
  15431. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15432. if (details) {
  15433. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15434. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15435. }
  15436. } else {
  15437. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15438. showToast('Error', 'Please select a valid backup archive first', 'error');
  15439. return;
  15440. }
  15441. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15442. const mf = state.inspectedBackupManifest;
  15443. if (details) {
  15444. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15445. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15446. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15447. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15448. }
  15449. }
  15450. if (modal) modal.classList.remove('hidden');
  15451. }
  15452. function closeRestoreModal() {
  15453. const modal = document.getElementById('modal-restore-confirm');
  15454. if (modal) modal.classList.add('hidden');
  15455. }
  15456. async function executeRestoreBackup() {
  15457. const target = state.pendingRestoreTarget;
  15458. if (!target) return;
  15459. const progress = document.getElementById('modal-restore-progress');
  15460. const progressText = document.getElementById('modal-restore-progress-text');
  15461. const cancelBtn = document.getElementById('btn-cancel-restore');
  15462. const execBtn = document.getElementById('btn-execute-restore');
  15463. if (cancelBtn) cancelBtn.disabled = true;
  15464. if (execBtn) execBtn.disabled = true;
  15465. if (progress) progress.classList.remove('hidden');
  15466. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15467. try {
  15468. let res;
  15469. if (target.type === 'file') {
  15470. const formData = new FormData();
  15471. formData.append('backup', target.file);
  15472. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15473. method: 'POST',
  15474. body: formData
  15475. });
  15476. } else {
  15477. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15478. method: 'POST'
  15479. });
  15480. }
  15481. const data = await res.json();
  15482. if (!res.ok || !data.success) {
  15483. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15484. if (cancelBtn) cancelBtn.disabled = false;
  15485. if (execBtn) execBtn.disabled = false;
  15486. if (progress) progress.classList.add('hidden');
  15487. return;
  15488. }
  15489. if (progressText) {
  15490. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15491. }
  15492. pollAfterRestoreReconnect();
  15493. } catch (err) {
  15494. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15495. if (cancelBtn) cancelBtn.disabled = false;
  15496. if (execBtn) execBtn.disabled = false;
  15497. if (progress) progress.classList.add('hidden');
  15498. }
  15499. }
  15500. function pollAfterRestoreReconnect() {
  15501. let attempts = 0;
  15502. const maxAttempts = 25;
  15503. const timer = setInterval(async () => {
  15504. attempts++;
  15505. try {
  15506. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15507. if (res.ok) {
  15508. clearInterval(timer);
  15509. closeRestoreModal();
  15510. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15511. setTimeout(() => {
  15512. window.location.reload();
  15513. }, 1200);
  15514. }
  15515. } catch (_) {
  15516. // Still restarting, retry
  15517. }
  15518. if (attempts >= maxAttempts) {
  15519. clearInterval(timer);
  15520. closeRestoreModal();
  15521. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15522. }
  15523. }, 1500);
  15524. }
  15525. async function loadBackupList() {
  15526. const tbody = document.getElementById('backups-table-tbody');
  15527. const empty = document.getElementById('backups-empty-state');
  15528. if (!tbody) return;
  15529. try {
  15530. const res = await fetch(`${API_BASE}/system/backups`);
  15531. if (!res.ok) return;
  15532. const list = await res.json();
  15533. state.backupsList = list || [];
  15534. renderBackupsTable(state.backupsList);
  15535. } catch (err) {
  15536. console.error('Failed to load backup list:', err);
  15537. }
  15538. }
  15539. function renderBackupsTable(backups) {
  15540. const tbody = document.getElementById('backups-table-tbody');
  15541. const empty = document.getElementById('backups-empty-state');
  15542. if (!tbody) return;
  15543. if (!backups || backups.length === 0) {
  15544. tbody.innerHTML = '';
  15545. if (empty) empty.classList.remove('hidden');
  15546. return;
  15547. }
  15548. if (empty) empty.classList.add('hidden');
  15549. tbody.innerHTML = backups.map(bk => {
  15550. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15551. const badge = isAuto
  15552. ? `<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>`
  15553. : `<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>`;
  15554. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15555. return `<tr class="hover:bg-slate-800/40 transition">
  15556. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15557. ${badge}
  15558. <span>${escapeHtml(bk.filename)}</span>
  15559. </td>
  15560. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15561. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15562. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15563. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15564. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15565. <td class="py-3 px-4 text-right space-x-2">
  15566. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15567. 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">
  15568. Download
  15569. </button>
  15570. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15571. 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">
  15572. Restore
  15573. </button>
  15574. </td>
  15575. </tr>`;
  15576. }).join('');
  15577. }
  15578. async function downloadLocalBackup(filename) {
  15579. try {
  15580. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15581. if (!res.ok) {
  15582. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15583. return;
  15584. }
  15585. const blob = await res.blob();
  15586. const blobUrl = window.URL.createObjectURL(blob);
  15587. const a = document.createElement('a');
  15588. a.href = blobUrl;
  15589. a.download = filename;
  15590. document.body.appendChild(a);
  15591. a.click();
  15592. setTimeout(() => {
  15593. window.URL.revokeObjectURL(blobUrl);
  15594. a.remove();
  15595. }, 1000);
  15596. } catch (err) {
  15597. showToast('Download Error', err.message, 'error');
  15598. }
  15599. }
  15600. // =============================================================================
  15601. // AUTHENTICATION & USER MANAGER
  15602. // =============================================================================
  15603. async function checkAuthStatus() {
  15604. try {
  15605. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15606. headers: {
  15607. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15608. }
  15609. });
  15610. if (res.ok) {
  15611. const user = await res.json();
  15612. state.currentUser = user;
  15613. updateUserProfileHeader(user);
  15614. hideLoginScreen();
  15615. state.isPolling = true;
  15616. fetchData();
  15617. initLiveTrafficStream();
  15618. return true;
  15619. } else {
  15620. showLoginScreen(false);
  15621. return false;
  15622. }
  15623. } catch (err) {
  15624. showLoginScreen(false);
  15625. return false;
  15626. }
  15627. }
  15628. function showLoginScreen(isExpired = false) {
  15629. const el = document.getElementById('login-screen');
  15630. if (el) el.classList.remove('hidden');
  15631. const errEl = document.getElementById('login-error');
  15632. const errTxt = document.getElementById('login-error-text');
  15633. if (isExpired && errEl && errTxt) {
  15634. errTxt.innerText = 'Session expired. Please sign in again.';
  15635. errEl.classList.remove('hidden');
  15636. } else if (errEl) {
  15637. errEl.classList.add('hidden');
  15638. }
  15639. const pwInput = document.getElementById('login-password');
  15640. if (pwInput) pwInput.value = '';
  15641. const userInput = document.getElementById('login-username');
  15642. if (userInput && !userInput.value) userInput.focus();
  15643. else if (pwInput) pwInput.focus();
  15644. }
  15645. function hideLoginScreen() {
  15646. const el = document.getElementById('login-screen');
  15647. if (el) el.classList.add('hidden');
  15648. const errEl = document.getElementById('login-error');
  15649. if (errEl) errEl.classList.add('hidden');
  15650. }
  15651. async function handleLoginSubmit(event) {
  15652. event.preventDefault();
  15653. const username = (document.getElementById('login-username')?.value || '').trim();
  15654. const password = document.getElementById('login-password')?.value || '';
  15655. const errEl = document.getElementById('login-error');
  15656. const errTxt = document.getElementById('login-error-text');
  15657. const btn = document.getElementById('login-submit-btn');
  15658. const btnText = document.getElementById('login-btn-text');
  15659. const spinner = document.getElementById('login-btn-spinner');
  15660. if (!username || !password) {
  15661. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15662. if (errEl) errEl.classList.remove('hidden');
  15663. return;
  15664. }
  15665. if (errEl) errEl.classList.add('hidden');
  15666. if (btn) btn.disabled = true;
  15667. if (btnText) btnText.innerText = 'Authenticating...';
  15668. if (spinner) spinner.classList.remove('hidden');
  15669. try {
  15670. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15671. method: 'POST',
  15672. headers: { 'Content-Type': 'application/json' },
  15673. body: JSON.stringify({ username, password })
  15674. });
  15675. const data = await res.json();
  15676. if (res.ok && data.success) {
  15677. localStorage.setItem('debtik_token', data.token);
  15678. state.currentUser = data.user;
  15679. updateUserProfileHeader(data.user);
  15680. hideLoginScreen();
  15681. state.isPolling = true;
  15682. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15683. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15684. navigate(hash);
  15685. fetchData();
  15686. initLiveTrafficStream();
  15687. // Ensure background telemetry polling is active
  15688. if (!window._telemetryInterval) {
  15689. window._telemetryInterval = setInterval(() => {
  15690. if (state.isPolling && state.currentUser && !document.hidden) {
  15691. fetchData(false);
  15692. }
  15693. }, 5000);
  15694. }
  15695. } else {
  15696. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15697. if (errEl) errEl.classList.remove('hidden');
  15698. }
  15699. } catch (err) {
  15700. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15701. if (errEl) errEl.classList.remove('hidden');
  15702. } finally {
  15703. if (btn) btn.disabled = false;
  15704. if (btnText) btnText.innerText = 'Sign In to Controller';
  15705. if (spinner) spinner.classList.add('hidden');
  15706. }
  15707. }
  15708. async function handleLogoutClick() {
  15709. try {
  15710. await originalFetch(`${API_BASE}/auth/logout`, {
  15711. method: 'POST',
  15712. headers: {
  15713. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15714. }
  15715. });
  15716. } catch (e) {}
  15717. stopSessionPolling();
  15718. localStorage.removeItem('debtik_token');
  15719. state.currentUser = null;
  15720. state.isPolling = false;
  15721. if (window._telemetryInterval) {
  15722. clearInterval(window._telemetryInterval);
  15723. window._telemetryInterval = null;
  15724. }
  15725. if (trafficEventSource) {
  15726. trafficEventSource.close();
  15727. trafficEventSource = null;
  15728. }
  15729. if (trafficPollFallback) {
  15730. clearInterval(trafficPollFallback);
  15731. trafficPollFallback = null;
  15732. }
  15733. showLoginScreen(false);
  15734. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15735. }
  15736. function togglePasswordVisibility(id) {
  15737. const input = document.getElementById(id);
  15738. if (!input) return;
  15739. input.type = input.type === 'password' ? 'text' : 'password';
  15740. }
  15741. function toggleUserMenu() {
  15742. const menu = document.getElementById('user-menu-dropdown');
  15743. if (menu) menu.classList.toggle('hidden');
  15744. }
  15745. function closeUserMenu() {
  15746. const menu = document.getElementById('user-menu-dropdown');
  15747. if (menu) menu.classList.add('hidden');
  15748. }
  15749. // Close user menu on outside click
  15750. document.addEventListener('click', (e) => {
  15751. const menu = document.getElementById('user-menu-dropdown');
  15752. if (!menu || menu.classList.contains('hidden')) return;
  15753. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15754. menu.classList.add('hidden');
  15755. }
  15756. });
  15757. function updateUserProfileHeader(user) {
  15758. if (!user) return;
  15759. const navName = document.getElementById('nav-user-name');
  15760. if (navName) navName.innerText = user.username;
  15761. const dropName = document.getElementById('dropdown-user-name');
  15762. if (dropName) dropName.innerText = user.username;
  15763. const navRole = document.getElementById('nav-user-role');
  15764. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15765. const navAvatar = document.getElementById('nav-user-avatar');
  15766. if (navAvatar) {
  15767. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15768. navAvatar.innerText = initials;
  15769. }
  15770. const statCurUser = document.getElementById('stat-current-user');
  15771. if (statCurUser) statCurUser.innerText = user.username;
  15772. const statCurRole = document.getElementById('stat-current-role');
  15773. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15774. // Role permissions UI visibility: hide user management for non-admins
  15775. const isFullAdmin = user.role === 'full';
  15776. const navUsers = document.getElementById('nav-users');
  15777. if (navUsers) {
  15778. if (isFullAdmin) navUsers.classList.remove('hidden');
  15779. else navUsers.classList.add('hidden');
  15780. }
  15781. const dropdownUsers = document.getElementById('dropdown-item-users');
  15782. if (dropdownUsers) {
  15783. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15784. else dropdownUsers.classList.add('hidden');
  15785. }
  15786. }
  15787. // ================= User Management CRUD =================
  15788. async function loadUsers(isManual = false) {
  15789. try {
  15790. const res = await fetch(`${API_BASE}/users`);
  15791. if (res.status === 403) {
  15792. const tbody = document.getElementById('users-table-tbody');
  15793. if (tbody) {
  15794. tbody.innerHTML = `
  15795. <tr>
  15796. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15797. <div class="inline-flex items-center gap-2">
  15798. <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>
  15799. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15800. </div>
  15801. </td>
  15802. </tr>
  15803. `;
  15804. }
  15805. return;
  15806. }
  15807. if (res.ok) {
  15808. state.users = await res.json();
  15809. renderUsersTable();
  15810. const totalUsers = document.getElementById('stat-total-users');
  15811. if (totalUsers) totalUsers.innerText = state.users.length;
  15812. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15813. const adminUsers = document.getElementById('stat-admin-users');
  15814. if (adminUsers) adminUsers.innerText = adminCount;
  15815. const badgeCount = document.getElementById('badge-users-count');
  15816. if (badgeCount) badgeCount.innerText = state.users.length;
  15817. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15818. }
  15819. } catch (err) {
  15820. console.error('Failed to load users:', err);
  15821. }
  15822. }
  15823. function renderUsersTable() {
  15824. const tbody = document.getElementById('users-table-tbody');
  15825. const emptyState = document.getElementById('users-empty-state');
  15826. if (!tbody) return;
  15827. tbody.innerHTML = '';
  15828. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15829. const filtered = (state.users || []).filter(u => {
  15830. if (!query) return true;
  15831. return u.username.toLowerCase().includes(query) ||
  15832. (u.role || '').toLowerCase().includes(query) ||
  15833. (u.comment || '').toLowerCase().includes(query);
  15834. });
  15835. if (filtered.length === 0) {
  15836. if (emptyState) emptyState.classList.remove('hidden');
  15837. return;
  15838. }
  15839. if (emptyState) emptyState.classList.add('hidden');
  15840. const currentAuthUser = state.currentUser?.username || '';
  15841. filtered.forEach(u => {
  15842. const isSelf = u.username === currentAuthUser;
  15843. const isFull = u.role === 'full';
  15844. const isWrite = u.role === 'write';
  15845. 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>`;
  15846. if (isFull) {
  15847. 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>`;
  15848. } else if (isWrite) {
  15849. 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>`;
  15850. }
  15851. const statusBadge = u.disabled
  15852. ? `<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>`
  15853. : `<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>`;
  15854. let lastLoginText = 'Never';
  15855. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15856. const dt = new Date(u.last_login_at);
  15857. lastLoginText = dt.toLocaleString();
  15858. }
  15859. const initials = u.username.slice(0, 2).toUpperCase();
  15860. const tr = document.createElement('tr');
  15861. tr.className = 'hover:bg-slate-800/40 transition group';
  15862. tr.innerHTML = `
  15863. <td class="py-3 px-4">
  15864. <div class="flex items-center gap-3">
  15865. <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">
  15866. ${initials}
  15867. </div>
  15868. <div>
  15869. <div class="font-bold text-white text-xs flex items-center gap-2">
  15870. <span>${escapeHtml(u.username)}</span>
  15871. ${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>' : ''}
  15872. </div>
  15873. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15874. </div>
  15875. </div>
  15876. </td>
  15877. <td class="py-3 px-4 font-sans">
  15878. ${roleBadge}
  15879. </td>
  15880. <td class="py-3 px-4 font-sans">
  15881. ${statusBadge}
  15882. </td>
  15883. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15884. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15885. </td>
  15886. <td class="py-3 px-4 text-slate-400 text-xs">
  15887. ${lastLoginText}
  15888. </td>
  15889. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15890. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15891. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15892. <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>
  15893. </button>
  15894. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15895. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15896. <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>
  15897. </button>
  15898. ${!isSelf ? `
  15899. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15900. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15901. <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>
  15902. </button>
  15903. ` : ''}
  15904. </td>
  15905. `;
  15906. tbody.appendChild(tr);
  15907. });
  15908. }
  15909. function openAddUserModal() {
  15910. document.getElementById('user-add-username').value = '';
  15911. document.getElementById('user-add-password').value = '';
  15912. document.getElementById('user-add-confirm').value = '';
  15913. document.getElementById('user-add-role').value = 'full';
  15914. document.getElementById('user-add-comment').value = '';
  15915. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15916. document.getElementById('user-add-username')?.focus();
  15917. }
  15918. function closeAddUserModal() {
  15919. document.getElementById('modal-add-user')?.classList.add('hidden');
  15920. }
  15921. async function submitAddUser(event) {
  15922. event.preventDefault();
  15923. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15924. const password = document.getElementById('user-add-password')?.value || '';
  15925. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15926. const role = document.getElementById('user-add-role')?.value || 'full';
  15927. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15928. if (password !== confirm) {
  15929. showToast('Validation Error', 'Passwords do not match', 'warning');
  15930. return;
  15931. }
  15932. if (password.length < 4) {
  15933. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15934. return;
  15935. }
  15936. try {
  15937. const res = await fetch(`${API_BASE}/users`, {
  15938. method: 'POST',
  15939. headers: { 'Content-Type': 'application/json' },
  15940. body: JSON.stringify({ username, password, role, comment })
  15941. });
  15942. const data = await res.json();
  15943. if (res.ok) {
  15944. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15945. closeAddUserModal();
  15946. loadUsers(false);
  15947. } else {
  15948. showToast('Error', data.message || 'Failed to create user', 'error');
  15949. }
  15950. } catch (err) {
  15951. showToast('Error', err.message, 'error');
  15952. }
  15953. }
  15954. function openEditUserModal(username) {
  15955. const user = (state.users || []).find(u => u.username === username);
  15956. if (!user) return;
  15957. document.getElementById('user-edit-username').value = user.username;
  15958. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15959. document.getElementById('user-edit-role').value = user.role || 'read';
  15960. document.getElementById('user-edit-comment').value = user.comment || '';
  15961. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15962. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15963. }
  15964. function closeEditUserModal() {
  15965. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15966. }
  15967. async function submitEditUser(event) {
  15968. event.preventDefault();
  15969. const username = document.getElementById('user-edit-username')?.value;
  15970. const role = document.getElementById('user-edit-role')?.value || 'read';
  15971. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15972. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15973. try {
  15974. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15975. method: 'PUT',
  15976. headers: { 'Content-Type': 'application/json' },
  15977. body: JSON.stringify({ role, comment, disabled })
  15978. });
  15979. const data = await res.json();
  15980. if (res.ok) {
  15981. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15982. closeEditUserModal();
  15983. loadUsers(false);
  15984. // If updated own role/disabled status, refresh self profile
  15985. if (username === state.currentUser?.username) {
  15986. checkAuthStatus();
  15987. }
  15988. } else {
  15989. showToast('Error', data.message || 'Failed to update user', 'error');
  15990. }
  15991. } catch (err) {
  15992. showToast('Error', err.message, 'error');
  15993. }
  15994. }
  15995. function openAdminResetPasswordModal(username) {
  15996. document.getElementById('admin-reset-username').value = username;
  15997. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15998. document.getElementById('admin-reset-new-pw').value = '';
  15999. document.getElementById('admin-reset-confirm-pw').value = '';
  16000. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  16001. document.getElementById('admin-reset-new-pw')?.focus();
  16002. }
  16003. function closeAdminResetPasswordModal() {
  16004. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  16005. }
  16006. async function submitAdminResetPassword(event) {
  16007. event.preventDefault();
  16008. const username = document.getElementById('admin-reset-username')?.value;
  16009. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  16010. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  16011. if (newPassword !== confirm) {
  16012. showToast('Validation Error', 'Passwords do not match', 'warning');
  16013. return;
  16014. }
  16015. if (newPassword.length < 4) {
  16016. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16017. return;
  16018. }
  16019. try {
  16020. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  16021. method: 'POST',
  16022. headers: { 'Content-Type': 'application/json' },
  16023. body: JSON.stringify({ new_password: newPassword })
  16024. });
  16025. const data = await res.json();
  16026. if (res.ok) {
  16027. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  16028. closeAdminResetPasswordModal();
  16029. } else {
  16030. showToast('Error', data.message || 'Failed to reset password', 'error');
  16031. }
  16032. } catch (err) {
  16033. showToast('Error', err.message, 'error');
  16034. }
  16035. }
  16036. async function deleteUser(username) {
  16037. if (username === state.currentUser?.username) {
  16038. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  16039. return;
  16040. }
  16041. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  16042. return;
  16043. }
  16044. try {
  16045. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16046. method: 'DELETE'
  16047. });
  16048. const data = await res.json();
  16049. if (res.ok) {
  16050. showToast('User Deleted', `User ${username} has been removed`, 'success');
  16051. loadUsers(false);
  16052. } else {
  16053. showToast('Error', data.message || 'Failed to delete user', 'error');
  16054. }
  16055. } catch (err) {
  16056. showToast('Error', err.message, 'error');
  16057. }
  16058. }
  16059. function openSelfPasswordModal() {
  16060. document.getElementById('self-current-password').value = '';
  16061. document.getElementById('self-new-password').value = '';
  16062. document.getElementById('self-confirm-password').value = '';
  16063. document.getElementById('modal-self-password')?.classList.remove('hidden');
  16064. document.getElementById('self-current-password')?.focus();
  16065. }
  16066. function closeSelfPasswordModal() {
  16067. document.getElementById('modal-self-password')?.classList.add('hidden');
  16068. }
  16069. async function submitSelfPassword(event) {
  16070. event.preventDefault();
  16071. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16072. const newPassword = document.getElementById('self-new-password')?.value || '';
  16073. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16074. if (newPassword !== confirm) {
  16075. showToast('Validation Error', 'New passwords do not match', 'warning');
  16076. return;
  16077. }
  16078. if (newPassword.length < 4) {
  16079. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16080. return;
  16081. }
  16082. try {
  16083. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16084. method: 'POST',
  16085. headers: { 'Content-Type': 'application/json' },
  16086. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16087. });
  16088. const data = await res.json();
  16089. if (res.ok) {
  16090. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16091. closeSelfPasswordModal();
  16092. } else {
  16093. showToast('Error', data.message || 'Failed to change password', 'error');
  16094. }
  16095. } catch (err) {
  16096. showToast('Error', err.message, 'error');
  16097. }
  16098. }
  16099. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16100. state.services = [];
  16101. async function loadServices(manual = false) {
  16102. try {
  16103. const res = await fetch(`${API_BASE}/system/services`);
  16104. if (!res.ok) throw new Error('Failed to load services');
  16105. const data = await res.json();
  16106. state.services = data || [];
  16107. renderServicesTable();
  16108. updateCertificatesBadges();
  16109. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16110. } catch (err) {
  16111. if (manual) showToast('Error', err.message, 'error');
  16112. }
  16113. }
  16114. function renderServicesTable() {
  16115. const tbody = document.getElementById('services-table-body');
  16116. if (!tbody) return;
  16117. if (!state.services || state.services.length === 0) {
  16118. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16119. return;
  16120. }
  16121. tbody.innerHTML = state.services.map(s => {
  16122. const isOff = s.disabled;
  16123. const statusBadge = isOff
  16124. ? '<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>'
  16125. : '<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>';
  16126. const toggleBtn = isOff
  16127. ? `<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>`
  16128. : `<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>`;
  16129. let certBadge = '';
  16130. if (s.name === 'www-ssl') {
  16131. if (s.certificate) {
  16132. 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>`;
  16133. } else {
  16134. 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>`;
  16135. }
  16136. }
  16137. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16138. return `
  16139. <tr class="hover:bg-slate-800/40 transition">
  16140. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16141. <td class="py-3 px-4">
  16142. <div class="flex items-center gap-2">
  16143. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16144. <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">
  16145. <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>
  16146. </button>
  16147. </div>
  16148. </td>
  16149. <td class="py-3 px-4">${statusBadge}</td>
  16150. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16151. <td class="py-3 px-4 text-right">
  16152. <div class="flex items-center justify-end gap-2">
  16153. <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">
  16154. <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>
  16155. <span>Edit</span>
  16156. </button>
  16157. ${toggleBtn}
  16158. </div>
  16159. </td>
  16160. </tr>
  16161. `;
  16162. }).join('');
  16163. }
  16164. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16165. document.getElementById('modal-service-name').value = serviceName;
  16166. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16167. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16168. document.getElementById('modal-service-port').value = currentPort;
  16169. const hintEl = document.getElementById('modal-service-port-hint');
  16170. const warnEl = document.getElementById('modal-service-warning');
  16171. const certGroup = document.getElementById('modal-service-cert-group');
  16172. const certSelect = document.getElementById('modal-service-cert-select');
  16173. if (serviceName === 'www') {
  16174. hintEl.textContent = 'Default HTTP web port: 80';
  16175. warnEl.classList.remove('hidden');
  16176. certGroup.classList.add('hidden');
  16177. } else if (serviceName === 'www-ssl') {
  16178. hintEl.textContent = 'Default HTTPS web port: 443';
  16179. warnEl.classList.remove('hidden');
  16180. certGroup.classList.remove('hidden');
  16181. const populateCertOptions = (certs) => {
  16182. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16183. (certs || []).forEach(c => {
  16184. const opt = document.createElement('option');
  16185. opt.value = c.name;
  16186. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16187. if (c.name === currentCert) opt.selected = true;
  16188. certSelect.appendChild(opt);
  16189. });
  16190. };
  16191. if (state.certificates && state.certificates.length > 0) {
  16192. populateCertOptions(state.certificates);
  16193. } else {
  16194. loadCertificates(false).then(() => {
  16195. populateCertOptions(state.certificates);
  16196. });
  16197. }
  16198. } else if (serviceName === 'telnet') {
  16199. hintEl.textContent = 'Default Telnet console port: 8282';
  16200. warnEl.classList.add('hidden');
  16201. certGroup.classList.add('hidden');
  16202. } else if (serviceName === 'ssh') {
  16203. hintEl.textContent = 'Default SSH port: 2222';
  16204. warnEl.classList.add('hidden');
  16205. certGroup.classList.add('hidden');
  16206. } else {
  16207. hintEl.textContent = '';
  16208. warnEl.classList.add('hidden');
  16209. certGroup.classList.add('hidden');
  16210. }
  16211. const modal = document.getElementById('modal-service-edit');
  16212. modal.classList.remove('hidden');
  16213. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16214. }
  16215. function closeEditServiceModal() {
  16216. const modal = document.getElementById('modal-service-edit');
  16217. if (modal) modal.classList.add('hidden');
  16218. }
  16219. async function submitSaveServicePort(event) {
  16220. event.preventDefault();
  16221. const name = document.getElementById('modal-service-name').value;
  16222. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16223. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16224. if (isNaN(port) || port < 1 || port > 65535) {
  16225. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16226. return;
  16227. }
  16228. const certSelect = document.getElementById('modal-service-cert-select');
  16229. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16230. try {
  16231. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16232. method: 'POST',
  16233. headers: { 'Content-Type': 'application/json' },
  16234. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16235. });
  16236. if (!res.ok) {
  16237. const errData = await res.json();
  16238. throw new Error(errData.message || 'Failed to update service settings');
  16239. }
  16240. closeEditServiceModal();
  16241. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16242. await loadServices();
  16243. } catch (err) {
  16244. showToast('Error', err.message, 'error');
  16245. }
  16246. }
  16247. async function toggleServiceState(serviceName, newDisabled) {
  16248. if (serviceName === 'www' && newDisabled) {
  16249. 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?")) {
  16250. return;
  16251. }
  16252. }
  16253. if (serviceName === 'www-ssl' && !newDisabled) {
  16254. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16255. if (!sslSvc || !sslSvc.certificate) {
  16256. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16257. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16258. return;
  16259. }
  16260. }
  16261. try {
  16262. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16263. method: 'POST',
  16264. headers: { 'Content-Type': 'application/json' },
  16265. body: JSON.stringify({ disabled: newDisabled })
  16266. });
  16267. if (!res.ok) {
  16268. const errData = await res.json();
  16269. throw new Error(errData.message || 'Failed to update service');
  16270. }
  16271. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16272. await loadServices();
  16273. } catch (err) {
  16274. showToast('Error', err.message, 'error');
  16275. }
  16276. }
  16277. // ==================== SYSTEM LOGS (/log) ====================
  16278. state.logs = [];
  16279. let logsTimer = null;
  16280. async function loadLogs(manual = false) {
  16281. const limitEl = document.getElementById('logs-limit-select');
  16282. const limit = limitEl ? limitEl.value : '100';
  16283. try {
  16284. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16285. if (!res.ok) throw new Error('Failed to load logs');
  16286. const data = await res.json();
  16287. state.logs = data.logs || [];
  16288. renderLogsTable();
  16289. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16290. } catch (err) {
  16291. if (manual) showToast('Error', err.message, 'error');
  16292. }
  16293. // Setup auto-refresh if enabled and on logs tab
  16294. if (!logsTimer && state.currentUser) {
  16295. logsTimer = setInterval(() => {
  16296. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16297. const auto = document.getElementById('logs-auto-refresh');
  16298. if (auto && auto.checked) {
  16299. loadLogs(false);
  16300. }
  16301. }
  16302. }, 3000);
  16303. }
  16304. }
  16305. function renderLogsTable() {
  16306. const tbody = document.getElementById('logs-table-body');
  16307. if (!tbody) return;
  16308. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16309. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16310. const filtered = state.logs.filter(entry => {
  16311. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16312. return false;
  16313. }
  16314. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16315. return false;
  16316. }
  16317. return true;
  16318. });
  16319. if (filtered.length === 0) {
  16320. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16321. return;
  16322. }
  16323. tbody.innerHTML = filtered.map(l => {
  16324. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16325. const topLower = l.topics.toLowerCase();
  16326. if (topLower.includes('auth')) {
  16327. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16328. } else if (topLower.includes('dhcp')) {
  16329. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16330. } else if (topLower.includes('route')) {
  16331. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16332. } else if (topLower.includes('firewall')) {
  16333. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16334. } else if (topLower.includes('error')) {
  16335. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16336. } else if (topLower.includes('system')) {
  16337. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16338. }
  16339. const d = new Date(l.time);
  16340. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16341. return `
  16342. <tr class="hover:bg-slate-800/40 transition">
  16343. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16344. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16345. <td class="py-2 px-3 whitespace-nowrap">
  16346. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16347. </td>
  16348. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16349. </tr>
  16350. `;
  16351. }).join('');
  16352. }
  16353. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16354. state.certificates = [];
  16355. async function loadCertificates(manual = false) {
  16356. try {
  16357. const res = await fetch(`${API_BASE}/certificates`);
  16358. if (!res.ok) throw new Error('Failed to load certificates');
  16359. state.certificates = await res.json() || [];
  16360. updateCertificatesBadges();
  16361. renderCertificatesTable();
  16362. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16363. } catch (err) {
  16364. if (manual) showToast('Error', err.message, 'error');
  16365. }
  16366. }
  16367. function updateCertificatesBadges() {
  16368. const total = (state.certificates || []).length;
  16369. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16370. const bCount = document.getElementById('badge-certs-count');
  16371. if (bCount) bCount.innerText = total;
  16372. const kpiTotal = document.getElementById('kpi-certs-total');
  16373. if (kpiTotal) kpiTotal.innerText = total;
  16374. const kpiCA = document.getElementById('kpi-certs-ca');
  16375. if (kpiCA) kpiCA.innerText = caCount;
  16376. const kpiHttps = document.getElementById('kpi-https-status');
  16377. if (kpiHttps) {
  16378. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16379. if (sslSvc) {
  16380. if (!sslSvc.disabled) {
  16381. 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>`;
  16382. } else {
  16383. 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>`;
  16384. }
  16385. }
  16386. }
  16387. }
  16388. function renderCertificatesTable() {
  16389. const tbody = document.getElementById('certs-table-body');
  16390. if (!tbody) return;
  16391. if (!state.certificates || state.certificates.length === 0) {
  16392. 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>';
  16393. return;
  16394. }
  16395. tbody.innerHTML = state.certificates.map(c => {
  16396. let typeBadge = '';
  16397. if (c.is_ca) {
  16398. 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>';
  16399. } else if (c.type === 'acme') {
  16400. 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>';
  16401. } else if (c.issuer && c.issuer !== c.common_name) {
  16402. 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>';
  16403. } else {
  16404. 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>';
  16405. }
  16406. const sansHtml = (c.sans && c.sans.length > 0)
  16407. ? 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('')
  16408. : '<span class="text-slate-500">-</span>';
  16409. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16410. let validStr = '-';
  16411. let validBadge = '';
  16412. if (validTo && !isNaN(validTo.getTime())) {
  16413. const now = new Date();
  16414. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16415. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16416. if (daysLeft < 0) {
  16417. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16418. } else if (daysLeft < 30) {
  16419. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16420. } else {
  16421. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16422. }
  16423. }
  16424. return `
  16425. <tr class="hover:bg-slate-800/40 transition">
  16426. <td class="py-3 px-4">${typeBadge}</td>
  16427. <td class="py-3 px-4">
  16428. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16429. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16430. </td>
  16431. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16432. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16433. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16434. <span>${validStr}</span> ${validBadge}
  16435. ${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>` : ''}
  16436. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16437. </td>
  16438. <td class="py-3 px-4 text-right whitespace-nowrap">
  16439. <div class="flex items-center justify-end gap-1.5">
  16440. <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">
  16441. <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>
  16442. <span>View</span>
  16443. </button>
  16444. <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">
  16445. <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>
  16446. </button>
  16447. </div>
  16448. </td>
  16449. </tr>
  16450. `;
  16451. }).join('');
  16452. }
  16453. // Create CA
  16454. function openCreateCAModal() {
  16455. document.getElementById('form-create-ca').reset();
  16456. document.getElementById('ca-days').value = '3650';
  16457. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16458. document.getElementById('ca-country').value = 'GR';
  16459. document.getElementById('ca-key-type').value = 'RSA-2048';
  16460. document.getElementById('modal-create-ca').classList.remove('hidden');
  16461. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16462. }
  16463. function closeCreateCAModal() {
  16464. document.getElementById('modal-create-ca').classList.add('hidden');
  16465. }
  16466. async function submitCreateCA(event) {
  16467. event.preventDefault();
  16468. const payload = {
  16469. name: document.getElementById('ca-name').value.trim(),
  16470. common_name: document.getElementById('ca-cn').value.trim(),
  16471. organization: document.getElementById('ca-org').value.trim(),
  16472. country: document.getElementById('ca-country').value.trim(),
  16473. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16474. key_type: document.getElementById('ca-key-type').value
  16475. };
  16476. try {
  16477. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16478. method: 'POST',
  16479. headers: { 'Content-Type': 'application/json' },
  16480. body: JSON.stringify(payload)
  16481. });
  16482. if (!res.ok) {
  16483. const errData = await res.json();
  16484. throw new Error(errData.message || 'Failed to create CA');
  16485. }
  16486. closeCreateCAModal();
  16487. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16488. await loadCertificates();
  16489. } catch (err) {
  16490. showToast('Error', err.message, 'error');
  16491. }
  16492. }
  16493. // Create Cert
  16494. function openCreateCertModal() {
  16495. document.getElementById('form-create-cert').reset();
  16496. document.getElementById('cert-days').value = '730';
  16497. document.getElementById('cert-key-type').value = 'RSA-2048';
  16498. const caSelect = document.getElementById('cert-ca-select');
  16499. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16500. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16501. const opt = document.createElement('option');
  16502. opt.value = ca.name;
  16503. opt.textContent = `${ca.name} (${ca.common_name})`;
  16504. caSelect.appendChild(opt);
  16505. });
  16506. document.getElementById('modal-create-cert').classList.remove('hidden');
  16507. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16508. }
  16509. function closeCreateCertModal() {
  16510. document.getElementById('modal-create-cert').classList.add('hidden');
  16511. }
  16512. async function submitCreateCert(event) {
  16513. event.preventDefault();
  16514. const rawSans = document.getElementById('cert-sans').value;
  16515. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16516. const caName = document.getElementById('cert-ca-select').value;
  16517. const payload = {
  16518. name: document.getElementById('cert-name').value.trim(),
  16519. common_name: document.getElementById('cert-cn').value.trim(),
  16520. ca_name: caName,
  16521. sans: sansList,
  16522. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16523. key_type: document.getElementById('cert-key-type').value,
  16524. is_server: true
  16525. };
  16526. try {
  16527. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16528. method: 'POST',
  16529. headers: { 'Content-Type': 'application/json' },
  16530. body: JSON.stringify(payload)
  16531. });
  16532. if (!res.ok) {
  16533. const errData = await res.json();
  16534. throw new Error(errData.message || 'Failed to issue certificate');
  16535. }
  16536. closeCreateCertModal();
  16537. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16538. await loadCertificates();
  16539. } catch (err) {
  16540. showToast('Error', err.message, 'error');
  16541. }
  16542. }
  16543. // Let's Encrypt
  16544. function openLetsEncryptModal() {
  16545. document.getElementById('form-letsencrypt').reset();
  16546. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16547. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16548. }
  16549. function closeLetsEncryptModal() {
  16550. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16551. }
  16552. async function submitLetsEncrypt(event) {
  16553. event.preventDefault();
  16554. const domain = document.getElementById('le-domain').value.trim();
  16555. const email = document.getElementById('le-email').value.trim();
  16556. let name = document.getElementById('le-name').value.trim();
  16557. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16558. const staging = document.getElementById('le-staging').checked;
  16559. const btn = document.getElementById('btn-submit-letsencrypt');
  16560. const origBtnHtml = btn.innerHTML;
  16561. btn.disabled = true;
  16562. 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>`;
  16563. try {
  16564. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16565. method: 'POST',
  16566. headers: { 'Content-Type': 'application/json' },
  16567. body: JSON.stringify({
  16568. name: name,
  16569. domain: domain,
  16570. email: email,
  16571. staging: staging
  16572. })
  16573. });
  16574. if (!res.ok) {
  16575. const errData = await res.json();
  16576. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16577. }
  16578. closeLetsEncryptModal();
  16579. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16580. await loadCertificates();
  16581. } catch (err) {
  16582. showToast('Let\'s Encrypt Error', err.message, 'error');
  16583. } finally {
  16584. btn.disabled = false;
  16585. btn.innerHTML = origBtnHtml;
  16586. }
  16587. }
  16588. // Import Cert
  16589. function openImportCertModal() {
  16590. document.getElementById('form-import-cert').reset();
  16591. document.getElementById('modal-import-cert').classList.remove('hidden');
  16592. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16593. }
  16594. function closeImportCertModal() {
  16595. document.getElementById('modal-import-cert').classList.add('hidden');
  16596. }
  16597. async function submitImportCert(event) {
  16598. event.preventDefault();
  16599. const payload = {
  16600. name: document.getElementById('import-cert-name').value.trim(),
  16601. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16602. key_pem: document.getElementById('import-key-pem').value.trim()
  16603. };
  16604. try {
  16605. const res = await fetch(`${API_BASE}/certificates/import`, {
  16606. method: 'POST',
  16607. headers: { 'Content-Type': 'application/json' },
  16608. body: JSON.stringify(payload)
  16609. });
  16610. if (!res.ok) {
  16611. const errData = await res.json();
  16612. throw new Error(errData.message || 'Failed to import certificate');
  16613. }
  16614. closeImportCertModal();
  16615. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16616. await loadCertificates();
  16617. } catch (err) {
  16618. showToast('Error', err.message, 'error');
  16619. }
  16620. }
  16621. // View / Export Modal
  16622. async function openViewCertModal(name) {
  16623. const c = (state.certificates || []).find(x => x.name === name);
  16624. if (!c) return;
  16625. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16626. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16627. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16628. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16629. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16630. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16631. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16632. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16633. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16634. document.getElementById('modal-view-cert').classList.remove('hidden');
  16635. try {
  16636. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16637. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16638. const data = await res.json();
  16639. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16640. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16641. } catch (err) {
  16642. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16643. document.getElementById('view-key-pem-text').value = '';
  16644. }
  16645. }
  16646. function closeViewCertModal() {
  16647. document.getElementById('modal-view-cert').classList.add('hidden');
  16648. }
  16649. function copyCertPEM() {
  16650. const text = document.getElementById('view-cert-pem-text').value;
  16651. if (!text) return;
  16652. navigator.clipboard.writeText(text).then(() => {
  16653. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16654. }).catch(() => {
  16655. showToast('Error', 'Failed to copy to clipboard', 'error');
  16656. });
  16657. }
  16658. function copyKeyPEM() {
  16659. const text = document.getElementById('view-key-pem-text').value;
  16660. if (!text) return;
  16661. navigator.clipboard.writeText(text).then(() => {
  16662. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16663. }).catch(() => {
  16664. showToast('Error', 'Failed to copy to clipboard', 'error');
  16665. });
  16666. }
  16667. async function deleteCertificate(name) {
  16668. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16669. return;
  16670. }
  16671. try {
  16672. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16673. method: 'DELETE'
  16674. });
  16675. if (!res.ok) {
  16676. const errData = await res.json();
  16677. throw new Error(errData.message || 'Failed to delete certificate');
  16678. }
  16679. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16680. await loadCertificates();
  16681. } catch (err) {
  16682. showToast('Error', err.message, 'error');
  16683. }
  16684. }
  16685. // Refresh immediately when returning to a backgrounded controller tab.
  16686. document.addEventListener('visibilitychange', () => {
  16687. if (!state.currentUser) return;
  16688. if (document.hidden) {
  16689. if (trafficEventSource) trafficEventSource.close();
  16690. trafficEventSource = null;
  16691. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16692. trafficPollFallback = null;
  16693. } else {
  16694. fetchData(false);
  16695. initLiveTrafficStream();
  16696. if (state.activeTab === 'bwtest') loadBwTestView();
  16697. }
  16698. });
  16699. async function loadUpdateStatus(populate = true) {
  16700. try {
  16701. const res = await fetch(`${API_BASE}/update/status`);
  16702. if (!res.ok) throw new Error(await responseError(res));
  16703. const data = await res.json();
  16704. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16705. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16706. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16707. document.getElementById('update-state').textContent = data.state || 'idle';
  16708. document.getElementById('update-log').textContent = data.log || '';
  16709. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16710. }
  16711. async function saveUpdateConfig() {
  16712. try {
  16713. const repository = document.getElementById('update-repository').value.trim();
  16714. const branch = 'master';
  16715. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16716. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16717. if (!res.ok) throw new Error(await responseError(res));
  16718. document.getElementById('update-install-button').disabled = true;
  16719. document.getElementById('update-available').textContent = '—';
  16720. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16721. await loadUpdateStatus(false);
  16722. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16723. }
  16724. async function checkUpdate() {
  16725. try {
  16726. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16727. if (!res.ok) throw new Error(await responseError(res));
  16728. const data = await res.json();
  16729. document.getElementById('update-available').textContent = data.available_version;
  16730. document.getElementById('update-install-button').disabled = !data.update_available;
  16731. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16732. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16733. }
  16734. async function startUpdate(action) {
  16735. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16736. try {
  16737. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16738. if (!res.ok) throw new Error(await responseError(res));
  16739. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16740. await loadUpdateStatus(false);
  16741. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16742. }
  16743. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16744. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16745. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16746. function safeFirewallRow(row) {
  16747. const result = {...row};
  16748. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16749. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16750. return result;
  16751. }
  16752. function setFirewallDays(prefix, days) {
  16753. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16754. 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); }
  16755. }
  16756. function getFirewallDays(prefix) {
  16757. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16758. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16759. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16760. return selected.join(',');
  16761. }
  16762. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16763. const id = document.getElementById(kind+'-modal-id')?.value;
  16764. if (!id) { resetDisplay(); return; }
  16765. try {
  16766. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16767. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16768. resetDisplay(); await loadFirewall(false);
  16769. } catch(error) { showToast('Error', error.message, 'error'); }
  16770. }
  16771. function reviewLegacyFirewallSettings(kind, id) {
  16772. if (!id) return true;
  16773. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16774. const rule = (rows || []).find(r => r.id === id);
  16775. if (!rule) return true;
  16776. 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'];
  16777. const present = unsupported.filter(key => rule[key]);
  16778. if (!present.length) return true;
  16779. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16780. }
  16781. function refreshFirewallRejectTypes() {
  16782. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16783. const old=select.value;
  16784. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16785. 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'];
  16786. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16787. if(types.includes(old))select.value=old;
  16788. }
  16789. function setFirewallActionSelection(kind, value) {
  16790. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16791. if(!Array.from(select.options).some(option=>option.value===value)) {
  16792. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16793. }
  16794. select.value=value;
  16795. }
  16796. // ==========================================
  16797. // REVERSE PROXY & APPLICATION GATEWAY
  16798. // ==========================================
  16799. state.proxyRules = [];
  16800. state.proxyConfig = null;
  16801. async function loadReverseProxy(manual = false) {
  16802. try {
  16803. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16804. fetch(`${API_BASE}/proxy/config`),
  16805. fetch(`${API_BASE}/proxy/rules`),
  16806. fetch(`${API_BASE}/certificates`).catch(() => null)
  16807. ]);
  16808. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16809. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16810. state.proxyConfig = await cfgRes.json();
  16811. state.proxyRules = await rulesRes.json() || [];
  16812. if (certsRes && certsRes.ok) {
  16813. state.certificates = await certsRes.json() || [];
  16814. }
  16815. renderProxyRules(state.proxyRules);
  16816. updateProxyMetrics();
  16817. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16818. } catch (err) {
  16819. console.error('loadReverseProxy error:', err);
  16820. if (manual) showToast('Error', err.message, 'error');
  16821. }
  16822. }
  16823. function updateProxyMetrics() {
  16824. const badge = document.getElementById('badge-proxy-count');
  16825. if (badge) badge.textContent = (state.proxyRules || []).length;
  16826. const metricRules = document.getElementById('proxy-metric-rules');
  16827. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16828. const cfg = state.proxyConfig;
  16829. const statusEl = document.getElementById('proxy-metric-status');
  16830. const portsEl = document.getElementById('proxy-metric-ports');
  16831. if (cfg) {
  16832. if (statusEl) {
  16833. if (cfg.enabled) {
  16834. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16835. } else {
  16836. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16837. }
  16838. }
  16839. if (portsEl) {
  16840. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16841. }
  16842. }
  16843. let totalRequests = 0;
  16844. const certSet = new Set();
  16845. (state.proxyRules || []).forEach(r => {
  16846. totalRequests += (r.stats && r.stats.requests) || 0;
  16847. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16848. });
  16849. const metricRequests = document.getElementById('proxy-metric-requests');
  16850. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16851. const metricCerts = document.getElementById('proxy-metric-certs');
  16852. if (metricCerts) metricCerts.textContent = certSet.size;
  16853. }
  16854. function renderProxyRules(rules) {
  16855. const tbody = document.getElementById('proxy-rules-table-body');
  16856. if (!tbody) return;
  16857. if (!rules || rules.length === 0) {
  16858. 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>';
  16859. return;
  16860. }
  16861. tbody.innerHTML = rules.map(r => {
  16862. const isEnabled = r.enabled !== false;
  16863. 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>';
  16864. 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>`;
  16865. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16866. 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>';
  16867. 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>';
  16868. 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>` : '';
  16869. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16870. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16871. return `
  16872. <tr class="hover:bg-slate-800/40 transition">
  16873. <td class="py-3 px-4">
  16874. <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'}">
  16875. <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>
  16876. </button>
  16877. </td>
  16878. <td class="py-3 px-4">
  16879. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16880. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16881. </td>
  16882. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16883. ${domainsStr}
  16884. </td>
  16885. <td class="py-3 px-4">
  16886. ${pathBadge}
  16887. </td>
  16888. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16889. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16890. </td>
  16891. <td class="py-3 px-4 whitespace-nowrap">
  16892. ${protoBadge}${certBadge}
  16893. </td>
  16894. <td class="py-3 px-4 font-mono">
  16895. ${stripBadge}
  16896. </td>
  16897. <td class="py-3 px-4 font-mono text-slate-300">
  16898. ${requests}
  16899. </td>
  16900. <td class="py-3 px-4 text-right whitespace-nowrap">
  16901. <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>
  16902. <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>
  16903. </td>
  16904. </tr>
  16905. `;
  16906. }).join('');
  16907. }
  16908. function populateProxyCertDropdown(selectedVal = '') {
  16909. const select = document.getElementById('proxy-rule-cert');
  16910. if (!select) return;
  16911. const certs = state.certificates || [];
  16912. select.innerHTML = '<option value="">(None / Use Default 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 populateDefaultProxyCertDropdown(selectedVal = '') {
  16925. const select = document.getElementById('proxy-cfg-default-cert');
  16926. if (!select) return;
  16927. const certs = state.certificates || [];
  16928. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16929. certs.filter(c => !c.is_ca).forEach(c => {
  16930. const opt = document.createElement('option');
  16931. opt.value = c.name;
  16932. const cn = c.common_name ? ` (${c.common_name})` : '';
  16933. opt.textContent = `${c.name}${cn}`;
  16934. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16935. opt.selected = true;
  16936. }
  16937. select.appendChild(opt);
  16938. });
  16939. }
  16940. function onProxyProtoChange() {
  16941. const proto = document.getElementById('proxy-rule-proto')?.value;
  16942. const certSelect = document.getElementById('proxy-rule-cert');
  16943. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16944. if (proto === 'http') {
  16945. if (certSelect) certSelect.disabled = true;
  16946. if (redirectCheck) redirectCheck.disabled = true;
  16947. } else {
  16948. if (certSelect) certSelect.disabled = false;
  16949. if (redirectCheck) redirectCheck.disabled = false;
  16950. }
  16951. }
  16952. function openAddProxyRuleModal() {
  16953. const modal = document.getElementById('modal-proxy-rule');
  16954. if (!modal) return;
  16955. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16956. <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>
  16957. <span>Add Reverse Proxy Rule</span>
  16958. `;
  16959. document.getElementById('proxy-rule-id').value = '';
  16960. document.getElementById('proxy-rule-name').value = '';
  16961. document.getElementById('proxy-rule-domains').value = '';
  16962. document.getElementById('proxy-rule-path').value = '/';
  16963. document.getElementById('proxy-rule-target').value = '';
  16964. document.getElementById('proxy-rule-proto').value = 'both';
  16965. document.getElementById('proxy-rule-strip-path').checked = false;
  16966. document.getElementById('proxy-rule-http-to-https').checked = false;
  16967. document.getElementById('proxy-rule-preserve-host').checked = false;
  16968. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16969. document.getElementById('proxy-rule-enabled').checked = true;
  16970. document.getElementById('proxy-rule-comment').value = '';
  16971. populateProxyCertDropdown('');
  16972. onProxyProtoChange();
  16973. modal.classList.remove('hidden');
  16974. }
  16975. function openEditProxyRuleModal(id) {
  16976. const modal = document.getElementById('modal-proxy-rule');
  16977. if (!modal) return;
  16978. const rule = (state.proxyRules || []).find(r => r.id === id);
  16979. if (!rule) {
  16980. showToast('Error', 'Rule not found', 'error');
  16981. return;
  16982. }
  16983. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16984. <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>
  16985. <span>Edit Reverse Proxy Rule</span>
  16986. `;
  16987. document.getElementById('proxy-rule-id').value = rule.id || '';
  16988. document.getElementById('proxy-rule-name').value = rule.name || '';
  16989. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16990. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16991. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16992. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16993. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16994. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16995. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16996. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16997. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16998. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16999. populateProxyCertDropdown(rule.certificate || '');
  17000. onProxyProtoChange();
  17001. modal.classList.remove('hidden');
  17002. }
  17003. function closeProxyRuleModal() {
  17004. const modal = document.getElementById('modal-proxy-rule');
  17005. if (modal) modal.classList.add('hidden');
  17006. }
  17007. async function saveProxyRule(event) {
  17008. event.preventDefault();
  17009. const id = document.getElementById('proxy-rule-id').value;
  17010. const name = document.getElementById('proxy-rule-name').value.trim();
  17011. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  17012. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  17013. const target = document.getElementById('proxy-rule-target').value.trim();
  17014. const proto = document.getElementById('proxy-rule-proto').value;
  17015. const cert = document.getElementById('proxy-rule-cert').value;
  17016. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  17017. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  17018. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  17019. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  17020. const enabled = document.getElementById('proxy-rule-enabled').checked;
  17021. const comment = document.getElementById('proxy-rule-comment').value.trim();
  17022. let domains = [];
  17023. if (rawDomains && rawDomains !== '*') {
  17024. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  17025. }
  17026. const payload = {
  17027. id: id || undefined,
  17028. name,
  17029. domains,
  17030. path: pathVal,
  17031. target_url: target,
  17032. protocol: proto,
  17033. certificate: cert,
  17034. strip_path: stripPath,
  17035. http_to_https: httpToHttps,
  17036. preserve_host: preserveHost,
  17037. insecure_tls: insecureTLS,
  17038. enabled,
  17039. comment
  17040. };
  17041. try {
  17042. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  17043. const method = id ? 'PUT' : 'POST';
  17044. const res = await fetch(url, {
  17045. method,
  17046. headers: { 'Content-Type': 'application/json' },
  17047. body: JSON.stringify(payload)
  17048. });
  17049. if (!res.ok) {
  17050. const errData = await res.json().catch(() => ({}));
  17051. throw new Error(errData.message || 'Failed to save proxy rule');
  17052. }
  17053. closeProxyRuleModal();
  17054. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  17055. await loadReverseProxy(false);
  17056. } catch (err) {
  17057. showToast('Error', err.message, 'error');
  17058. }
  17059. }
  17060. async function deleteProxyRule(id) {
  17061. const rule = (state.proxyRules || []).find(r => r.id === id);
  17062. const name = rule ? rule.name : id;
  17063. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  17064. return;
  17065. }
  17066. try {
  17067. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  17068. method: 'DELETE'
  17069. });
  17070. if (!res.ok) {
  17071. const errData = await res.json().catch(() => ({}));
  17072. throw new Error(errData.message || 'Failed to delete rule');
  17073. }
  17074. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17075. await loadReverseProxy(false);
  17076. } catch (err) {
  17077. showToast('Error', err.message, 'error');
  17078. }
  17079. }
  17080. async function toggleProxyRuleState(id, currentState) {
  17081. try {
  17082. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17083. method: 'POST',
  17084. headers: { 'Content-Type': 'application/json' },
  17085. body: JSON.stringify({ enabled: !currentState })
  17086. });
  17087. if (!res.ok) {
  17088. const errData = await res.json().catch(() => ({}));
  17089. throw new Error(errData.message || 'Failed to toggle rule state');
  17090. }
  17091. await loadReverseProxy(false);
  17092. } catch (err) {
  17093. showToast('Error', err.message, 'error');
  17094. }
  17095. }
  17096. function openProxyConfigModal() {
  17097. const modal = document.getElementById('modal-proxy-config');
  17098. if (!modal) return;
  17099. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17100. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17101. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17102. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17103. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17104. modal.classList.remove('hidden');
  17105. }
  17106. function closeProxyConfigModal() {
  17107. const modal = document.getElementById('modal-proxy-config');
  17108. if (modal) modal.classList.add('hidden');
  17109. }
  17110. async function saveProxyConfig(event) {
  17111. event.preventDefault();
  17112. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17113. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17114. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17115. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17116. const payload = {
  17117. enabled,
  17118. http_port: httpPort,
  17119. https_port: httpsPort,
  17120. default_cert: defaultCert
  17121. };
  17122. try {
  17123. const res = await fetch(`${API_BASE}/proxy/config`, {
  17124. method: 'POST',
  17125. headers: { 'Content-Type': 'application/json' },
  17126. body: JSON.stringify(payload)
  17127. });
  17128. if (!res.ok) {
  17129. const errData = await res.json().catch(() => ({}));
  17130. throw new Error(errData.message || 'Failed to update proxy settings');
  17131. }
  17132. closeProxyConfigModal();
  17133. showToast('Success', 'Reverse proxy settings updated', 'success');
  17134. await loadReverseProxy(false);
  17135. } catch (err) {
  17136. showToast('Error', err.message, 'error');
  17137. }
  17138. }
  17139. // ==================== SD-WAN Controller ====================
  17140. async function loadSDWAN(manual = false) {
  17141. try {
  17142. const [groupsRes, telemetryRes] = await Promise.all([
  17143. fetch(`${API_BASE}/sdwan/groups`),
  17144. fetch(`${API_BASE}/sdwan/telemetry`)
  17145. ]);
  17146. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17147. state.sdwanGroups = await groupsRes.json() || [];
  17148. if (telemetryRes.ok) {
  17149. state.sdwanTelemetry = await telemetryRes.json() || {};
  17150. }
  17151. renderSDWANGroups(state.sdwanGroups);
  17152. renderSDWANMembers(state.sdwanGroups);
  17153. updateSDWANMetrics(state.sdwanTelemetry);
  17154. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17155. } catch (err) {
  17156. console.error('loadSDWAN error:', err);
  17157. if (manual) showToast('Error', err.message, 'error');
  17158. }
  17159. }
  17160. function updateSDWANMetrics(telemetry) {
  17161. const groups = state.sdwanGroups || [];
  17162. const t = telemetry || {};
  17163. const badge = document.getElementById('badge-sdwan-count');
  17164. if (badge) badge.textContent = groups.length;
  17165. const metricGroups = document.getElementById('sdwan-metric-groups');
  17166. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17167. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17168. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17169. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17170. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17171. const metricDown = document.getElementById('sdwan-metric-down');
  17172. if (metricDown) metricDown.textContent = t.down_members || 0;
  17173. }
  17174. function renderSDWANGroups(groups) {
  17175. const tbody = document.getElementById('sdwan-groups-table-body');
  17176. if (!tbody) return;
  17177. if (!groups || groups.length === 0) {
  17178. 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>';
  17179. return;
  17180. }
  17181. tbody.innerHTML = groups.map(g => {
  17182. const isEnabled = g.disabled !== true;
  17183. const members = g.members || [];
  17184. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17185. // Build distribution progress bar
  17186. let distHtml = '';
  17187. if (members.length === 0) {
  17188. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17189. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17190. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17191. const segments = members.map((m, idx) => {
  17192. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17193. const col = colors[idx % colors.length];
  17194. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17195. }).join('');
  17196. const labels = members.map((m, idx) => {
  17197. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17198. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17199. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17200. }).join('');
  17201. distHtml = `
  17202. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17203. <div class="flex flex-wrap">${labels}</div>
  17204. `;
  17205. } else if (g.mode === 'lowest-latency') {
  17206. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17207. } else if (g.mode === 'lowest-loss') {
  17208. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17209. } else if (g.mode === 'failover') {
  17210. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17211. }
  17212. let modeBadge = '';
  17213. switch (g.mode) {
  17214. case 'weighted':
  17215. 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>';
  17216. break;
  17217. case 'pcc':
  17218. 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>';
  17219. break;
  17220. case 'lowest-latency':
  17221. 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>';
  17222. break;
  17223. case 'lowest-loss':
  17224. 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>';
  17225. break;
  17226. case 'failover':
  17227. 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>';
  17228. break;
  17229. default:
  17230. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17231. }
  17232. const autoNatBadge = g.auto_nat
  17233. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17234. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17235. return `
  17236. <tr class="hover:bg-slate-800/40 transition">
  17237. <td class="py-3 px-4">
  17238. <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'}">
  17239. <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>
  17240. </button>
  17241. </td>
  17242. <td class="py-3 px-4">
  17243. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17244. <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>
  17245. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17246. </div>
  17247. </td>
  17248. <td class="py-3 px-4">${modeBadge}</td>
  17249. <td class="py-3 px-4">${distHtml}</td>
  17250. <td class="py-3 px-4">
  17251. <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>
  17252. </td>
  17253. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17254. <td class="py-3 px-4">${autoNatBadge}</td>
  17255. <td class="py-3 px-4 text-right">
  17256. <div class="flex items-center justify-end gap-1.5">
  17257. <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">
  17258. <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>
  17259. </button>
  17260. <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">
  17261. <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>
  17262. </button>
  17263. <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">
  17264. <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>
  17265. </button>
  17266. </div>
  17267. </td>
  17268. </tr>
  17269. `;
  17270. }).join('');
  17271. }
  17272. function renderSDWANMembers(groups) {
  17273. const tbody = document.getElementById('sdwan-members-table-body');
  17274. if (!tbody) return;
  17275. const allMembers = [];
  17276. (groups || []).forEach(g => {
  17277. (g.members || []).forEach(m => {
  17278. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17279. });
  17280. });
  17281. if (allMembers.length === 0) {
  17282. 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>';
  17283. return;
  17284. }
  17285. tbody.innerHTML = allMembers.map(m => {
  17286. const isEnabled = m.disabled !== true;
  17287. 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>';
  17288. if (!isEnabled) {
  17289. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17290. } else if (m.status === 'DEGRADED') {
  17291. 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>';
  17292. } else if (m.status === 'DOWN') {
  17293. 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>';
  17294. }
  17295. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17296. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17297. return `
  17298. <tr class="hover:bg-slate-800/40 transition">
  17299. <td class="py-3 px-4">
  17300. <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'}">
  17301. <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>
  17302. </button>
  17303. </td>
  17304. <td class="py-3 px-4">
  17305. <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>
  17306. </td>
  17307. <td class="py-3 px-4">
  17308. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17309. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17310. </td>
  17311. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17312. <td class="py-3 px-4">
  17313. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17314. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17315. </td>
  17316. <td class="py-3 px-4">${statusBadge}</td>
  17317. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17318. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17319. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17320. </td>
  17321. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17322. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17323. </td>
  17324. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17325. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17326. </td>
  17327. <td class="py-3 px-4 text-right">
  17328. <div class="flex items-center justify-end gap-1.5">
  17329. <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">
  17330. <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>
  17331. </button>
  17332. <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">
  17333. <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>
  17334. </button>
  17335. </div>
  17336. </td>
  17337. </tr>
  17338. `;
  17339. }).join('');
  17340. }
  17341. // Modal handling for SD-WAN Groups
  17342. function openAddSDWANGroupModal() {
  17343. const modal = document.getElementById('modal-sdwan-group');
  17344. if (!modal) return;
  17345. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17346. document.getElementById('sdwan-group-id').value = '';
  17347. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17348. document.getElementById('sdwan-group-name').disabled = false;
  17349. document.getElementById('sdwan-group-mode').value = 'weighted';
  17350. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17351. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17352. document.getElementById('sdwan-group-probe-interval').value = 3;
  17353. document.getElementById('sdwan-group-auto-nat').checked = true;
  17354. document.getElementById('sdwan-group-comment').value = '';
  17355. modal.classList.remove('hidden');
  17356. }
  17357. function openEditSDWANGroupModal(id) {
  17358. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17359. if (!group) return;
  17360. const modal = document.getElementById('modal-sdwan-group');
  17361. if (!modal) return;
  17362. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17363. document.getElementById('sdwan-group-id').value = group.id;
  17364. document.getElementById('sdwan-group-name').value = group.name;
  17365. document.getElementById('sdwan-group-name').disabled = true;
  17366. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17367. if (group.mode === 'pcc') {
  17368. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17369. } else {
  17370. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17371. }
  17372. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17373. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17374. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17375. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17376. modal.classList.remove('hidden');
  17377. }
  17378. function closeSDWANGroupModal() {
  17379. const modal = document.getElementById('modal-sdwan-group');
  17380. if (modal) modal.classList.add('hidden');
  17381. }
  17382. function onSDWANModeChange() {
  17383. const mode = document.getElementById('sdwan-group-mode').value;
  17384. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17385. if (pccContainer) {
  17386. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17387. else pccContainer.classList.add('hidden');
  17388. }
  17389. }
  17390. async function saveSDWANGroup(event) {
  17391. event.preventDefault();
  17392. const id = document.getElementById('sdwan-group-id').value;
  17393. const name = document.getElementById('sdwan-group-name').value.trim();
  17394. const mode = document.getElementById('sdwan-group-mode').value;
  17395. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17396. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17397. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17398. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17399. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17400. const payload = {
  17401. id: id || undefined,
  17402. name,
  17403. mode,
  17404. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17405. probe_interval: probeInterval,
  17406. auto_nat: autoNAT,
  17407. comment,
  17408. members: existing ? existing.members : undefined
  17409. };
  17410. try {
  17411. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17412. method: 'POST',
  17413. headers: { 'Content-Type': 'application/json' },
  17414. body: JSON.stringify(payload)
  17415. });
  17416. if (!res.ok) {
  17417. const err = await res.json().catch(() => ({}));
  17418. throw new Error(err.message || 'Failed to save SD-WAN group');
  17419. }
  17420. closeSDWANGroupModal();
  17421. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17422. await loadSDWAN(false);
  17423. } catch (err) {
  17424. showToast('Error', err.message, 'error');
  17425. }
  17426. }
  17427. async function toggleSDWANGroupState(id, currentState) {
  17428. try {
  17429. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17430. method: 'POST',
  17431. headers: { 'Content-Type': 'application/json' },
  17432. body: JSON.stringify({ disabled: currentState })
  17433. });
  17434. if (!res.ok) throw new Error('Failed to update group state');
  17435. await loadSDWAN(false);
  17436. } catch (err) {
  17437. showToast('Error', err.message, 'error');
  17438. }
  17439. }
  17440. async function deleteSDWANGroup(id) {
  17441. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17442. const name = group ? group.name : id;
  17443. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17444. try {
  17445. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17446. method: 'DELETE'
  17447. });
  17448. if (!res.ok) {
  17449. const err = await res.json().catch(() => ({}));
  17450. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17451. }
  17452. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17453. await loadSDWAN(false);
  17454. } catch (err) {
  17455. showToast('Error', err.message, 'error');
  17456. }
  17457. }
  17458. // Modal handling for SD-WAN Members
  17459. function populateSDWANGroupsSelect(selectedId = '') {
  17460. const sel = document.getElementById('sdwan-member-group-id');
  17461. if (!sel) return;
  17462. sel.innerHTML = '';
  17463. (state.sdwanGroups || []).forEach(g => {
  17464. const opt = document.createElement('option');
  17465. opt.value = g.id;
  17466. opt.textContent = `${g.name} (${g.mode})`;
  17467. if (g.id === selectedId) opt.selected = true;
  17468. sel.appendChild(opt);
  17469. });
  17470. }
  17471. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17472. const sel = document.getElementById('sdwan-member-interface');
  17473. if (!sel) return;
  17474. sel.innerHTML = '';
  17475. (state.interfaces || []).forEach(i => {
  17476. const opt = document.createElement('option');
  17477. opt.value = i.name;
  17478. opt.textContent = `${i.name} (${i.role || i.type})`;
  17479. if (i.name === selectedVal) opt.selected = true;
  17480. sel.appendChild(opt);
  17481. });
  17482. }
  17483. function openAddSDWANMemberModal(defaultGroupId = null) {
  17484. const modal = document.getElementById('modal-sdwan-member');
  17485. if (!modal) return;
  17486. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17487. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17488. return;
  17489. }
  17490. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17491. document.getElementById('sdwan-member-id').value = '';
  17492. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17493. populateSDWANMemberInterfaceSelect();
  17494. document.getElementById('sdwan-member-gateway').value = '';
  17495. document.getElementById('sdwan-member-weight').value = 50;
  17496. document.getElementById('sdwan-member-priority').value = 1;
  17497. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17498. document.getElementById('sdwan-member-max-lat').value = 250;
  17499. document.getElementById('sdwan-member-max-loss').value = 20;
  17500. document.getElementById('sdwan-member-comment').value = '';
  17501. modal.classList.remove('hidden');
  17502. }
  17503. function openEditSDWANMemberModal(groupId, memberId) {
  17504. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17505. if (!group) return;
  17506. const member = (group.members || []).find(m => m.id === memberId);
  17507. if (!member) return;
  17508. const modal = document.getElementById('modal-sdwan-member');
  17509. if (!modal) return;
  17510. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17511. document.getElementById('sdwan-member-id').value = member.id;
  17512. populateSDWANGroupsSelect(group.id);
  17513. document.getElementById('sdwan-member-group-id').disabled = true;
  17514. populateSDWANMemberInterfaceSelect(member.interface);
  17515. document.getElementById('sdwan-member-interface').disabled = true;
  17516. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17517. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17518. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17519. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17520. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17521. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17522. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17523. modal.classList.remove('hidden');
  17524. }
  17525. function closeSDWANMemberModal() {
  17526. const modal = document.getElementById('modal-sdwan-member');
  17527. if (modal) {
  17528. document.getElementById('sdwan-member-group-id').disabled = false;
  17529. document.getElementById('sdwan-member-interface').disabled = false;
  17530. modal.classList.add('hidden');
  17531. }
  17532. }
  17533. async function saveSDWANMember(event) {
  17534. event.preventDefault();
  17535. const id = document.getElementById('sdwan-member-id').value;
  17536. let groupId = document.getElementById('sdwan-member-group-id').value;
  17537. let iface = document.getElementById('sdwan-member-interface').value;
  17538. // In edit mode with disabled selects, fallback to existing member data if needed
  17539. if (id) {
  17540. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17541. if (existingGroup) {
  17542. if (!groupId) groupId = existingGroup.id;
  17543. const mem = (existingGroup.members || []).find(m => m.id === id);
  17544. if (mem && !iface) iface = mem.interface;
  17545. }
  17546. }
  17547. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17548. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17549. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17550. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17551. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17552. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17553. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17554. const payload = {
  17555. id: id || undefined,
  17556. interface: iface,
  17557. gateway,
  17558. weight,
  17559. priority,
  17560. target_probe: targetProbe,
  17561. max_latency: maxLatency,
  17562. max_loss: maxLoss,
  17563. comment
  17564. };
  17565. try {
  17566. const method = id ? 'PUT' : 'POST';
  17567. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17568. method,
  17569. headers: { 'Content-Type': 'application/json' },
  17570. body: JSON.stringify(payload)
  17571. });
  17572. if (!res.ok) {
  17573. const err = await res.json().catch(() => ({}));
  17574. throw new Error(err.message || 'Failed to save member link');
  17575. }
  17576. closeSDWANMemberModal();
  17577. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17578. await loadSDWAN(false);
  17579. } catch (err) {
  17580. showToast('Error', err.message, 'error');
  17581. }
  17582. }
  17583. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17584. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17585. if (!group) return;
  17586. const member = (group.members || []).find(m => m.id === memberId);
  17587. if (!member) return;
  17588. const payload = {
  17589. ...member,
  17590. disabled: currentState
  17591. };
  17592. try {
  17593. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17594. method: 'PUT',
  17595. headers: { 'Content-Type': 'application/json' },
  17596. body: JSON.stringify(payload)
  17597. });
  17598. if (!res.ok) throw new Error('Failed to update member state');
  17599. await loadSDWAN(false);
  17600. } catch (err) {
  17601. showToast('Error', err.message, 'error');
  17602. }
  17603. }
  17604. async function deleteSDWANMember(groupId, iface) {
  17605. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17606. try {
  17607. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17608. method: 'DELETE'
  17609. });
  17610. if (!res.ok) {
  17611. const err = await res.json().catch(() => ({}));
  17612. throw new Error(err.message || 'Failed to remove member link');
  17613. }
  17614. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17615. await loadSDWAN(false);
  17616. } catch (err) {
  17617. showToast('Error', err.message, 'error');
  17618. }
  17619. }
  17620. // ==============================================================================
  17621. // DYNAMIC ROUTING: RIP MODULE
  17622. // ==============================================================================
  17623. state.ripInstances = [];
  17624. state.ripInterfaces = [];
  17625. state.ripNeighborsLive = [];
  17626. state.ripRoutes = [];
  17627. state.selectedRipRow = {};
  17628. state.activeRipTab = 'instances';
  17629. function switchRipTab(tab) {
  17630. state.activeRipTab = tab;
  17631. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17632. const pane = document.getElementById(`rip-pane-${t}`);
  17633. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17634. if (pane) {
  17635. if (t === tab) pane.classList.remove('hidden');
  17636. else pane.classList.add('hidden');
  17637. }
  17638. if (btn) {
  17639. if (t === tab) {
  17640. 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';
  17641. } else {
  17642. 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';
  17643. }
  17644. }
  17645. });
  17646. }
  17647. function selectRipRow(tab, id) {
  17648. if (!state.selectedRipRow) state.selectedRipRow = {};
  17649. state.selectedRipRow[tab] = id;
  17650. if (tab === 'instances') {
  17651. renderRipInstances();
  17652. const btnEn = document.getElementById('btn-rip-inst-enable');
  17653. const btnDis = document.getElementById('btn-rip-inst-disable');
  17654. const btnRem = document.getElementById('btn-rip-inst-remove');
  17655. if (btnEn) btnEn.disabled = false;
  17656. if (btnDis) btnDis.disabled = false;
  17657. if (btnRem) btnRem.disabled = false;
  17658. } else if (tab === 'interfaces') {
  17659. renderRipInterfaces();
  17660. const btnEn = document.getElementById('btn-rip-iface-enable');
  17661. const btnDis = document.getElementById('btn-rip-iface-disable');
  17662. const btnRem = document.getElementById('btn-rip-iface-remove');
  17663. if (btnEn) btnEn.disabled = false;
  17664. if (btnDis) btnDis.disabled = false;
  17665. if (btnRem) btnRem.disabled = false;
  17666. }
  17667. }
  17668. function renderRipInstances() {
  17669. const tbody = document.getElementById('rip-instances-table-body');
  17670. if (!tbody) return;
  17671. const countEl = document.getElementById('rip-instances-footer-count');
  17672. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17673. let list = state.ripInstances || [];
  17674. if (filter) {
  17675. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17676. }
  17677. if (countEl) countEl.innerText = list.length;
  17678. const selId = state.selectedRipRow?.instances;
  17679. tbody.innerHTML = list.map((inst, idx) => {
  17680. const isSel = inst.id === selId;
  17681. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17682. const flagD = inst.disabled
  17683. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  17684. : (inst.running
  17685. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  17686. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  17687. const redist = [];
  17688. if (inst.redistribute_connected) redist.push('conn');
  17689. if (inst.redistribute_static) redist.push('static');
  17690. if (inst.redistribute_bgp) redist.push('bgp');
  17691. if (inst.redistribute_ospf) redist.push('ospf');
  17692. if (inst.redistribute_default) redist.push('default');
  17693. return `
  17694. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17695. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17696. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17697. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17698. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17699. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17700. </td>
  17701. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${inst.version == 1 || inst.version === 'ripng' ? 'RIPng' : 'RIPv2'}</td>
  17702. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17703. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17704. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17705. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17706. </tr>
  17707. `;
  17708. }).join('');
  17709. }
  17710. function renderRipInterfaces() {
  17711. const tbody = document.getElementById('rip-interfaces-table-body');
  17712. if (!tbody) return;
  17713. const countEl = document.getElementById('rip-interfaces-footer-count');
  17714. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17715. let list = state.ripInterfaces || [];
  17716. if (filter) {
  17717. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17718. }
  17719. if (countEl) countEl.innerText = list.length;
  17720. const selId = state.selectedRipRow?.interfaces;
  17721. tbody.innerHTML = list.map((iface, idx) => {
  17722. const isSel = iface.id === selId;
  17723. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17724. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17725. return `
  17726. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17727. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17728. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17729. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17730. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17731. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17732. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17733. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17734. <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>
  17735. </tr>
  17736. `;
  17737. }).join('');
  17738. }
  17739. function renderRipNeighbors() {
  17740. const tbody = document.getElementById('rip-neighbors-table-body');
  17741. if (!tbody) return;
  17742. const countEl = document.getElementById('rip-neighbors-footer-count');
  17743. const list = state.ripNeighborsLive || [];
  17744. if (countEl) countEl.innerText = list.length;
  17745. tbody.innerHTML = list.map((nbr, 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-rose-300">${escapeHtml(nbr.address || '')}</td>
  17749. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17750. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17751. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17752. </tr>
  17753. `).join('');
  17754. }
  17755. function renderRipRoutes() {
  17756. const tbody = document.getElementById('rip-routes-table-body');
  17757. if (!tbody) return;
  17758. const countEl = document.getElementById('rip-routes-footer-count');
  17759. const list = state.ripRoutes || [];
  17760. if (countEl) countEl.innerText = list.length;
  17761. tbody.innerHTML = list.map((r, idx) => `
  17762. <tr class="hover:bg-[#1a2636] text-slate-300">
  17763. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17764. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17765. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17766. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17767. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17768. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17769. </tr>
  17770. `).join('');
  17771. }
  17772. function openRipInstanceModal() {
  17773. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17774. document.getElementById('modal-rip-instance-id').value = '';
  17775. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17776. document.getElementById('modal-rip-instance-version').value = '2';
  17777. document.getElementById('modal-rip-instance-update').value = '30';
  17778. document.getElementById('modal-rip-instance-timeout').value = '180';
  17779. document.getElementById('modal-rip-instance-garbage').value = '120';
  17780. document.getElementById('modal-rip-instance-metric').value = '1';
  17781. document.getElementById('modal-rip-instance-comment').value = '';
  17782. document.getElementById('modal-rip-instance-enabled').checked = true;
  17783. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17784. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17785. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17786. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17787. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17788. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17789. }
  17790. function openEditRipInstanceModal(id) {
  17791. const inst = (state.ripInstances || []).find(i => i.id === id);
  17792. if (!inst) return;
  17793. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17794. document.getElementById('modal-rip-instance-id').value = inst.id;
  17795. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17796. document.getElementById('modal-rip-instance-version').value = (inst.version == 1 || inst.version === 'ripng') ? '1' : '2';
  17797. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17798. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17799. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17800. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17801. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17802. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17803. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17804. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17805. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17806. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17807. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17808. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17809. }
  17810. function closeRipInstanceModal() {
  17811. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17812. }
  17813. async function submitRipInstance(e) {
  17814. e.preventDefault();
  17815. const id = document.getElementById('modal-rip-instance-id').value;
  17816. const payload = {
  17817. id: id || undefined,
  17818. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17819. version: parseInt(document.getElementById('modal-rip-instance-version').value, 10) || 2,
  17820. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17821. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17822. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17823. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17824. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17825. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17826. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17827. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17828. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17829. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17830. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17831. };
  17832. try {
  17833. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17834. method: 'POST',
  17835. headers: { 'Content-Type': 'application/json' },
  17836. body: JSON.stringify(payload)
  17837. });
  17838. if (!res.ok) throw new Error(await res.text());
  17839. closeRipInstanceModal();
  17840. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17841. await loadDynamicRouting(false);
  17842. } catch (err) {
  17843. showToast('Error', err.message, 'error');
  17844. }
  17845. }
  17846. async function enableSelectedRipInstance() {
  17847. const id = state.selectedRipRow?.instances;
  17848. if (!id) return;
  17849. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17850. await loadDynamicRouting(false);
  17851. }
  17852. async function disableSelectedRipInstance() {
  17853. const id = state.selectedRipRow?.instances;
  17854. if (!id) return;
  17855. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17856. await loadDynamicRouting(false);
  17857. }
  17858. async function removeSelectedRipInstance() {
  17859. const id = state.selectedRipRow?.instances;
  17860. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  17861. await fetch(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' });
  17862. state.selectedRipRow.instances = null;
  17863. await loadDynamicRouting(false);
  17864. }
  17865. function openRipInterfaceModal() {
  17866. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  17867. document.getElementById('modal-rip-iface-id').value = '';
  17868. const dl = document.getElementById('rip-iface-datalist');
  17869. if (dl) {
  17870. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17871. }
  17872. const instSel = document.getElementById('modal-rip-iface-instance');
  17873. if (instSel && instSel.tagName === 'SELECT') {
  17874. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17875. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17876. }
  17877. document.getElementById('modal-rip-iface-pattern').value = '*';
  17878. if (instSel) instSel.value = (state.ripInstances && state.ripInstances.length > 0) ? state.ripInstances[0].name : 'default';
  17879. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  17880. document.getElementById('modal-rip-iface-metric').value = '1';
  17881. document.getElementById('modal-rip-iface-comment').value = '';
  17882. document.getElementById('modal-rip-iface-enabled').checked = true;
  17883. document.getElementById('modal-rip-iface-passive').checked = false;
  17884. document.getElementById('modal-rip-iface-bfd').checked = false;
  17885. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17886. }
  17887. function openEditRipInterfaceModal(id) {
  17888. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  17889. if (!iface) return;
  17890. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  17891. document.getElementById('modal-rip-iface-id').value = iface.id;
  17892. const dl = document.getElementById('rip-iface-datalist');
  17893. if (dl) {
  17894. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  17895. }
  17896. const instSel = document.getElementById('modal-rip-iface-instance');
  17897. if (instSel && instSel.tagName === 'SELECT') {
  17898. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  17899. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  17900. instSel.value = iface.instance || 'default';
  17901. } else if (instSel) {
  17902. instSel.value = iface.instance || '';
  17903. }
  17904. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '*';
  17905. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  17906. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  17907. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  17908. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  17909. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  17910. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  17911. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17912. }
  17913. function closeRipInterfaceModal() {
  17914. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  17915. }
  17916. async function submitRipInterface(e) {
  17917. e.preventDefault();
  17918. const id = document.getElementById('modal-rip-iface-id').value;
  17919. const payload = {
  17920. id: id || undefined,
  17921. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  17922. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  17923. mode: document.getElementById('modal-rip-iface-mode').value,
  17924. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  17925. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  17926. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  17927. passive: document.getElementById('modal-rip-iface-passive').checked,
  17928. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  17929. };
  17930. try {
  17931. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  17932. method: 'POST',
  17933. headers: { 'Content-Type': 'application/json' },
  17934. body: JSON.stringify(payload)
  17935. });
  17936. if (!res.ok) throw new Error(await res.text());
  17937. closeRipInterfaceModal();
  17938. showToast('Saved', `RIP interface template saved`, 'success');
  17939. await loadDynamicRouting(false);
  17940. } catch (err) {
  17941. showToast('Error', err.message, 'error');
  17942. }
  17943. }
  17944. async function enableSelectedRipInterface() {
  17945. const id = state.selectedRipRow?.interfaces;
  17946. if (!id) return;
  17947. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17948. await loadDynamicRouting(false);
  17949. }
  17950. async function disableSelectedRipInterface() {
  17951. const id = state.selectedRipRow?.interfaces;
  17952. if (!id) return;
  17953. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17954. await loadDynamicRouting(false);
  17955. }
  17956. async function removeSelectedRipInterface() {
  17957. const id = state.selectedRipRow?.interfaces;
  17958. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  17959. await fetch(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' });
  17960. state.selectedRipRow.interfaces = null;
  17961. await loadDynamicRouting(false);
  17962. }
  17963. // ==============================================================================
  17964. // DYNAMIC ROUTING: BFD MODULE
  17965. // ==============================================================================
  17966. state.bfdInstance = null;
  17967. state.bfdInterfaces = [];
  17968. state.bfdNeighbors = [];
  17969. state.bfdSessions = [];
  17970. state.selectedBfdRow = {};
  17971. state.activeBfdTab = 'config';
  17972. function switchBfdTab(tab) {
  17973. state.activeBfdTab = tab;
  17974. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  17975. const pane = document.getElementById(`bfd-pane-${t}`);
  17976. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  17977. if (pane) {
  17978. if (t === tab) pane.classList.remove('hidden');
  17979. else pane.classList.add('hidden');
  17980. }
  17981. if (btn) {
  17982. if (t === tab) {
  17983. 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';
  17984. } else {
  17985. 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';
  17986. }
  17987. }
  17988. });
  17989. }
  17990. function selectBfdRow(tab, id) {
  17991. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  17992. state.selectedBfdRow[tab] = id;
  17993. if (tab === 'interfaces') {
  17994. renderBfdInterfaces();
  17995. const btnEn = document.getElementById('btn-bfd-iface-enable');
  17996. const btnDis = document.getElementById('btn-bfd-iface-disable');
  17997. const btnRem = document.getElementById('btn-bfd-iface-remove');
  17998. if (btnEn) btnEn.disabled = false;
  17999. if (btnDis) btnDis.disabled = false;
  18000. if (btnRem) btnRem.disabled = false;
  18001. } else if (tab === 'peers') {
  18002. renderBfdPeers();
  18003. const btnEn = document.getElementById('btn-bfd-peer-enable');
  18004. const btnDis = document.getElementById('btn-bfd-peer-disable');
  18005. const btnRem = document.getElementById('btn-bfd-peer-remove');
  18006. if (btnEn) btnEn.disabled = false;
  18007. if (btnDis) btnDis.disabled = false;
  18008. if (btnRem) btnRem.disabled = false;
  18009. }
  18010. }
  18011. function renderBfdConfig() {
  18012. const inst = state.bfdInstance;
  18013. const pill = document.getElementById('bfd-live-status-pill');
  18014. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  18015. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  18016. const peerStat = document.getElementById('bfd-stat-peers');
  18017. const sessStat = document.getElementById('bfd-stat-sessions');
  18018. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  18019. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  18020. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  18021. const isEnabled = inst && (inst.enabled || inst.running || (!inst.disabled && (state.bfdInterfaces || []).length > 0));
  18022. if (!inst || inst.disabled || !isEnabled) {
  18023. if (pill) {
  18024. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  18025. pill.innerText = 'DISABLED';
  18026. }
  18027. if (toggleBtn) {
  18028. toggleBtn.innerText = 'Enable BFD';
  18029. 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';
  18030. }
  18031. } else {
  18032. if (pill) {
  18033. if (inst.running) {
  18034. 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';
  18035. pill.innerText = 'RUNNING (ACTIVE)';
  18036. } else {
  18037. 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';
  18038. pill.innerText = 'CONFIGURED';
  18039. }
  18040. }
  18041. if (toggleBtn) {
  18042. toggleBtn.innerText = 'Disable BFD';
  18043. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  18044. }
  18045. }
  18046. }
  18047. async function toggleBfdGlobalState() {
  18048. const current = state.bfdInstance;
  18049. const isCurrentlyEnabled = current && (current.enabled || current.running) && !current.disabled;
  18050. const newEnabled = !isCurrentlyEnabled;
  18051. const newDisabled = !newEnabled;
  18052. try {
  18053. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  18054. method: 'POST',
  18055. headers: { 'Content-Type': 'application/json' },
  18056. body: JSON.stringify({ enabled: newEnabled, disabled: newDisabled })
  18057. });
  18058. if (!res.ok) throw new Error(await res.text());
  18059. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  18060. await loadDynamicRouting(false);
  18061. } catch (err) {
  18062. showToast('Error', err.message, 'error');
  18063. }
  18064. }
  18065. function renderBfdInterfaces() {
  18066. const tbody = document.getElementById('bfd-interfaces-table-body');
  18067. if (!tbody) return;
  18068. const countEl = document.getElementById('bfd-interfaces-footer-count');
  18069. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  18070. let list = state.bfdInterfaces || [];
  18071. if (filter) {
  18072. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18073. }
  18074. if (countEl) countEl.innerText = list.length;
  18075. const selId = state.selectedBfdRow?.interfaces;
  18076. tbody.innerHTML = list.map((iface, idx) => {
  18077. const isSel = iface.id === selId;
  18078. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18079. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18080. return `
  18081. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  18082. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18083. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18084. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18085. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18086. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  18087. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  18088. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  18089. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  18090. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  18091. </tr>
  18092. `;
  18093. }).join('');
  18094. }
  18095. function renderBfdPeers() {
  18096. const tbody = document.getElementById('bfd-peers-table-body');
  18097. if (!tbody) return;
  18098. const countEl = document.getElementById('bfd-peers-footer-count');
  18099. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  18100. let list = state.bfdNeighbors || [];
  18101. if (filter) {
  18102. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18103. }
  18104. if (countEl) countEl.innerText = list.length;
  18105. const selId = state.selectedBfdRow?.peers;
  18106. tbody.innerHTML = list.map((p, idx) => {
  18107. const isSel = p.id === selId;
  18108. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18109. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18110. return `
  18111. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18112. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18113. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18114. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18115. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18116. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18117. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(p.local_address || 'auto')}</td>
  18118. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18119. </tr>
  18120. `;
  18121. }).join('');
  18122. }
  18123. function renderBfdSessions() {
  18124. const tbody = document.getElementById('bfd-sessions-table-body');
  18125. if (!tbody) return;
  18126. const countEl = document.getElementById('bfd-sessions-footer-count');
  18127. const list = state.bfdSessions || [];
  18128. if (countEl) countEl.innerText = list.length;
  18129. tbody.innerHTML = list.map((s, idx) => {
  18130. const isUp = (s.state || '').toLowerCase() === 'up';
  18131. const stateBadge = isUp
  18132. ? '<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>'
  18133. : `<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>`;
  18134. return `
  18135. <tr class="hover:bg-[#1a2636] text-slate-300">
  18136. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18137. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18138. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18139. <td class="py-1.5 px-3">${stateBadge}</td>
  18140. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18141. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18142. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18143. </tr>
  18144. `;
  18145. }).join('');
  18146. }
  18147. function openBfdInterfaceModal() {
  18148. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18149. document.getElementById('modal-bfd-iface-id').value = '';
  18150. const dl = document.getElementById('bfd-iface-datalist');
  18151. if (dl) {
  18152. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18153. }
  18154. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18155. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18156. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18157. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18158. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18159. document.getElementById('modal-bfd-iface-comment').value = '';
  18160. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18161. document.getElementById('modal-bfd-iface-passive').checked = false;
  18162. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18163. }
  18164. function openEditBfdInterfaceModal(id) {
  18165. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18166. if (!iface) return;
  18167. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18168. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18169. const dl = document.getElementById('bfd-iface-datalist');
  18170. if (dl) {
  18171. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18172. }
  18173. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18174. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18175. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18176. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18177. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18178. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18179. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18180. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18181. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18182. }
  18183. function closeBfdInterfaceModal() {
  18184. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18185. }
  18186. async function submitBfdInterface(e) {
  18187. e.preventDefault();
  18188. const id = document.getElementById('modal-bfd-iface-id').value;
  18189. const payload = {
  18190. id: id || undefined,
  18191. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18192. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18193. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18194. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18195. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18196. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18197. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18198. passive: document.getElementById('modal-bfd-iface-passive').checked
  18199. };
  18200. try {
  18201. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18202. method: 'POST',
  18203. headers: { 'Content-Type': 'application/json' },
  18204. body: JSON.stringify(payload)
  18205. });
  18206. if (!res.ok) throw new Error(await res.text());
  18207. closeBfdInterfaceModal();
  18208. showToast('Saved', `BFD profile saved`, 'success');
  18209. await loadDynamicRouting(false);
  18210. } catch (err) {
  18211. showToast('Error', err.message, 'error');
  18212. }
  18213. }
  18214. async function enableSelectedBfdInterface() {
  18215. const id = state.selectedBfdRow?.interfaces;
  18216. if (!id) return;
  18217. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18218. await loadDynamicRouting(false);
  18219. }
  18220. async function disableSelectedBfdInterface() {
  18221. const id = state.selectedBfdRow?.interfaces;
  18222. if (!id) return;
  18223. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18224. await loadDynamicRouting(false);
  18225. }
  18226. async function removeSelectedBfdInterface() {
  18227. const id = state.selectedBfdRow?.interfaces;
  18228. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18229. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' });
  18230. state.selectedBfdRow.interfaces = null;
  18231. await loadDynamicRouting(false);
  18232. }
  18233. function openBfdPeerModal() {
  18234. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18235. document.getElementById('modal-bfd-peer-id').value = '';
  18236. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18237. if (dlPeer) {
  18238. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18239. }
  18240. document.getElementById('modal-bfd-peer-address').value = '';
  18241. document.getElementById('modal-bfd-peer-interface').value = '';
  18242. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18243. if (localAddrEl) localAddrEl.value = '';
  18244. document.getElementById('modal-bfd-peer-comment').value = '';
  18245. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18246. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18247. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18248. }
  18249. function openEditBfdPeerModal(id) {
  18250. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18251. if (!p) return;
  18252. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18253. document.getElementById('modal-bfd-peer-id').value = p.id;
  18254. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18255. if (dlPeer) {
  18256. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18257. }
  18258. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18259. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18260. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18261. if (localAddrEl) localAddrEl.value = p.local_address || '';
  18262. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18263. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18264. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18265. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18266. }
  18267. function closeBfdPeerModal() {
  18268. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18269. }
  18270. async function submitBfdPeer(e) {
  18271. e.preventDefault();
  18272. const id = document.getElementById('modal-bfd-peer-id').value;
  18273. const localAddr = document.getElementById('modal-bfd-peer-local-address')?.value.trim() || '';
  18274. const payload = {
  18275. id: id || undefined,
  18276. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18277. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18278. local_address: localAddr,
  18279. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18280. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18281. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18282. };
  18283. try {
  18284. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18285. method: 'POST',
  18286. headers: { 'Content-Type': 'application/json' },
  18287. body: JSON.stringify(payload)
  18288. });
  18289. if (!res.ok) throw new Error(await res.text());
  18290. closeBfdPeerModal();
  18291. showToast('Saved', `BFD peer saved`, 'success');
  18292. await loadDynamicRouting(false);
  18293. } catch (err) {
  18294. showToast('Error', err.message, 'error');
  18295. }
  18296. }
  18297. async function enableSelectedBfdPeer() {
  18298. const id = state.selectedBfdRow?.peers;
  18299. if (!id) return;
  18300. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18301. if (!p) return;
  18302. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) });
  18303. await loadDynamicRouting(false);
  18304. }
  18305. async function disableSelectedBfdPeer() {
  18306. const id = state.selectedBfdRow?.peers;
  18307. if (!id) return;
  18308. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18309. if (!p) return;
  18310. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) });
  18311. await loadDynamicRouting(false);
  18312. }
  18313. async function removeSelectedBfdPeer() {
  18314. const id = state.selectedBfdRow?.peers;
  18315. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18316. await fetch(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' });
  18317. state.selectedBfdRow.peers = null;
  18318. await loadDynamicRouting(false);
  18319. }
  18320. // ==============================================================================
  18321. // DYNAMIC ROUTING: BABEL MODULE
  18322. // ==============================================================================
  18323. state.babelInstances = [];
  18324. state.babelInterfaces = [];
  18325. state.babelInterfacesLive = [];
  18326. state.babelNeighbors = [];
  18327. state.babelRoutes = [];
  18328. state.selectedBabelRow = {};
  18329. state.activeBabelTab = 'instances';
  18330. function switchBabelTab(tab) {
  18331. state.activeBabelTab = tab;
  18332. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18333. const pane = document.getElementById(`babel-pane-${t}`);
  18334. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18335. if (pane) {
  18336. if (t === tab) pane.classList.remove('hidden');
  18337. else pane.classList.add('hidden');
  18338. }
  18339. if (btn) {
  18340. if (t === tab) {
  18341. 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';
  18342. } else {
  18343. 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';
  18344. }
  18345. }
  18346. });
  18347. }
  18348. function selectBabelRow(tab, id) {
  18349. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18350. state.selectedBabelRow[tab] = id;
  18351. if (tab === 'instances') {
  18352. renderBabelInstances();
  18353. const btnEn = document.getElementById('btn-babel-inst-enable');
  18354. const btnDis = document.getElementById('btn-babel-inst-disable');
  18355. const btnRem = document.getElementById('btn-babel-inst-remove');
  18356. if (btnEn) btnEn.disabled = false;
  18357. if (btnDis) btnDis.disabled = false;
  18358. if (btnRem) btnRem.disabled = false;
  18359. } else if (tab === 'interfaces') {
  18360. renderBabelInterfaces();
  18361. const btnEn = document.getElementById('btn-babel-iface-enable');
  18362. const btnDis = document.getElementById('btn-babel-iface-disable');
  18363. const btnRem = document.getElementById('btn-babel-iface-remove');
  18364. if (btnEn) btnEn.disabled = false;
  18365. if (btnDis) btnDis.disabled = false;
  18366. if (btnRem) btnRem.disabled = false;
  18367. }
  18368. }
  18369. function renderBabelInstances() {
  18370. const tbody = document.getElementById('babel-instances-table-body');
  18371. if (!tbody) return;
  18372. const countEl = document.getElementById('babel-instances-footer-count');
  18373. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18374. let list = state.babelInstances || [];
  18375. if (filter) {
  18376. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18377. }
  18378. if (countEl) countEl.innerText = list.length;
  18379. const selId = state.selectedBabelRow?.instances;
  18380. tbody.innerHTML = list.map((inst, idx) => {
  18381. const isSel = inst.id === selId;
  18382. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18383. const flagD = inst.disabled
  18384. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18385. : (inst.running
  18386. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18387. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18388. const redist = [];
  18389. if (inst.redistribute_connected) redist.push('conn');
  18390. if (inst.redistribute_static) redist.push('static');
  18391. if (inst.redistribute_bgp) redist.push('bgp');
  18392. if (inst.redistribute_ospf) redist.push('ospf');
  18393. if (inst.redistribute_default) redist.push('default');
  18394. return `
  18395. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18396. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18397. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18398. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18399. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18400. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18401. </td>
  18402. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18403. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18404. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18405. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18406. </tr>
  18407. `;
  18408. }).join('');
  18409. }
  18410. function renderBabelInterfaces() {
  18411. const tbody = document.getElementById('babel-interfaces-table-body');
  18412. if (!tbody) return;
  18413. const countEl = document.getElementById('babel-interfaces-footer-count');
  18414. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18415. let list = state.babelInterfaces || [];
  18416. if (filter) {
  18417. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18418. }
  18419. if (countEl) countEl.innerText = list.length;
  18420. const selId = state.selectedBabelRow?.interfaces;
  18421. tbody.innerHTML = list.map((iface, idx) => {
  18422. const isSel = iface.id === selId;
  18423. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18424. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18425. return `
  18426. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18427. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18428. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18429. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18430. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18431. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18432. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18433. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18434. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18435. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18436. </tr>
  18437. `;
  18438. }).join('');
  18439. }
  18440. function renderBabelLiveInterfaces() {
  18441. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18442. if (!tbody) return;
  18443. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18444. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18445. let list = state.babelInterfacesLive || [];
  18446. if (filter) {
  18447. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18448. }
  18449. if (countEl) countEl.innerText = list.length;
  18450. tbody.innerHTML = list.map((iface, idx) => {
  18451. const isUp = (iface.state || '').toLowerCase() === 'up';
  18452. const stateBadge = isUp
  18453. ? '<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>'
  18454. : '<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>';
  18455. return `
  18456. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18457. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18458. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18459. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18460. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18461. <td class="py-1.5 px-3">${stateBadge}</td>
  18462. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18463. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18464. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18465. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18466. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18467. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18468. </tr>
  18469. `;
  18470. }).join('');
  18471. }
  18472. function renderBabelNeighbors() {
  18473. const tbody = document.getElementById('babel-neighbors-table-body');
  18474. if (!tbody) return;
  18475. const countEl = document.getElementById('babel-neighbors-footer-count');
  18476. const list = state.babelNeighbors || [];
  18477. if (countEl) countEl.innerText = list.length;
  18478. tbody.innerHTML = list.map((nbr, idx) => `
  18479. <tr class="hover:bg-[#1a2636] text-slate-300">
  18480. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18481. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18482. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18483. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18484. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18485. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18486. </tr>
  18487. `).join('');
  18488. }
  18489. function renderBabelRoutes() {
  18490. const tbody = document.getElementById('babel-routes-table-body');
  18491. if (!tbody) return;
  18492. const countEl = document.getElementById('babel-routes-footer-count');
  18493. const list = state.babelRoutes || [];
  18494. if (countEl) countEl.innerText = list.length;
  18495. tbody.innerHTML = list.map((r, idx) => `
  18496. <tr class="hover:bg-[#1a2636] text-slate-300">
  18497. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18498. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18499. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18500. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18501. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18502. </tr>
  18503. `).join('');
  18504. }
  18505. function openBabelInstanceModal() {
  18506. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18507. document.getElementById('modal-babel-instance-id').value = '';
  18508. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18509. document.getElementById('modal-babel-instance-routerid').value = '';
  18510. document.getElementById('modal-babel-instance-metric').value = '10';
  18511. document.getElementById('modal-babel-instance-comment').value = '';
  18512. document.getElementById('modal-babel-instance-enabled').checked = true;
  18513. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18514. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18515. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18516. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18517. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18518. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18519. }
  18520. function openEditBabelInstanceModal(id) {
  18521. const inst = (state.babelInstances || []).find(i => i.id === id);
  18522. if (!inst) return;
  18523. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18524. document.getElementById('modal-babel-instance-id').value = inst.id;
  18525. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18526. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18527. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18528. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18529. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18530. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18531. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18532. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18533. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18534. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18535. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18536. }
  18537. function closeBabelInstanceModal() {
  18538. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18539. }
  18540. async function submitBabelInstance(e) {
  18541. e.preventDefault();
  18542. const id = document.getElementById('modal-babel-instance-id').value;
  18543. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18544. const payload = {
  18545. id: id || undefined,
  18546. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18547. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18548. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18549. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18550. enabled: isEnabled,
  18551. disabled: !isEnabled,
  18552. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18553. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18554. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18555. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18556. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18557. };
  18558. try {
  18559. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18560. method: 'POST',
  18561. headers: { 'Content-Type': 'application/json' },
  18562. body: JSON.stringify(payload)
  18563. });
  18564. if (!res.ok) throw new Error(await res.text());
  18565. closeBabelInstanceModal();
  18566. showToast('Saved', `Babel instance saved`, 'success');
  18567. await loadDynamicRouting(false);
  18568. } catch (err) {
  18569. showToast('Error', err.message, 'error');
  18570. }
  18571. }
  18572. async function enableSelectedBabelInstance() {
  18573. const id = state.selectedBabelRow?.instances;
  18574. if (!id) return;
  18575. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18576. await loadDynamicRouting(false);
  18577. }
  18578. async function disableSelectedBabelInstance() {
  18579. const id = state.selectedBabelRow?.instances;
  18580. if (!id) return;
  18581. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18582. await loadDynamicRouting(false);
  18583. }
  18584. async function removeSelectedBabelInstance() {
  18585. const id = state.selectedBabelRow?.instances;
  18586. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18587. await fetch(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' });
  18588. state.selectedBabelRow.instances = null;
  18589. await loadDynamicRouting(false);
  18590. }
  18591. function toggleBabelAuthKey() {
  18592. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18593. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18594. if (wrap) {
  18595. if (authVal === 'mac') wrap.classList.remove('hidden');
  18596. else wrap.classList.add('hidden');
  18597. }
  18598. }
  18599. function openBabelInterfaceModal() {
  18600. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18601. document.getElementById('modal-babel-iface-id').value = '';
  18602. const instSel = document.getElementById('modal-babel-iface-instance');
  18603. if (instSel) {
  18604. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18605. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18606. if (state.babelInstances && state.babelInstances.length > 0) {
  18607. instSel.value = state.babelInstances[0].name;
  18608. }
  18609. }
  18610. const dl = document.getElementById('babel-iface-datalist');
  18611. if (dl) {
  18612. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18613. }
  18614. document.getElementById('modal-babel-iface-pattern').value = '*';
  18615. document.getElementById('modal-babel-iface-type').value = 'wired';
  18616. document.getElementById('modal-babel-iface-auth').value = 'none';
  18617. document.getElementById('modal-babel-iface-auth-key').value = '';
  18618. toggleBabelAuthKey();
  18619. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18620. document.getElementById('modal-babel-iface-hello').value = '4';
  18621. document.getElementById('modal-babel-iface-update').value = '16';
  18622. document.getElementById('modal-babel-iface-comment').value = '';
  18623. document.getElementById('modal-babel-iface-enabled').checked = true;
  18624. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18625. }
  18626. function openEditBabelInterfaceModal(id) {
  18627. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18628. if (!iface) return;
  18629. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18630. document.getElementById('modal-babel-iface-id').value = iface.id;
  18631. const instSel = document.getElementById('modal-babel-iface-instance');
  18632. if (instSel) {
  18633. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18634. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18635. instSel.value = iface.instance || 'all';
  18636. }
  18637. const dl = document.getElementById('babel-iface-datalist');
  18638. if (dl) {
  18639. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18640. }
  18641. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18642. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18643. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18644. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18645. toggleBabelAuthKey();
  18646. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18647. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18648. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18649. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18650. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18651. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18652. }
  18653. function closeBabelInterfaceModal() {
  18654. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18655. }
  18656. async function submitBabelInterface(e) {
  18657. e.preventDefault();
  18658. const id = document.getElementById('modal-babel-iface-id').value;
  18659. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18660. const payload = {
  18661. id: id || undefined,
  18662. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18663. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18664. type: document.getElementById('modal-babel-iface-type').value,
  18665. auth: document.getElementById('modal-babel-iface-auth').value,
  18666. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18667. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18668. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18669. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18670. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18671. disabled: !isEnabled
  18672. };
  18673. try {
  18674. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18675. method: 'POST',
  18676. headers: { 'Content-Type': 'application/json' },
  18677. body: JSON.stringify(payload)
  18678. });
  18679. if (!res.ok) throw new Error(await res.text());
  18680. closeBabelInterfaceModal();
  18681. showToast('Saved', `Babel interface template saved`, 'success');
  18682. await loadDynamicRouting(false);
  18683. } catch (err) {
  18684. showToast('Error', err.message, 'error');
  18685. }
  18686. }
  18687. async function enableSelectedBabelInterface() {
  18688. const id = state.selectedBabelRow?.interfaces;
  18689. if (!id) return;
  18690. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18691. await loadDynamicRouting(false);
  18692. }
  18693. async function disableSelectedBabelInterface() {
  18694. const id = state.selectedBabelRow?.interfaces;
  18695. if (!id) return;
  18696. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18697. await loadDynamicRouting(false);
  18698. }
  18699. async function removeSelectedBabelInterface() {
  18700. const id = state.selectedBabelRow?.interfaces;
  18701. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18702. await fetch(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' });
  18703. state.selectedBabelRow.interfaces = null;
  18704. await loadDynamicRouting(false);
  18705. }
  18706. // ==============================================================================
  18707. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18708. // ==============================================================================
  18709. state.radvInstances = [];
  18710. state.radvInterfaces = [];
  18711. state.selectedRadvRow = {};
  18712. state.activeRadvTab = 'instances';
  18713. function switchRadvTab(tab) {
  18714. state.activeRadvTab = tab;
  18715. ['instances', 'interfaces'].forEach(t => {
  18716. const pane = document.getElementById(`radv-pane-${t}`);
  18717. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18718. if (pane) {
  18719. if (t === tab) pane.classList.remove('hidden');
  18720. else pane.classList.add('hidden');
  18721. }
  18722. if (btn) {
  18723. if (t === tab) {
  18724. 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';
  18725. } else {
  18726. 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';
  18727. }
  18728. }
  18729. });
  18730. }
  18731. function selectRadvRow(tab, id) {
  18732. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18733. state.selectedRadvRow[tab] = id;
  18734. if (tab === 'instances') {
  18735. renderRAdvInstances();
  18736. const btnEn = document.getElementById('btn-radv-inst-enable');
  18737. const btnDis = document.getElementById('btn-radv-inst-disable');
  18738. const btnRem = document.getElementById('btn-radv-inst-remove');
  18739. if (btnEn) btnEn.disabled = false;
  18740. if (btnDis) btnDis.disabled = false;
  18741. if (btnRem) btnRem.disabled = false;
  18742. } else if (tab === 'interfaces') {
  18743. renderRAdvInterfaces();
  18744. const btnEn = document.getElementById('btn-radv-iface-enable');
  18745. const btnDis = document.getElementById('btn-radv-iface-disable');
  18746. const btnRem = document.getElementById('btn-radv-iface-remove');
  18747. if (btnEn) btnEn.disabled = false;
  18748. if (btnDis) btnDis.disabled = false;
  18749. if (btnRem) btnRem.disabled = false;
  18750. }
  18751. }
  18752. function renderRAdvInstances() {
  18753. const tbody = document.getElementById('radv-instances-table-body');
  18754. if (!tbody) return;
  18755. const countEl = document.getElementById('radv-instances-footer-count');
  18756. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18757. let list = state.radvInstances || [];
  18758. if (filter) {
  18759. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18760. }
  18761. if (countEl) countEl.innerText = list.length;
  18762. const selId = state.selectedRadvRow?.instances;
  18763. tbody.innerHTML = list.map((inst, idx) => {
  18764. const isSel = inst.id === selId;
  18765. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18766. const flagD = inst.disabled
  18767. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  18768. : (inst.running
  18769. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  18770. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  18771. return `
  18772. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18773. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18774. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18775. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18776. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18777. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18778. </td>
  18779. <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>
  18780. </tr>
  18781. `;
  18782. }).join('');
  18783. }
  18784. function renderRAdvInterfaces() {
  18785. const tbody = document.getElementById('radv-interfaces-table-body');
  18786. if (!tbody) return;
  18787. const countEl = document.getElementById('radv-interfaces-footer-count');
  18788. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18789. let list = state.radvInterfaces || [];
  18790. if (filter) {
  18791. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18792. }
  18793. if (countEl) countEl.innerText = list.length;
  18794. const selId = state.selectedRadvRow?.interfaces;
  18795. tbody.innerHTML = list.map((iface, idx) => {
  18796. const isSel = iface.id === selId;
  18797. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18798. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18799. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18800. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18801. return `
  18802. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18803. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18804. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18805. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18806. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18807. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18808. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18809. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18810. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18811. </tr>
  18812. `;
  18813. }).join('');
  18814. }
  18815. function openRAdvInstanceModal() {
  18816. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18817. document.getElementById('modal-radv-instance-id').value = '';
  18818. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18819. document.getElementById('modal-radv-instance-comment').value = '';
  18820. document.getElementById('modal-radv-instance-enabled').checked = true;
  18821. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18822. }
  18823. function openEditRAdvInstanceModal(id) {
  18824. const inst = (state.radvInstances || []).find(i => i.id === id);
  18825. if (!inst) return;
  18826. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18827. document.getElementById('modal-radv-instance-id').value = inst.id;
  18828. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18829. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18830. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18831. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18832. }
  18833. function closeRAdvInstanceModal() {
  18834. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18835. }
  18836. async function submitRAdvInstance(e) {
  18837. e.preventDefault();
  18838. const id = document.getElementById('modal-radv-instance-id').value;
  18839. const payload = {
  18840. id: id || undefined,
  18841. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18842. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18843. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  18844. };
  18845. try {
  18846. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  18847. method: 'POST',
  18848. headers: { 'Content-Type': 'application/json' },
  18849. body: JSON.stringify(payload)
  18850. });
  18851. if (!res.ok) throw new Error(await res.text());
  18852. closeRAdvInstanceModal();
  18853. showToast('Saved', `RAdv instance saved`, 'success');
  18854. await loadDynamicRouting(false);
  18855. } catch (err) {
  18856. showToast('Error', err.message, 'error');
  18857. }
  18858. }
  18859. async function enableSelectedRadvInstance() {
  18860. const id = state.selectedRadvRow?.instances;
  18861. if (!id) return;
  18862. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18863. await loadDynamicRouting(false);
  18864. }
  18865. async function disableSelectedRadvInstance() {
  18866. const id = state.selectedRadvRow?.instances;
  18867. if (!id) return;
  18868. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18869. await loadDynamicRouting(false);
  18870. }
  18871. async function removeSelectedRadvInstance() {
  18872. const id = state.selectedRadvRow?.instances;
  18873. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  18874. await fetch(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' });
  18875. state.selectedRadvRow.instances = null;
  18876. await loadDynamicRouting(false);
  18877. }
  18878. function openRAdvInterfaceModal() {
  18879. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  18880. document.getElementById('modal-radv-iface-id').value = '';
  18881. const dl = document.getElementById('radv-iface-datalist');
  18882. if (dl) {
  18883. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18884. }
  18885. const instSel = document.getElementById('modal-radv-iface-instance');
  18886. if (instSel && instSel.tagName === 'SELECT') {
  18887. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18888. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18889. instSel.value = (state.radvInstances && state.radvInstances.length > 0) ? state.radvInstances[0].name : 'default';
  18890. } else if (instSel) {
  18891. instSel.value = 'default';
  18892. }
  18893. document.getElementById('modal-radv-iface-interface').value = '*';
  18894. document.getElementById('modal-radv-iface-min-ra').value = '200';
  18895. document.getElementById('modal-radv-iface-max-ra').value = '600';
  18896. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  18897. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  18898. document.getElementById('modal-radv-iface-prefixes').value = '';
  18899. document.getElementById('modal-radv-iface-rdnss').value = '';
  18900. document.getElementById('modal-radv-iface-comment').value = '';
  18901. document.getElementById('modal-radv-iface-enabled').checked = true;
  18902. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18903. }
  18904. function openEditRAdvInterfaceModal(id) {
  18905. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  18906. if (!iface) return;
  18907. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  18908. document.getElementById('modal-radv-iface-id').value = iface.id;
  18909. const dl = document.getElementById('radv-iface-datalist');
  18910. if (dl) {
  18911. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18912. }
  18913. const instSel = document.getElementById('modal-radv-iface-instance');
  18914. if (instSel && instSel.tagName === 'SELECT') {
  18915. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18916. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18917. instSel.value = iface.instance || 'default';
  18918. } else if (instSel) {
  18919. instSel.value = iface.instance || '';
  18920. }
  18921. document.getElementById('modal-radv-iface-interface').value = iface.interface || '*';
  18922. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  18923. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  18924. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  18925. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  18926. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  18927. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  18928. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  18929. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  18930. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18931. }
  18932. function closeRAdvInterfaceModal() {
  18933. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  18934. }
  18935. async function submitRAdvInterface(e) {
  18936. e.preventDefault();
  18937. const id = document.getElementById('modal-radv-iface-id').value;
  18938. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  18939. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  18940. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18941. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18942. const payload = {
  18943. id: id || undefined,
  18944. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  18945. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  18946. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  18947. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  18948. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  18949. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  18950. prefixes: prefixes,
  18951. rdnss: rdnss,
  18952. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  18953. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  18954. };
  18955. try {
  18956. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  18957. method: 'POST',
  18958. headers: { 'Content-Type': 'application/json' },
  18959. body: JSON.stringify(payload)
  18960. });
  18961. if (!res.ok) throw new Error(await res.text());
  18962. closeRAdvInterfaceModal();
  18963. showToast('Saved', `RAdv interface saved`, 'success');
  18964. await loadDynamicRouting(false);
  18965. } catch (err) {
  18966. showToast('Error', err.message, 'error');
  18967. }
  18968. }
  18969. async function enableSelectedRadvInterface() {
  18970. const id = state.selectedRadvRow?.interfaces;
  18971. if (!id) return;
  18972. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18973. await loadDynamicRouting(false);
  18974. }
  18975. async function disableSelectedRadvInterface() {
  18976. const id = state.selectedRadvRow?.interfaces;
  18977. if (!id) return;
  18978. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18979. await loadDynamicRouting(false);
  18980. }
  18981. async function removeSelectedRadvInterface() {
  18982. const id = state.selectedRadvRow?.interfaces;
  18983. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  18984. await fetch(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' });
  18985. state.selectedRadvRow.interfaces = null;
  18986. await loadDynamicRouting(false);
  18987. }
  18988. // ================= EIGRP ROUTING CONTROLLER =================
  18989. state.selectedEigrpRow = { instances: null, networks: null, interfaces: null };
  18990. function switchEigrpTab(tab) {
  18991. state.activeEigrpTab = tab;
  18992. const tabs = ['instances', 'networks', 'interfaces', 'neighbors', 'topology'];
  18993. tabs.forEach(t => {
  18994. const btn = document.getElementById(`eigrp-tab-btn-${t}`);
  18995. const pane = document.getElementById(`eigrp-pane-${t}`);
  18996. if (btn) {
  18997. if (t === tab) {
  18998. 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';
  18999. } else {
  19000. 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';
  19001. }
  19002. }
  19003. if (pane) {
  19004. if (t === tab) pane.classList.remove('hidden');
  19005. else pane.classList.add('hidden');
  19006. }
  19007. });
  19008. const dlIface = document.getElementById('eigrp-iface-datalist');
  19009. if (dlIface && state.interfaces) {
  19010. dlIface.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19011. }
  19012. const dlNet = document.getElementById('eigrp-net-datalist');
  19013. if (dlNet && state.interfaces) {
  19014. const cidrs = [];
  19015. state.interfaces.forEach(i => {
  19016. (i.addrs || []).forEach(a => {
  19017. if (a.includes('.') && a.includes('/')) cidrs.push(a);
  19018. });
  19019. });
  19020. dlNet.innerHTML = '<option value="0.0.0.0/0">' + cidrs.map(c => `<option value="${escapeHtml(c)}">`).join('');
  19021. }
  19022. }
  19023. function selectEigrpRow(kind, id) {
  19024. if (!state.selectedEigrpRow) state.selectedEigrpRow = {};
  19025. if (state.selectedEigrpRow[kind] === id) {
  19026. state.selectedEigrpRow[kind] = null;
  19027. } else {
  19028. state.selectedEigrpRow[kind] = id;
  19029. }
  19030. if (kind === 'instances') {
  19031. renderEigrpInstances();
  19032. const isSel = !!state.selectedEigrpRow.instances;
  19033. const btnEn = document.getElementById('btn-eigrp-inst-enable');
  19034. const btnDis = document.getElementById('btn-eigrp-inst-disable');
  19035. const btnRem = document.getElementById('btn-eigrp-inst-remove');
  19036. if (btnEn) btnEn.disabled = !isSel;
  19037. if (btnDis) btnDis.disabled = !isSel;
  19038. if (btnRem) btnRem.disabled = !isSel;
  19039. } else if (kind === 'networks') {
  19040. renderEigrpNetworks();
  19041. const isSel = !!state.selectedEigrpRow.networks;
  19042. const btnRem = document.getElementById('btn-eigrp-net-remove');
  19043. if (btnRem) btnRem.disabled = !isSel;
  19044. } else if (kind === 'interfaces') {
  19045. renderEigrpInterfaces();
  19046. const isSel = !!state.selectedEigrpRow.interfaces;
  19047. const btnEn = document.getElementById('btn-eigrp-iface-enable');
  19048. const btnDis = document.getElementById('btn-eigrp-iface-disable');
  19049. const btnRem = document.getElementById('btn-eigrp-iface-remove');
  19050. if (btnEn) btnEn.disabled = !isSel;
  19051. if (btnDis) btnDis.disabled = !isSel;
  19052. if (btnRem) btnRem.disabled = !isSel;
  19053. }
  19054. }
  19055. // --- EIGRP INSTANCES ---
  19056. function renderEigrpInstances() {
  19057. const tbody = document.getElementById('eigrp-instances-table-body');
  19058. if (!tbody) return;
  19059. const countEl = document.getElementById('eigrp-instances-footer-count');
  19060. const filter = (document.getElementById('filter-eigrp-instances')?.value || '').toLowerCase();
  19061. let list = state.eigrpInstances || [];
  19062. if (filter) {
  19063. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || String(i.as || '').includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19064. }
  19065. if (countEl) countEl.innerText = list.length;
  19066. const selId = state.selectedEigrpRow?.instances;
  19067. tbody.innerHTML = list.map((inst, idx) => {
  19068. const isSel = inst.id === selId;
  19069. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19070. const flagD = inst.disabled
  19071. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  19072. : (inst.running
  19073. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  19074. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  19075. const redist = [];
  19076. if (inst.redistribute_connected) redist.push('conn');
  19077. if (inst.redistribute_static) redist.push('static');
  19078. if (inst.redistribute_ospf) redist.push('ospf');
  19079. if (inst.redistribute_bgp) redist.push('bgp');
  19080. return `
  19081. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('instances', '${inst.id}')" ondblclick="openEditEigrpInstanceModal('${inst.id}')">
  19082. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19083. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19084. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  19085. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  19086. <span class="text-purple-400">⚡</span> <span>${escapeHtml(inst.name || 'default')}</span>
  19087. </td>
  19088. <td class="py-1.5 px-3 font-mono text-purple-300 font-bold">${inst.as || 100}</td>
  19089. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  19090. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  19091. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.variance || 1}</td>
  19092. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.max_paths || 4}</td>
  19093. </tr>
  19094. `;
  19095. }).join('');
  19096. }
  19097. function openEigrpInstanceModal() {
  19098. document.getElementById('eigrp-instance-modal-title').innerText = 'Add EIGRP Instance';
  19099. document.getElementById('modal-eigrp-instance-id').value = '';
  19100. document.getElementById('modal-eigrp-instance-name').value = 'eigrp' + ((state.eigrpInstances || []).length + 1);
  19101. document.getElementById('modal-eigrp-instance-as').value = '100';
  19102. document.getElementById('modal-eigrp-instance-routerid').value = '';
  19103. document.getElementById('modal-eigrp-instance-comment').value = '';
  19104. document.getElementById('modal-eigrp-instance-variance').value = '1';
  19105. document.getElementById('modal-eigrp-instance-maxpaths').value = '4';
  19106. document.getElementById('modal-eigrp-instance-metric').value = '10000';
  19107. document.getElementById('modal-eigrp-instance-redist-conn').checked = false;
  19108. document.getElementById('modal-eigrp-instance-redist-static').checked = false;
  19109. document.getElementById('modal-eigrp-instance-redist-ospf').checked = false;
  19110. document.getElementById('modal-eigrp-instance-redist-bgp').checked = false;
  19111. document.getElementById('modal-eigrp-instance-enabled').checked = true;
  19112. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19113. }
  19114. function openEditEigrpInstanceModal(id) {
  19115. const inst = (state.eigrpInstances || []).find(i => i.id === id);
  19116. if (!inst) return;
  19117. document.getElementById('eigrp-instance-modal-title').innerText = `Edit EIGRP Instance: ${inst.name}`;
  19118. document.getElementById('modal-eigrp-instance-id').value = inst.id;
  19119. document.getElementById('modal-eigrp-instance-name').value = inst.name || '';
  19120. document.getElementById('modal-eigrp-instance-as').value = inst.as || 100;
  19121. document.getElementById('modal-eigrp-instance-routerid').value = inst.router_id || '';
  19122. document.getElementById('modal-eigrp-instance-comment').value = inst.comment || '';
  19123. document.getElementById('modal-eigrp-instance-variance').value = inst.variance || 1;
  19124. document.getElementById('modal-eigrp-instance-maxpaths').value = inst.max_paths || 4;
  19125. document.getElementById('modal-eigrp-instance-metric').value = inst.default_metric || 10000;
  19126. document.getElementById('modal-eigrp-instance-redist-conn').checked = !!inst.redistribute_connected;
  19127. document.getElementById('modal-eigrp-instance-redist-static').checked = !!inst.redistribute_static;
  19128. document.getElementById('modal-eigrp-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  19129. document.getElementById('modal-eigrp-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  19130. document.getElementById('modal-eigrp-instance-enabled').checked = !inst.disabled;
  19131. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19132. }
  19133. function closeEigrpInstanceModal() {
  19134. document.getElementById('eigrp-instance-modal')?.classList.add('hidden');
  19135. }
  19136. async function submitEigrpInstance(e) {
  19137. e.preventDefault();
  19138. const payload = {
  19139. id: document.getElementById('modal-eigrp-instance-id').value.trim() || undefined,
  19140. name: document.getElementById('modal-eigrp-instance-name').value.trim(),
  19141. as: parseInt(document.getElementById('modal-eigrp-instance-as').value, 10) || 100,
  19142. router_id: document.getElementById('modal-eigrp-instance-routerid').value.trim(),
  19143. comment: document.getElementById('modal-eigrp-instance-comment').value.trim(),
  19144. variance: parseInt(document.getElementById('modal-eigrp-instance-variance').value, 10) || 1,
  19145. max_paths: parseInt(document.getElementById('modal-eigrp-instance-maxpaths').value, 10) || 4,
  19146. default_metric: parseInt(document.getElementById('modal-eigrp-instance-metric').value, 10) || 10000,
  19147. redistribute_connected: document.getElementById('modal-eigrp-instance-redist-conn').checked,
  19148. redistribute_static: document.getElementById('modal-eigrp-instance-redist-static').checked,
  19149. redistribute_ospf: document.getElementById('modal-eigrp-instance-redist-ospf').checked,
  19150. redistribute_bgp: document.getElementById('modal-eigrp-instance-redist-bgp').checked,
  19151. disabled: !document.getElementById('modal-eigrp-instance-enabled').checked
  19152. };
  19153. try {
  19154. const res = await fetch(`${API_BASE}/routing/eigrp/instances`, {
  19155. method: 'POST',
  19156. headers: { 'Content-Type': 'application/json' },
  19157. body: JSON.stringify(payload)
  19158. });
  19159. if (!res.ok) throw new Error(await res.text());
  19160. closeEigrpInstanceModal();
  19161. showToast('Saved', `EIGRP instance saved`, 'success');
  19162. await loadDynamicRouting(false);
  19163. } catch (err) {
  19164. showToast('Error', err.message, 'error');
  19165. }
  19166. }
  19167. async function enableSelectedEigrpInstance() {
  19168. const id = state.selectedEigrpRow?.instances;
  19169. if (!id) return;
  19170. await fetch(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  19171. await loadDynamicRouting(false);
  19172. }
  19173. async function disableSelectedEigrpInstance() {
  19174. const id = state.selectedEigrpRow?.instances;
  19175. if (!id) return;
  19176. await fetch(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  19177. await loadDynamicRouting(false);
  19178. }
  19179. async function removeSelectedEigrpInstance() {
  19180. const id = state.selectedEigrpRow?.instances;
  19181. if (!id || !confirm('Are you sure you want to remove this EIGRP instance?')) return;
  19182. await fetch(`${API_BASE}/routing/eigrp/instances/${id}`, { method: 'DELETE' });
  19183. state.selectedEigrpRow.instances = null;
  19184. await loadDynamicRouting(false);
  19185. }
  19186. // --- EIGRP NETWORKS ---
  19187. function renderEigrpNetworks() {
  19188. const tbody = document.getElementById('eigrp-networks-table-body');
  19189. if (!tbody) return;
  19190. const countEl = document.getElementById('eigrp-networks-footer-count');
  19191. const filter = (document.getElementById('filter-eigrp-networks')?.value || '').toLowerCase();
  19192. let list = state.eigrpNetworks || [];
  19193. if (filter) {
  19194. list = list.filter(n => (n.network || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  19195. }
  19196. if (countEl) countEl.innerText = list.length;
  19197. const selId = state.selectedEigrpRow?.networks;
  19198. tbody.innerHTML = list.map((net, idx) => {
  19199. const isSel = net.id === selId;
  19200. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19201. return `
  19202. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('networks', '${net.id}')">
  19203. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19204. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(net.comment || '')}</td>
  19205. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(net.network || '')}</td>
  19206. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(net.instance || 'all')}</td>
  19207. </tr>
  19208. `;
  19209. }).join('');
  19210. }
  19211. function openEigrpNetworkModal() {
  19212. document.getElementById('modal-eigrp-network-id').value = '';
  19213. const instSel = document.getElementById('modal-eigrp-network-instance');
  19214. if (instSel) {
  19215. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19216. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19217. }
  19218. document.getElementById('modal-eigrp-network-cidr').value = '0.0.0.0/0';
  19219. document.getElementById('modal-eigrp-network-comment').value = '';
  19220. document.getElementById('eigrp-network-modal')?.classList.remove('hidden');
  19221. }
  19222. function closeEigrpNetworkModal() {
  19223. document.getElementById('eigrp-network-modal')?.classList.add('hidden');
  19224. }
  19225. async function submitEigrpNetwork(e) {
  19226. e.preventDefault();
  19227. const payload = {
  19228. id: document.getElementById('modal-eigrp-network-id').value.trim() || undefined,
  19229. instance: document.getElementById('modal-eigrp-network-instance').value,
  19230. network: document.getElementById('modal-eigrp-network-cidr').value.trim(),
  19231. comment: document.getElementById('modal-eigrp-network-comment').value.trim()
  19232. };
  19233. try {
  19234. const res = await fetch(`${API_BASE}/routing/eigrp/networks`, {
  19235. method: 'POST',
  19236. headers: { 'Content-Type': 'application/json' },
  19237. body: JSON.stringify(payload)
  19238. });
  19239. if (!res.ok) throw new Error(await res.text());
  19240. closeEigrpNetworkModal();
  19241. showToast('Saved', `EIGRP network saved`, 'success');
  19242. await loadDynamicRouting(false);
  19243. } catch (err) {
  19244. showToast('Error', err.message, 'error');
  19245. }
  19246. }
  19247. async function removeSelectedEigrpNetwork() {
  19248. const id = state.selectedEigrpRow?.networks;
  19249. if (!id || !confirm('Are you sure you want to remove this EIGRP network?')) return;
  19250. await fetch(`${API_BASE}/routing/eigrp/networks/${id}`, { method: 'DELETE' });
  19251. state.selectedEigrpRow.networks = null;
  19252. await loadDynamicRouting(false);
  19253. }
  19254. // --- EIGRP INTERFACES ---
  19255. function renderEigrpInterfaces() {
  19256. const tbody = document.getElementById('eigrp-interfaces-table-body');
  19257. if (!tbody) return;
  19258. const countEl = document.getElementById('eigrp-interfaces-footer-count');
  19259. const filter = (document.getElementById('filter-eigrp-interfaces')?.value || '').toLowerCase();
  19260. let list = state.eigrpInterfaces || [];
  19261. if (filter) {
  19262. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19263. }
  19264. if (countEl) countEl.innerText = list.length;
  19265. const selId = state.selectedEigrpRow?.interfaces;
  19266. tbody.innerHTML = list.map((iface, idx) => {
  19267. const isSel = iface.id === selId;
  19268. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19269. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400 font-bold">E</span>';
  19270. return `
  19271. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('interfaces', '${iface.id}')" ondblclick="openEditEigrpInterfaceModal('${iface.id}')">
  19272. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19273. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19274. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  19275. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  19276. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  19277. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 5}s / ${iface.hold_time || 15}s</td>
  19278. <td class="py-1.5 px-3 font-mono ${iface.passive ? 'text-amber-400 font-bold' : 'text-slate-400'}">${iface.passive ? 'Yes' : 'No'}</td>
  19279. <td class="py-1.5 px-3 font-mono ${iface.split_horizon ? 'text-emerald-400' : 'text-slate-400'}">${iface.split_horizon ? 'Yes' : 'No'}</td>
  19280. <td class="py-1.5 px-3 text-slate-300 uppercase font-mono">${escapeHtml(iface.auth_mode || 'none')}</td>
  19281. </tr>
  19282. `;
  19283. }).join('');
  19284. }
  19285. function toggleEigrpAuthKey() {
  19286. const mode = document.getElementById('modal-eigrp-iface-auth-mode')?.value;
  19287. const wrap = document.getElementById('modal-eigrp-iface-auth-key-wrap');
  19288. if (wrap) {
  19289. if (mode === 'md5') wrap.classList.remove('hidden');
  19290. else wrap.classList.add('hidden');
  19291. }
  19292. }
  19293. function openEigrpInterfaceModal() {
  19294. document.getElementById('eigrp-interface-modal-title').innerText = 'Add EIGRP Interface Profile';
  19295. document.getElementById('modal-eigrp-iface-id').value = '';
  19296. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19297. if (instSel) {
  19298. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19299. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19300. }
  19301. const dl = document.getElementById('eigrp-iface-datalist');
  19302. if (dl && state.interfaces) {
  19303. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19304. }
  19305. document.getElementById('modal-eigrp-iface-interface').value = '*';
  19306. document.getElementById('modal-eigrp-iface-hello').value = '5';
  19307. document.getElementById('modal-eigrp-iface-hold').value = '15';
  19308. document.getElementById('modal-eigrp-iface-auth-mode').value = 'none';
  19309. document.getElementById('modal-eigrp-iface-auth-key').value = '';
  19310. toggleEigrpAuthKey();
  19311. document.getElementById('modal-eigrp-iface-passive').checked = false;
  19312. document.getElementById('modal-eigrp-iface-split-horizon').checked = true;
  19313. document.getElementById('modal-eigrp-iface-comment').value = '';
  19314. document.getElementById('modal-eigrp-iface-enabled').checked = true;
  19315. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19316. }
  19317. function openEditEigrpInterfaceModal(id) {
  19318. const iface = (state.eigrpInterfaces || []).find(i => i.id === id);
  19319. if (!iface) return;
  19320. document.getElementById('eigrp-interface-modal-title').innerText = `Edit EIGRP Interface: ${iface.interface}`;
  19321. document.getElementById('modal-eigrp-iface-id').value = iface.id;
  19322. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19323. if (instSel) {
  19324. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19325. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19326. instSel.value = iface.instance || 'all';
  19327. }
  19328. const dl = document.getElementById('eigrp-iface-datalist');
  19329. if (dl && state.interfaces) {
  19330. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19331. }
  19332. document.getElementById('modal-eigrp-iface-interface').value = iface.interface || '*';
  19333. document.getElementById('modal-eigrp-iface-hello').value = iface.hello_interval || 5;
  19334. document.getElementById('modal-eigrp-iface-hold').value = iface.hold_time || 15;
  19335. document.getElementById('modal-eigrp-iface-auth-mode').value = iface.auth_mode || 'none';
  19336. document.getElementById('modal-eigrp-iface-auth-key').value = iface.auth_key || '';
  19337. toggleEigrpAuthKey();
  19338. document.getElementById('modal-eigrp-iface-passive').checked = !!iface.passive;
  19339. document.getElementById('modal-eigrp-iface-split-horizon').checked = iface.split_horizon !== false;
  19340. document.getElementById('modal-eigrp-iface-comment').value = iface.comment || '';
  19341. document.getElementById('modal-eigrp-iface-enabled').checked = !iface.disabled;
  19342. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19343. }
  19344. function closeEigrpInterfaceModal() {
  19345. document.getElementById('eigrp-interface-modal')?.classList.add('hidden');
  19346. }
  19347. async function submitEigrpInterface(e) {
  19348. e.preventDefault();
  19349. const payload = {
  19350. id: document.getElementById('modal-eigrp-iface-id').value.trim() || undefined,
  19351. instance: document.getElementById('modal-eigrp-iface-instance').value,
  19352. interface: document.getElementById('modal-eigrp-iface-interface').value.trim(),
  19353. hello_interval: parseInt(document.getElementById('modal-eigrp-iface-hello').value, 10) || 5,
  19354. hold_time: parseInt(document.getElementById('modal-eigrp-iface-hold').value, 10) || 15,
  19355. passive: document.getElementById('modal-eigrp-iface-passive').checked,
  19356. split_horizon: document.getElementById('modal-eigrp-iface-split-horizon').checked,
  19357. auth_mode: document.getElementById('modal-eigrp-iface-auth-mode').value,
  19358. auth_key: document.getElementById('modal-eigrp-iface-auth-key').value.trim(),
  19359. comment: document.getElementById('modal-eigrp-iface-comment').value.trim(),
  19360. disabled: !document.getElementById('modal-eigrp-iface-enabled').checked
  19361. };
  19362. try {
  19363. const res = await fetch(`${API_BASE}/routing/eigrp/interfaces`, {
  19364. method: 'POST',
  19365. headers: { 'Content-Type': 'application/json' },
  19366. body: JSON.stringify(payload)
  19367. });
  19368. if (!res.ok) throw new Error(await res.text());
  19369. closeEigrpInterfaceModal();
  19370. showToast('Saved', `EIGRP interface saved`, 'success');
  19371. await loadDynamicRouting(false);
  19372. } catch (err) {
  19373. showToast('Error', err.message, 'error');
  19374. }
  19375. }
  19376. async function enableSelectedEigrpInterface() {
  19377. const id = state.selectedEigrpRow?.interfaces;
  19378. if (!id) return;
  19379. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  19380. await loadDynamicRouting(false);
  19381. }
  19382. async function disableSelectedEigrpInterface() {
  19383. const id = state.selectedEigrpRow?.interfaces;
  19384. if (!id) return;
  19385. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  19386. await loadDynamicRouting(false);
  19387. }
  19388. async function removeSelectedEigrpInterface() {
  19389. const id = state.selectedEigrpRow?.interfaces;
  19390. if (!id || !confirm('Are you sure you want to remove this EIGRP interface?')) return;
  19391. await fetch(`${API_BASE}/routing/eigrp/interfaces/${id}`, { method: 'DELETE' });
  19392. state.selectedEigrpRow.interfaces = null;
  19393. await loadDynamicRouting(false);
  19394. }
  19395. // --- EIGRP NEIGHBORS (LIVE) ---
  19396. function renderEigrpNeighbors() {
  19397. const tbody = document.getElementById('eigrp-neighbors-table-body');
  19398. if (!tbody) return;
  19399. const countEl = document.getElementById('eigrp-neighbors-footer-count');
  19400. const filter = (document.getElementById('filter-eigrp-neighbors')?.value || '').toLowerCase();
  19401. let list = state.eigrpNeighbors || [];
  19402. if (filter) {
  19403. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.interface || '').toLowerCase().includes(filter) || String(n.as || '').includes(filter));
  19404. }
  19405. if (countEl) countEl.innerText = list.length;
  19406. tbody.innerHTML = list.map((nbr, idx) => `
  19407. <tr class="hover:bg-[#1a2636] text-slate-300">
  19408. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19409. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${nbr.as || '-'}</td>
  19410. <td class="py-1.5 px-3 font-mono font-semibold text-purple-300">${escapeHtml(nbr.address || '')}</td>
  19411. <td class="py-1.5 px-3 font-mono text-white">${escapeHtml(nbr.interface || '')}</td>
  19412. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.hold_time || 0}s</td>
  19413. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '-')}</td>
  19414. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.srtt || 0}</td>
  19415. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.rto || 0}</td>
  19416. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.q_cnt || 0}</td>
  19417. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.seq_num || 0}</td>
  19418. </tr>
  19419. `).join('');
  19420. }
  19421. // --- EIGRP TOPOLOGY (LIVE) ---
  19422. function renderEigrpTopology() {
  19423. const tbody = document.getElementById('eigrp-topology-table-body');
  19424. if (!tbody) return;
  19425. const countEl = document.getElementById('eigrp-topology-footer-count');
  19426. const filter = (document.getElementById('filter-eigrp-topology')?.value || '').toLowerCase();
  19427. let list = state.eigrpTopology || [];
  19428. if (filter) {
  19429. 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));
  19430. }
  19431. if (countEl) countEl.innerText = list.length;
  19432. tbody.innerHTML = list.map((top, idx) => `
  19433. <tr class="hover:bg-[#1a2636] text-slate-300">
  19434. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19435. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${top.as || '-'}</td>
  19436. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(top.network || '')}</td>
  19437. <td class="py-1.5 px-3 font-mono text-slate-300">${top.successors || 1}</td>
  19438. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(top.fd || '-')}</td>
  19439. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(top.next_hop || '-')}</td>
  19440. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(top.interface || '-')}</td>
  19441. </tr>
  19442. `).join('');
  19443. }