app.js 947 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791
  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(), successes: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. // Map endpoint paths to the views that consume them, so unrelated failures do not
  9. // hide whether the current view has fresh data.
  10. function viewUsesEndpoint(tab, path) {
  11. const endpoints = {
  12. dashboard: ['/system/status', '/interfaces', '/vpn/status', '/firewall/summary'],
  13. interfaces: ['/interfaces', '/vlans', '/roles'],
  14. firewall: ['/firewall/summary', '/firewall/filter', '/firewall/nat', '/firewall/mangle', '/firewall/address-lists'],
  15. routes: ['/routes', '/routing/rules', '/routing/tables'],
  16. 'routing-filters': ['/routing/filters', '/routing/filters/community-lists', '/routing/filters/as-lists'],
  17. bgp: ['/routing/bgp/instance', '/routing/bgp/peers', '/routing/bgp/networks', '/routing/bgp/routes'],
  18. ospf: ['/routing/ospf/instances', '/routing/ospf/areas', '/routing/ospf/templates', '/routing/ospf/neighbors', '/routing/ospf/lsa'],
  19. rip: ['/routing/rip/instances', '/routing/rip/interfaces', '/routing/rip/neighbors-live', '/routing/rip/routes'],
  20. bfd: ['/routing/bfd/instance', '/routing/bfd/interfaces', '/routing/bfd/peers', '/routing/bfd/sessions'],
  21. babel: ['/routing/babel/instances', '/routing/babel/interfaces', '/routing/babel/neighbors', '/routing/babel/routes'],
  22. radv: ['/routing/radv/instances', '/routing/radv/interfaces'],
  23. eigrp: ['/routing/eigrp/instances', '/routing/eigrp/interfaces', '/routing/eigrp/networks', '/routing/eigrp/neighbors', '/routing/eigrp/topology'],
  24. 'dhcp-client': ['/dhcp/clients'], 'dhcp-server': ['/dhcp-server/servers', '/dhcp-server/networks', '/dhcp-server/leases'],
  25. bridge: ['/bridge/summary'], sdwan: ['/sdwan/groups', '/sdwan/telemetry'],
  26. ppp: ['/vpn/ppp/secrets', '/vpn/ppp/profiles', '/vpn/ppp/active'],
  27. aerotun: ['/vpn/aerotun/tunnels', '/vpn/aerotun/stats'], wireguard: ['/vpn/wireguard/interfaces', '/vpn/wireguard/peers'],
  28. eoip: ['/vpn/eoip'], vxlan: ['/vpn/vxlan', '/vpn/vxlan/vteps'], pppoe: ['/vpn/pppoe/clients'],
  29. ipsec: ['/vpn/ipsec/tunnels'], l2tp: ['/vpn/l2tp/clients'], pptp: ['/vpn/pptp/clients'],
  30. vrrp: ['/vrrp/summary'], logs: ['/system/logs'], users: ['/users'],
  31. services: ['/system/services'], certificates: ['/certificates'], settings: ['/dns/settings', '/dns/static', '/dns/status'],
  32. reverse_proxy: ['/proxy/config', '/proxy/rules'], updates: ['/update/status']
  33. };
  34. return (endpoints[tab] || []).some(endpoint => path === '/api' + endpoint);
  35. }
  36. function renderViewDataHealth() {
  37. const el = document.getElementById('view-data-health');
  38. if (!el) return;
  39. const tab = state.activeTab;
  40. el.hidden = !['dashboard','interfaces','firewall','routes','routing-filters','bgp','ospf','rip','bfd','babel','radv','eigrp','dhcp-client','dhcp-server','bridge','sdwan','ppp','aerotun','wireguard','eoip','vxlan','pppoe','ipsec','l2tp','pptp','vrrp','logs','users','services','certificates','settings','reverse_proxy','updates'].includes(tab);
  41. if (el.hidden) return;
  42. const failures = [...telemetryHealth.failures].filter(([path]) => viewUsesEndpoint(tab, path));
  43. const successes = [...telemetryHealth.successes].filter(([path]) => viewUsesEndpoint(tab, path));
  44. if (!failures.length && !successes.length) {
  45. el.textContent = 'View data: waiting';
  46. el.title = 'No successful data request recorded for this view';
  47. } else if (failures.length) {
  48. el.textContent = 'View data: incomplete or unavailable';
  49. el.title = failures.map(([path, error]) => `${path}: ${error}`).join('\n');
  50. } else {
  51. const oldest = Math.min(...successes.map(([, time]) => time));
  52. const seconds = Math.floor((Date.now() - oldest) / 1000);
  53. el.textContent = `Tracked data: oldest update ${seconds}s ago`;
  54. el.title = 'Oldest successful response among tracked requests for this view';
  55. }
  56. el.className = `text-[10px] font-mono ${failures.length || !successes.length || Date.now() - Math.min(...successes.map(([, time]) => time)) > 60000 ? 'text-amber-400' : 'text-emerald-400'}`;
  57. }
  58. function renderTelemetryHealth() {
  59. const el = document.getElementById('telemetry-health');
  60. if (!el) return;
  61. const failures = [...telemetryHealth.failures.entries()];
  62. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  63. const stale = seconds === null || seconds > 15;
  64. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  65. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  66. 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';
  67. }
  68. function stopSessionPolling() {
  69. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  70. window._telemetryInterval = null;
  71. if (trafficEventSource) trafficEventSource.close();
  72. trafficEventSource = null;
  73. if (trafficPollFallback) clearInterval(trafficPollFallback);
  74. trafficPollFallback = null;
  75. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  76. bwtestState.pollTimer = null;
  77. if (logsTimer) clearInterval(logsTimer);
  78. logsTimer = null;
  79. stopFwStatPolling();
  80. stopNATStatPolling();
  81. stopMangleStatPolling();
  82. telemetryHealth.failures.clear();
  83. telemetryHealth.successes.clear();
  84. telemetryHealth.lastSuccess = 0;
  85. lastSummaryRefresh = 0;
  86. }
  87. window.fetch = async function(resource, options = {}) {
  88. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  89. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  90. if (!isAPI) return originalFetch(resource, options);
  91. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  92. const token = localStorage.getItem('debtik_token');
  93. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  94. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  95. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  96. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  97. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  98. const perform = async () => {
  99. let timeout;
  100. if (isRead && !config.signal) {
  101. const controller = new AbortController();
  102. config.signal = controller.signal;
  103. timeout = setTimeout(() => controller.abort(), 15000);
  104. }
  105. try {
  106. const response = await originalFetch(resource, config);
  107. if (isRead) {
  108. if (response.ok) {
  109. telemetryHealth.lastSuccess = Date.now();
  110. telemetryHealth.successes.set(url.pathname, telemetryHealth.lastSuccess);
  111. telemetryHealth.failures.delete(url.pathname);
  112. } else {
  113. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  114. }
  115. renderTelemetryHealth();
  116. renderViewDataHealth();
  117. }
  118. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  119. stopSessionPolling();
  120. state.isPolling = false;
  121. state.currentUser = null;
  122. localStorage.removeItem('debtik_token');
  123. showLoginScreen(true);
  124. }
  125. return response;
  126. } catch (err) {
  127. if (isRead) {
  128. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  129. renderTelemetryHealth();
  130. renderViewDataHealth();
  131. }
  132. throw err;
  133. } finally {
  134. if (timeout) clearTimeout(timeout);
  135. }
  136. };
  137. if (!isRead) return perform();
  138. const request = perform();
  139. pendingAPIReads.set(key, request);
  140. try { return (await request).clone(); }
  141. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  142. };
  143. let state = {
  144. currentUser: null,
  145. users: [],
  146. interfaces: [],
  147. vlans: [],
  148. systemStatus: null,
  149. vpnStatus: null,
  150. routes: [],
  151. activeTab: 'dashboard',
  152. fwSubTab: 'filter',
  153. bridgeSubTab: 'bridges',
  154. bridges: [],
  155. bridgePorts: [],
  156. bridgeVLANs: [],
  157. bridgeHosts: [],
  158. bridgeSummary: null,
  159. routesSubTab: 'routes',
  160. pppSubTab: 'secrets',
  161. eoipTunnels: [],
  162. vxlanTunnels: [],
  163. vxlanVteps: [],
  164. pppSecrets: [],
  165. pppProfiles: [],
  166. pppActiveSessions: [],
  167. pppoeServer: null,
  168. pptpServer: null,
  169. l2tpServer: null,
  170. ipsecServer: null,
  171. ifaceFilter: 'all',
  172. currentModalIface: null,
  173. isPolling: false,
  174. expandedParents: new Set(['eth0']),
  175. pppoeData: null,
  176. wgData: null,
  177. ipsecData: null,
  178. l2tpData: null,
  179. pptpData: null,
  180. fwSummary: null,
  181. filterRules: [],
  182. natRules: [],
  183. mangleRules: [],
  184. addressLists: [],
  185. connections: [],
  186. policyRules: [],
  187. routingTables: [],
  188. routingFilters: [],
  189. filterChainSelected: 'all',
  190. activeToolsSubTab: 'ping',
  191. dhcpClients: [],
  192. dhcpSummary: null,
  193. dhcpServerTab: 'servers',
  194. dhcpServers: [],
  195. dhcpNetworks: [],
  196. dhcpLeases: [],
  197. dhcpOptions: [],
  198. dhcpServerSummary: null,
  199. sdwanGroups: [],
  200. sdwanTelemetry: null
  201. };
  202. const API_BASE = '/api';
  203. function escapeHtml(str) {
  204. if (str === null || str === undefined) return '';
  205. return String(str)
  206. .replace(/&/g, '&')
  207. .replace(/</g, '&lt;')
  208. .replace(/>/g, '&gt;')
  209. .replace(/"/g, '&quot;')
  210. .replace(/'/g, '&#039;');
  211. }
  212. function formatBytes(bytes) {
  213. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  214. const k = 1024;
  215. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  216. const i = Math.floor(Math.log(bytes) / Math.log(k));
  217. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  218. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  219. }
  220. // Initialize on page load
  221. document.addEventListener('DOMContentLoaded', async () => {
  222. initTableSorting();
  223. // Verify authentication before bootstrapping telemetry and views
  224. const isAuthenticated = await checkAuthStatus();
  225. if (isAuthenticated) {
  226. const hash = window.location.hash.replace('#', '') || 'dashboard';
  227. navigate(hash);
  228. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  229. if (!window._telemetryInterval) {
  230. window._telemetryInterval = setInterval(() => {
  231. if (state.isPolling && state.currentUser && !document.hidden) {
  232. fetchData(false);
  233. }
  234. }, 5000);
  235. }
  236. }
  237. });
  238. let trafficEventSource = null;
  239. let trafficPollFallback = null;
  240. function initLiveTrafficStream() {
  241. if (trafficEventSource) {
  242. try { trafficEventSource.close(); } catch(e) {}
  243. trafficEventSource = null;
  244. }
  245. if (trafficPollFallback) {
  246. clearInterval(trafficPollFallback);
  247. trafficPollFallback = null;
  248. }
  249. if (window.EventSource) {
  250. try {
  251. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  252. trafficEventSource.onmessage = (event) => {
  253. try {
  254. const data = JSON.parse(event.data);
  255. updateLiveInterfaceTraffic(data);
  256. } catch (e) {
  257. console.error('Error parsing live traffic event:', e);
  258. }
  259. };
  260. trafficEventSource.onerror = () => {
  261. // Fallback polling if SSE disconnects
  262. if (!trafficPollFallback) {
  263. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  264. }
  265. };
  266. trafficEventSource.onopen = () => {
  267. if (trafficPollFallback) {
  268. clearInterval(trafficPollFallback);
  269. trafficPollFallback = null;
  270. }
  271. };
  272. return;
  273. } catch (e) {
  274. console.warn('EventSource failed, using 1s polling fallback:', e);
  275. }
  276. }
  277. // Fallback if EventSource is unavailable
  278. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  279. }
  280. async function pollLiveTrafficSnapshot() {
  281. try {
  282. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  283. if (res.ok) {
  284. const data = await res.json();
  285. updateLiveInterfaceTraffic(data);
  286. }
  287. } catch (e) {}
  288. }
  289. function updateLiveInterfaceTraffic(data) {
  290. if (!data || !data.interfaces) return;
  291. state.latestTraffic = data;
  292. // 1. Update Top & Dashboard Total Bandwidth Indicators
  293. const rxHuman = data.total_rx_human || '0 B/s';
  294. const txHuman = data.total_tx_human || '0 B/s';
  295. const statRx = document.getElementById('stat-traffic-rx');
  296. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  297. const statTx = document.getElementById('stat-traffic-tx');
  298. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  299. // 2. Update state.interfaces rates in-memory
  300. if (Array.isArray(state.interfaces)) {
  301. state.interfaces.forEach(i => {
  302. const live = data.interfaces[i.name];
  303. if (live) {
  304. i.rate = {
  305. rx_bytes_sec: live.rx_bytes_sec,
  306. tx_bytes_sec: live.tx_bytes_sec,
  307. rx_human: live.rx_human,
  308. tx_human: live.tx_human
  309. };
  310. i.stats = {
  311. rx_bytes: live.rx_bytes,
  312. tx_bytes: live.tx_bytes,
  313. rx_packets: live.rx_packets,
  314. tx_packets: live.tx_packets,
  315. rx_errors: live.rx_errors,
  316. tx_errors: live.tx_errors,
  317. rx_dropped: live.rx_dropped,
  318. tx_dropped: live.tx_dropped
  319. };
  320. }
  321. });
  322. }
  323. // 3. Update all live UI rate spans in-place (ZERO flicker)
  324. Object.keys(data.interfaces).forEach(name => {
  325. const live = data.interfaces[name];
  326. // Dashboard Port Matrix Card
  327. const cardRate = document.getElementById(`port-card-rate-${name}`);
  328. if (cardRate && cardRate.innerText !== live.rx_human) {
  329. cardRate.innerText = live.rx_human;
  330. }
  331. // Dashboard Quick Interfaces Table
  332. const quickRx = document.getElementById(`quick-rx-${name}`);
  333. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  334. const quickTx = document.getElementById(`quick-tx-${name}`);
  335. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  336. // Main Interfaces Tree Table
  337. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  338. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  339. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  340. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  341. // VLAN Sub-interfaces Table
  342. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  343. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  344. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  345. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  346. // VLAN Page Table
  347. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  348. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  349. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  350. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  351. });
  352. }
  353. // Navigation Handler
  354. function navigate(tabName) {
  355. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  356. navigate('bgp');
  357. return;
  358. }
  359. if (tabName === 'vlans') {
  360. navigate('interfaces');
  361. return;
  362. }
  363. if (tabName === 'persistence') {
  364. navigate('dashboard');
  365. return;
  366. }
  367. stopFwStatPolling();
  368. stopNATStatPolling();
  369. stopMangleStatPolling();
  370. state.activeTab = tabName;
  371. renderViewDataHealth();
  372. window.location.hash = tabName;
  373. // Update nav links styling
  374. document.querySelectorAll('.nav-link').forEach(link => {
  375. 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';
  376. });
  377. const activeNav = document.getElementById(`nav-${tabName}`);
  378. if (activeNav) {
  379. 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';
  380. }
  381. // Update page headers
  382. const titles = {
  383. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  384. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  385. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  386. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  387. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  388. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  389. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  390. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  391. sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
  392. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  393. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  394. rip: { title: 'RIP Dynamic Routing', sub: 'Routing Information Protocol (RIPv2 IPv4 & RIPng IPv6) hop-count distance-vector routing' },
  395. bfd: { title: 'BFD Fast Session Detection', sub: 'Bidirectional Forwarding Detection (BFD) sub-second link failure detection for BGP and OSPF' },
  396. babel: { title: 'Babel Dynamic Routing', sub: 'Babel loop-avoiding distance-vector routing for wired and wireless mesh networks (RFC 8966)' },
  397. radv: { title: 'IPv6 Router Advertisements (RAdv)', sub: 'BIRD 2 ICMPv6 Router Advertisement daemon for IPv6 SLAAC autoconfiguration and RDNSS' },
  398. eigrp: { title: 'EIGRP Dynamic Routing', sub: 'Enhanced Interior Gateway Routing Protocol (RFC 7868) DUAL routing, neighbors and topology' },
  399. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  400. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  401. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  402. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  403. vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
  404. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  405. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  406. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  407. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  408. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  409. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  410. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  411. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  412. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  413. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  414. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  415. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  416. reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
  417. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  418. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  419. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  420. };
  421. const header = titles[tabName] || titles.dashboard;
  422. const pTitle = document.getElementById('page-title');
  423. if (pTitle) pTitle.innerText = header.title;
  424. const pSub = document.getElementById('page-subtitle');
  425. if (pSub) pSub.innerText = header.sub;
  426. // Toggle sections dynamically for all section elements
  427. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  428. if (el.id === `section-${tabName}`) {
  429. el.classList.remove('hidden');
  430. } else {
  431. el.classList.add('hidden');
  432. }
  433. });
  434. if (tabName === 'interfaces') {
  435. loadRoles();
  436. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  437. else switchIfaceSubTab('tree');
  438. }
  439. if (tabName === 'bridge') loadBridge();
  440. if (tabName === 'firewall') loadFirewall();
  441. if (tabName === 'routes') loadRoutes();
  442. if (tabName === 'sdwan') loadSDWAN();
  443. if (tabName === 'bgp') {
  444. loadDynamicRouting();
  445. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  446. }
  447. if (tabName === 'ospf') {
  448. loadDynamicRouting();
  449. switchOspfTab(state.activeOspfTab || 'instances');
  450. }
  451. if (tabName === 'rip') {
  452. loadDynamicRouting();
  453. switchRipTab(state.activeRipTab || 'instances');
  454. }
  455. if (tabName === 'bfd') {
  456. loadDynamicRouting();
  457. switchBfdTab(state.activeBfdTab || 'config');
  458. }
  459. if (tabName === 'babel') {
  460. loadDynamicRouting();
  461. switchBabelTab(state.activeBabelTab || 'instances');
  462. }
  463. if (tabName === 'radv') {
  464. loadDynamicRouting();
  465. switchRadvTab(state.activeRadvTab || 'instances');
  466. }
  467. if (tabName === 'eigrp') {
  468. loadDynamicRouting();
  469. switchEigrpTab(state.activeEigrpTab || 'instances');
  470. }
  471. if (tabName === 'routing-filters') loadDynamicRouting();
  472. if (tabName === 'dynamic-routing') loadDynamicRouting();
  473. if (tabName === 'ppp') loadPPP();
  474. if (tabName === 'eoip') loadEoIP();
  475. if (tabName === 'vxlan') loadVXLAN();
  476. if (tabName === 'aerotun') loadAeroTUN();
  477. if (tabName === 'pppoe') loadPPPoE();
  478. if (tabName === 'wireguard') loadWireGuard();
  479. if (tabName === 'ipsec') loadIPSec();
  480. if (tabName === 'l2tp') loadL2TP();
  481. if (tabName === 'pptp') loadPPTP();
  482. if (tabName === 'tools') loadToolsView();
  483. if (tabName === 'dhcp-client') loadDHCPClients();
  484. if (tabName === 'dhcp-server') loadDHCPServer();
  485. if (tabName === 'vrrp') loadVRRP();
  486. if (tabName === 'bwtest') loadBwTestView();
  487. if (tabName === 'settings') loadSettingsData();
  488. if (tabName === 'users') loadUsers();
  489. if (tabName === 'certificates') loadCertificates();
  490. if (tabName === 'reverse_proxy') loadReverseProxy();
  491. if (tabName === 'services') loadServices();
  492. if (tabName === 'updates') loadUpdateStatus();
  493. if (tabName === 'logs') loadLogs();
  494. setTimeout(initTableSorting, 50);
  495. }
  496. // Fetch all core system, network and VPN telemetry
  497. function fetchData(isManual = false) {
  498. if (coreRefreshPromise) return coreRefreshPromise;
  499. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  500. return coreRefreshPromise;
  501. }
  502. async function refreshCoreData(isManual = false) {
  503. const spinner = document.getElementById('refresh-spinner');
  504. if (isManual && spinner) spinner.classList.add('animate-spin');
  505. try {
  506. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  507. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  508. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  509. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  510. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  511. summaryFetch('/vlans'),
  512. summaryFetch('/vpn/status'),
  513. summaryFetch('/firewall/summary'),
  514. summaryFetch('/routing/dynamic/summary'),
  515. summaryFetch('/bridge/summary'),
  516. summaryFetch('/dhcp/clients/summary'),
  517. summaryFetch('/dhcp/clients'),
  518. summaryFetch('/vrrp/summary').catch(() => null),
  519. summaryFetch('/roles').catch(() => null)
  520. ]);
  521. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  522. if (rolesRes && rolesRes.ok) {
  523. state.roles = await rolesRes.json();
  524. const countEl = document.getElementById('badge-roles-count');
  525. if (countEl) countEl.innerText = (state.roles || []).length;
  526. }
  527. if (vrrpSumRes && vrrpSumRes.ok) {
  528. state.vrrpSummary = await vrrpSumRes.json();
  529. renderVRRPSummary();
  530. }
  531. if (dhcpSumRes && dhcpSumRes.ok) {
  532. state.dhcpSummary = await dhcpSumRes.json();
  533. const bDhcp = document.getElementById('badge-dhcp-client-count');
  534. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  535. }
  536. if (dhcpClientsRes && dhcpClientsRes.ok) {
  537. state.dhcpClients = await dhcpClientsRes.json();
  538. }
  539. if (brSummaryRes.ok) {
  540. state.bridgeSummary = await brSummaryRes.json();
  541. const bBridge = document.getElementById('badge-bridge-count');
  542. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  543. const sBr = document.getElementById('bridge-stat-bridges');
  544. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  545. const sPorts = document.getElementById('bridge-stat-ports');
  546. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  547. const sHosts = document.getElementById('bridge-stat-hosts');
  548. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  549. }
  550. if (statusRes.ok) state.systemStatus = await statusRes.json();
  551. if (ifacesRes.ok) {
  552. const ifacesData = await ifacesRes.json();
  553. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  554. state.interfaces = rawIfaces.filter(i => {
  555. if (!i.name) return false;
  556. if (i.name.startsWith('ep_')) return false;
  557. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  558. });
  559. try { populateToolsInterfaces(); } catch (e) {}
  560. }
  561. if (vlansRes.ok) {
  562. const vlansData = await vlansRes.json();
  563. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  564. }
  565. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  566. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  567. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  568. updateSystemMetrics();
  569. updateBadges();
  570. if (state.activeTab === 'dashboard') renderDashboard();
  571. if (state.activeTab === 'interfaces') {
  572. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  573. else renderInterfacesList();
  574. }
  575. if (state.activeTab === 'vlans') renderVlansList();
  576. if (state.activeTab === 'firewall') await loadFirewall(false);
  577. if (state.activeTab === 'routes') await loadRoutes(false);
  578. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf' || state.activeTab === 'rip' || state.activeTab === 'bfd' || state.activeTab === 'babel' || state.activeTab === 'radv' || state.activeTab === 'eigrp' || state.activeTab === 'routing-filters') await loadDynamicRouting(false);
  579. if (state.activeTab === 'ppp') await loadPPP(false);
  580. if (state.activeTab === 'eoip') await loadEoIP(false);
  581. if (state.activeTab === 'vxlan') await loadVXLAN(false);
  582. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  583. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  584. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  585. if (state.activeTab === 'ipsec') await loadIPSec(false);
  586. if (state.activeTab === 'l2tp') await loadL2TP(false);
  587. if (state.activeTab === 'pptp') await loadPPTP(false);
  588. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  589. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  590. if (state.activeTab === 'vrrp') await loadVRRP(false);
  591. if (state.activeTab === 'settings') await loadSettingsData(false);
  592. if (state.activeTab === 'users') await loadUsers(false);
  593. if (state.activeTab === 'certificates') await loadCertificates(false);
  594. if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
  595. if (state.activeTab === 'sdwan') await loadSDWAN(false);
  596. if (state.activeTab === 'services') await loadServices(false);
  597. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  598. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  599. } catch (err) {
  600. console.error('Failed to fetch router state:', err);
  601. } finally {
  602. if (isManual && spinner) {
  603. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  604. }
  605. }
  606. }
  607. // Update Top KPI and Sidebar Telemetry
  608. function updateSystemMetrics() {
  609. const s = state.systemStatus;
  610. const v = state.vpnStatus;
  611. if (!s) return;
  612. // Sidebar Host & Uptime
  613. const sideHost = document.getElementById('side-hostname');
  614. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  615. const sideUp = document.getElementById('side-uptime');
  616. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  617. const sideGw = document.getElementById('side-gateway-ip');
  618. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  619. // Compute CPU Metrics
  620. let cpuPct = 0;
  621. if (s.cpu_pct !== undefined) {
  622. cpuPct = s.cpu_pct;
  623. } else if (s.cpu_load && s.cpu_load.length > 0) {
  624. const cores = s.cpu_cores || 1;
  625. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  626. }
  627. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  628. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  629. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  630. // Sidebar CPU
  631. const sideCpuVal = document.getElementById('side-cpu-val');
  632. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  633. const sideCpuBar = document.getElementById('side-cpu-bar');
  634. if (sideCpuBar) {
  635. sideCpuBar.style.width = cpuWidth;
  636. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  637. }
  638. // Dashboard CPU Card
  639. const dashCpuVal = document.getElementById('dash-cpu-val');
  640. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  641. const dashCpuBar = document.getElementById('dash-cpu-bar');
  642. if (dashCpuBar) {
  643. dashCpuBar.style.width = cpuWidth;
  644. if (cpuPct > 85) {
  645. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  646. } else if (cpuPct > 65) {
  647. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  648. } else {
  649. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  650. }
  651. }
  652. const dashCpuCores = document.getElementById('dash-cpu-cores');
  653. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  654. const dashCpuLoad = document.getElementById('dash-cpu-load');
  655. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  656. const dashCpuStatus = document.getElementById('dash-cpu-status');
  657. if (dashCpuStatus) {
  658. if (cpuPct > 85) {
  659. dashCpuStatus.innerText = 'High';
  660. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  661. } else if (cpuPct > 65) {
  662. dashCpuStatus.innerText = 'Heavy';
  663. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  664. } else {
  665. dashCpuStatus.innerText = 'Normal';
  666. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  667. }
  668. }
  669. // Compute RAM Metrics
  670. const memPct = Math.round(s.mem_usage_pct || 0);
  671. const memPctStr = `${memPct}%`;
  672. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  673. const usedMB = s.mem_used_mb || 0;
  674. const totalMB = s.mem_total_mb || 0;
  675. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  676. function fmtMemMB(mb) {
  677. if (mb >= 1024) {
  678. return `${(mb / 1024).toFixed(1)} GB`;
  679. }
  680. return `${mb} MB`;
  681. }
  682. // Sidebar RAM
  683. const sideRamVal = document.getElementById('side-ram-val');
  684. if (sideRamVal) sideRamVal.innerText = memPctStr;
  685. const sideRamBar = document.getElementById('side-ram-bar');
  686. if (sideRamBar) sideRamBar.style.width = memWidth;
  687. // Dashboard RAM Card
  688. const dashRamVal = document.getElementById('dash-ram-val');
  689. if (dashRamVal) dashRamVal.innerText = memPctStr;
  690. const dashRamBar = document.getElementById('dash-ram-bar');
  691. if (dashRamBar) {
  692. dashRamBar.style.width = memWidth;
  693. if (memPct > 85) {
  694. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  695. } else if (memPct > 70) {
  696. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  697. } else {
  698. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  699. }
  700. }
  701. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  702. if (dashRamUsedTotal) {
  703. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  704. }
  705. const dashRamFree = document.getElementById('dash-ram-free');
  706. if (dashRamFree) {
  707. dashRamFree.innerText = fmtMemMB(freeMB);
  708. }
  709. const dashRamStatus = document.getElementById('dash-ram-status');
  710. if (dashRamStatus) {
  711. if (memPct > 85) {
  712. dashRamStatus.innerText = 'High';
  713. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  714. } else {
  715. dashRamStatus.innerText = 'Active';
  716. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  717. }
  718. }
  719. // Legacy Dashboard Stats (Safe checks)
  720. const elIfacesUp = document.getElementById('stat-ifaces-up');
  721. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  722. const elIfacesTot = document.getElementById('stat-ifaces-total');
  723. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  724. const elIfacesDown = document.getElementById('stat-ifaces-down');
  725. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  726. const elVlans = document.getElementById('stat-vlans-count');
  727. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  728. // VPN Status Indicators
  729. if (v) {
  730. const totalActive = v.total_active_tunnels || 0;
  731. const statVpnActive = document.getElementById('stat-vpn-active');
  732. if (statVpnActive) statVpnActive.innerText = totalActive;
  733. const tunnelsDot = document.getElementById('tunnels-dot');
  734. const tunnelsLabel = document.getElementById('tunnels-label');
  735. if (tunnelsDot && tunnelsLabel) {
  736. if (totalActive > 0) {
  737. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  738. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  739. } else {
  740. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  741. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  742. }
  743. }
  744. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  745. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  746. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  747. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  748. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  749. }
  750. // Total Live Bandwidth Rate
  751. let totalRx = 0;
  752. let totalTx = 0;
  753. (state.interfaces || []).forEach(i => {
  754. if (i.rate) {
  755. totalRx += i.rate.rx_bytes_sec || 0;
  756. totalTx += i.rate.tx_bytes_sec || 0;
  757. }
  758. });
  759. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  760. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  761. }
  762. function setDotBadge(id, active) {
  763. const el = document.getElementById(id);
  764. if (!el) return;
  765. if (active) {
  766. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  767. } else {
  768. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  769. }
  770. }
  771. function updateBadges() {
  772. const bIfaces = document.getElementById('badge-ifaces-count');
  773. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  774. const bVlans = document.getElementById('badge-vlans-count');
  775. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  776. if (state.fwSummary) {
  777. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  778. const badgeFw = document.getElementById('badge-firewall-count');
  779. if (badgeFw) badgeFw.innerText = totalFwRules;
  780. }
  781. if (state.vpnStatus) {
  782. const v = state.vpnStatus;
  783. const bEoIP = document.getElementById('badge-eoip-count');
  784. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  785. const bVXLAN = document.getElementById('badge-vxlan-count');
  786. if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
  787. const bAero = document.getElementById('badge-aerotun-count');
  788. if (bAero) bAero.innerText = v.total_aerotun || 0;
  789. const bPPPSess = document.getElementById('badge-ppp-sessions');
  790. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  791. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  792. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  793. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  794. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  795. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  796. }
  797. if (state.dynSummary) {
  798. const d = state.dynSummary;
  799. setDotBadge('badge-bgp-dot', d.bgp_running);
  800. setDotBadge('badge-ospf-dot', d.ospf_running);
  801. setDotBadge('badge-rip-dot', d.rip_running);
  802. setDotBadge('badge-bfd-dot', d.bfd_running);
  803. setDotBadge('badge-babel-dot', d.babel_running);
  804. setDotBadge('badge-radv-dot', d.radv_running);
  805. setDotBadge('badge-eigrp-dot', d.eigrp_running);
  806. const bBgp = document.getElementById('badge-bgp-count');
  807. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  808. const bOspf = document.getElementById('badge-ospf-count');
  809. if (bOspf) bOspf.innerText = (state.ospfLiveInterfaces || state.ospfTemplates || []).length;
  810. const bRip = document.getElementById('badge-rip-count');
  811. if (bRip) bRip.innerText = (state.ripInterfaces || []).length;
  812. const bBfd = document.getElementById('badge-bfd-count');
  813. if (bBfd) bBfd.innerText = (state.bfdInterfaces || []).length;
  814. const bBabel = document.getElementById('badge-babel-count');
  815. if (bBabel) bBabel.innerText = (state.babelInterfaces || []).length;
  816. const bRadv = document.getElementById('badge-radv-count');
  817. if (bRadv) bRadv.innerText = (state.radvInterfaces || []).length;
  818. const bEigrp = document.getElementById('badge-eigrp-count');
  819. if (bEigrp) bEigrp.innerText = (state.eigrpInterfaces || []).length || (state.eigrpNetworks || []).length || (state.eigrpInstances || []).length;
  820. const bFilters = document.getElementById('badge-filters-count');
  821. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  822. }
  823. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  824. if (bDhcpServer) {
  825. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  826. }
  827. }
  828. // Render Dashboard View
  829. function renderDashboard() {
  830. const matrix = document.getElementById('port-matrix');
  831. if (!matrix) return;
  832. const ifaces = state.interfaces || [];
  833. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  834. if (matrix.dataset.sig === sig) {
  835. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  836. }
  837. matrix.dataset.sig = sig;
  838. matrix.innerHTML = '';
  839. (state.interfaces || []).forEach(iface => {
  840. const isUp = iface.state === 'UP';
  841. const isVlan = iface.is_vlan;
  842. const portCard = document.createElement('div');
  843. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  844. isUp
  845. ? (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')
  846. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  847. }`;
  848. portCard.onclick = () => openIfaceModal(iface.name);
  849. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  850. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  851. portCard.innerHTML = `
  852. <div class="flex items-center justify-between mb-2">
  853. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  854. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  855. </div>
  856. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  857. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  858. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  859. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  860. </div>
  861. `;
  862. matrix.appendChild(portCard);
  863. });
  864. const ifaceTbody = document.getElementById('quick-interfaces-table');
  865. if (ifaceTbody) {
  866. ifaceTbody.innerHTML = '';
  867. (state.interfaces || []).forEach(i => {
  868. const isUp = i.state === 'UP';
  869. const tr = document.createElement('tr');
  870. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  871. tr.onclick = () => openIfaceModal(i.name);
  872. const rxStr = i.rate?.rx_human || '0 B/s';
  873. const txStr = i.rate?.tx_human || '0 B/s';
  874. tr.innerHTML = `
  875. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  876. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  877. <span>${i.name}</span>
  878. </td>
  879. <td class="py-2.5 text-slate-300 font-sans">
  880. ${getRoleBadge(i.role || 'LAN')}
  881. </td>
  882. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  883. <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>
  884. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  885. <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>
  886. </td>
  887. <td class="py-2.5 text-right font-sans font-semibold">
  888. <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>
  889. </td>
  890. `;
  891. ifaceTbody.appendChild(tr);
  892. });
  893. }
  894. const vlanTbody = document.getElementById('quick-vlans-table');
  895. if (vlanTbody) {
  896. vlanTbody.innerHTML = '';
  897. }
  898. }
  899. // Expand / Collapse Handlers
  900. function toggleExpand(parentName) {
  901. if (state.expandedParents.has(parentName)) {
  902. state.expandedParents.delete(parentName);
  903. } else {
  904. state.expandedParents.add(parentName);
  905. }
  906. renderInterfacesList();
  907. }
  908. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  909. function supportsVLAN(iface) {
  910. if (!iface) return false;
  911. if (iface.is_vlan) return false;
  912. const name = (iface.name || '').toLowerCase();
  913. const type = (iface.type || '').toLowerCase();
  914. const role = (iface.role || '').toLowerCase();
  915. // Exclude loopback
  916. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  917. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  918. if (type === 'wireguard' || name.startsWith('wg')) return false;
  919. // Exclude PPP / PPPoE
  920. if (type === 'ppp' || name.startsWith('ppp')) return false;
  921. // Exclude other Layer 3 tunnels and dummy devices
  922. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  923. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  924. return false;
  925. }
  926. // If name already contains a dot, it's already a sub-interface
  927. if (name.includes('.')) return false;
  928. return true;
  929. }
  930. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  931. function supportsDHCPClient(iface) {
  932. if (!iface) return false;
  933. const name = (iface.name || '').toLowerCase();
  934. const type = (iface.type || '').toLowerCase();
  935. const role = (iface.role || '').toLowerCase();
  936. // Exclude loopback
  937. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  938. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  939. if (type === 'wireguard' || name.startsWith('wg')) return false;
  940. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  941. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  942. // Exclude other Layer 3 tunnels and dummy devices
  943. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  944. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  945. return false;
  946. }
  947. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  948. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  949. if (isBridgePort) return false;
  950. return true;
  951. }
  952. // Expand / Collapse Handlers
  953. function toggleExpand(parentName) {
  954. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  955. if (childVlans.length === 0) {
  956. // Cannot expand an interface with no VLANs
  957. state.expandedParents.delete(parentName);
  958. return;
  959. }
  960. if (state.expandedParents.has(parentName)) {
  961. state.expandedParents.delete(parentName);
  962. } else {
  963. state.expandedParents.add(parentName);
  964. }
  965. renderInterfacesList();
  966. }
  967. function expandAllIfaces(expand) {
  968. if (expand) {
  969. (state.interfaces || []).forEach(i => {
  970. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  971. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  972. });
  973. } else {
  974. state.expandedParents.clear();
  975. }
  976. renderInterfacesList();
  977. }
  978. // =========================================================================
  979. // INTERFACE ROLE TAGS MANAGEMENT
  980. // =========================================================================
  981. const ROLE_COLORS = {
  982. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  983. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  984. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  985. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  986. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  987. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  988. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  989. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  990. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  991. };
  992. function getRoleBadge(roleName) {
  993. const name = roleName || 'LAN';
  994. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  995. const colorKey = (role?.color || 'blue').toLowerCase();
  996. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  997. 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>`;
  998. }
  999. function switchIfaceSubTab(subTab) {
  1000. state.activeIfaceSubTab = subTab;
  1001. const treeTab = document.getElementById('ifaces-subtab-tree');
  1002. const rolesTab = document.getElementById('ifaces-subtab-roles');
  1003. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  1004. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  1005. if (subTab === 'roles') {
  1006. treeTab?.classList.add('hidden');
  1007. rolesTab?.classList.remove('hidden');
  1008. if (btnRoles) {
  1009. 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';
  1010. }
  1011. if (btnTree) {
  1012. 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';
  1013. }
  1014. loadRoles();
  1015. } else {
  1016. rolesTab?.classList.add('hidden');
  1017. treeTab?.classList.remove('hidden');
  1018. if (btnTree) {
  1019. 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';
  1020. }
  1021. if (btnRoles) {
  1022. 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';
  1023. }
  1024. renderInterfacesList();
  1025. }
  1026. }
  1027. async function loadRoles() {
  1028. try {
  1029. const res = await fetch(`${API_BASE}/roles`);
  1030. if (res.ok) {
  1031. state.roles = await res.json();
  1032. const countEl = document.getElementById('badge-roles-count');
  1033. if (countEl) countEl.innerText = (state.roles || []).length;
  1034. renderRolesTable();
  1035. populateRoleSelects();
  1036. }
  1037. } catch (err) {
  1038. console.error('Failed to load role tags:', err);
  1039. }
  1040. }
  1041. function renderRolesTable() {
  1042. const tbody = document.getElementById('roles-table-body');
  1043. const empty = document.getElementById('roles-empty-state');
  1044. if (!tbody) return;
  1045. const roles = state.roles || [];
  1046. if (roles.length === 0) {
  1047. tbody.innerHTML = '';
  1048. empty?.classList.remove('hidden');
  1049. return;
  1050. }
  1051. empty?.classList.add('hidden');
  1052. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  1053. if (tbody.dataset.sig === sig) return;
  1054. tbody.dataset.sig = sig;
  1055. tbody.innerHTML = roles.map(r => {
  1056. const colorKey = (r.color || 'blue').toLowerCase();
  1057. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1058. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  1059. const ifacesChips = ifaces.length > 0
  1060. ? 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('')
  1061. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  1062. return `
  1063. <tr class="hover:bg-slate-800/40 transition">
  1064. <td class="py-3 px-4">
  1065. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  1066. ${escapeHtml(r.name)}
  1067. </span>
  1068. </td>
  1069. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  1070. <span>${escapeHtml(r.name)}</span>
  1071. ${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>' : ''}
  1072. </td>
  1073. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  1074. <span class="inline-flex items-center gap-1.5">
  1075. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  1076. <span>${escapeHtml(r.color || 'blue')}</span>
  1077. </span>
  1078. </td>
  1079. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  1080. <td class="py-3 px-4 font-sans">
  1081. <div class="flex flex-wrap items-center">
  1082. ${ifacesChips}
  1083. </div>
  1084. </td>
  1085. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  1086. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  1087. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1088. Edit
  1089. </button>
  1090. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  1091. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1092. Delete
  1093. </button>
  1094. </td>
  1095. </tr>
  1096. `;
  1097. }).join('');
  1098. }
  1099. function openRoleModal(id = null) {
  1100. const modal = document.getElementById('role-modal');
  1101. if (!modal) return;
  1102. const idInput = document.getElementById('role-modal-id');
  1103. const nameInput = document.getElementById('role-modal-name');
  1104. const colorSelect = document.getElementById('role-modal-color');
  1105. const descInput = document.getElementById('role-modal-desc');
  1106. const title = document.getElementById('role-modal-title');
  1107. if (id) {
  1108. const role = (state.roles || []).find(r => r.id === id);
  1109. if (role) {
  1110. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1111. if (idInput) idInput.value = role.id;
  1112. if (nameInput) nameInput.value = role.name;
  1113. if (colorSelect) colorSelect.value = role.color || 'blue';
  1114. if (descInput) descInput.value = role.description || '';
  1115. }
  1116. } else {
  1117. if (title) title.innerText = 'Add Role Tag';
  1118. if (idInput) idInput.value = '';
  1119. if (nameInput) nameInput.value = '';
  1120. if (colorSelect) colorSelect.value = 'blue';
  1121. if (descInput) descInput.value = '';
  1122. }
  1123. updateRoleModalPreview();
  1124. modal.classList.remove('hidden');
  1125. }
  1126. function closeRoleModal() {
  1127. const modal = document.getElementById('role-modal');
  1128. if (modal) modal.classList.add('hidden');
  1129. }
  1130. function updateRoleModalPreview() {
  1131. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1132. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1133. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1134. const preview = document.getElementById('role-modal-preview');
  1135. if (preview) {
  1136. preview.innerText = name;
  1137. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1138. }
  1139. }
  1140. async function submitSaveRole(e) {
  1141. e.preventDefault();
  1142. const id = document.getElementById('role-modal-id')?.value;
  1143. const name = document.getElementById('role-modal-name')?.value.trim();
  1144. const color = document.getElementById('role-modal-color')?.value;
  1145. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1146. if (!name) return;
  1147. try {
  1148. const payload = { id, name, color, description: desc };
  1149. const method = id ? 'PUT' : 'POST';
  1150. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1151. const res = await fetch(url, {
  1152. method,
  1153. headers: { 'Content-Type': 'application/json' },
  1154. body: JSON.stringify(payload)
  1155. });
  1156. if (res.ok) {
  1157. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1158. closeRoleModal();
  1159. await loadRoles();
  1160. fetchData(false);
  1161. } else {
  1162. const err = await res.json();
  1163. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1164. }
  1165. } catch (err) {
  1166. showToast('Error', err.message, 'error');
  1167. }
  1168. }
  1169. async function deleteRoleTag(id, name) {
  1170. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1171. try {
  1172. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1173. method: 'DELETE'
  1174. });
  1175. if (res.ok) {
  1176. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1177. await loadRoles();
  1178. fetchData(false);
  1179. } else {
  1180. const err = await res.json();
  1181. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1182. }
  1183. } catch (err) {
  1184. showToast('Error', err.message, 'error');
  1185. }
  1186. }
  1187. function populateRoleSelects(selectedRole = '') {
  1188. const ifaceSelect = document.getElementById('modal-iface-role');
  1189. const vlanSelect = document.getElementById('vlan-role');
  1190. const roles = state.roles || [];
  1191. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1192. if (ifaceSelect) {
  1193. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1194. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1195. ifaceSelect.innerHTML = optionsHtml;
  1196. ifaceSelect.dataset.optionsSig = optionsHtml;
  1197. }
  1198. if (currentVal) ifaceSelect.value = currentVal;
  1199. }
  1200. if (vlanSelect) {
  1201. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1202. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1203. vlanSelect.innerHTML = optionsHtml;
  1204. vlanSelect.dataset.optionsSig = optionsHtml;
  1205. }
  1206. if (currentVal) vlanSelect.value = currentVal;
  1207. }
  1208. }
  1209. // Filter and Render Hierarchical Interfaces List
  1210. function filterIfaces(filter) {
  1211. state.ifaceFilter = filter || 'all';
  1212. renderInterfacesList();
  1213. }
  1214. function renderInterfacesList() {
  1215. const tbody = document.getElementById('interfaces-tree-tbody');
  1216. const emptyState = document.getElementById('interfaces-empty-state');
  1217. const summary = document.getElementById('ifaces-list-summary');
  1218. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1219. const allIfaces = state.interfaces || [];
  1220. const allVlans = state.vlans || [];
  1221. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1222. const filteredParents = parentIfaces.filter(parent => {
  1223. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1224. if (query) {
  1225. const matchName = parent.name.toLowerCase().includes(query);
  1226. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1227. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1228. const matchType = (parent.type || '').toLowerCase().includes(query);
  1229. const matchVlan = childVlans.some(v =>
  1230. v.name.toLowerCase().includes(query) ||
  1231. String(v.vlan_id).includes(query) ||
  1232. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1233. (v.description || '').toLowerCase().includes(query)
  1234. );
  1235. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1236. }
  1237. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1238. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1239. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1240. return true;
  1241. });
  1242. if (summary) {
  1243. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1244. }
  1245. if (filteredParents.length === 0) {
  1246. emptyState?.classList.remove('hidden');
  1247. tbody.innerHTML = '';
  1248. return;
  1249. }
  1250. emptyState?.classList.add('hidden');
  1251. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1252. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1253. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1254. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1255. }).join(';');
  1256. if (tbody.dataset.sig === sig) {
  1257. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1258. }
  1259. tbody.dataset.sig = sig;
  1260. tbody.innerHTML = '';
  1261. filteredParents.forEach(parent => {
  1262. const isUp = parent.state === 'UP';
  1263. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1264. const hasVlans = childVlans.length > 0;
  1265. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1266. const canHaveVlan = supportsVLAN(parent);
  1267. const parentRow = document.createElement('tr');
  1268. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1269. parentRow.innerHTML = `
  1270. <td class="py-3 px-3 text-center">
  1271. ${hasVlans ? `
  1272. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1273. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1274. <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">
  1275. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1276. </svg>
  1277. </button>
  1278. ` : `
  1279. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1280. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1281. </div>
  1282. `}
  1283. </td>
  1284. <td class="py-3 px-4">
  1285. <div class="flex items-center space-x-2.5">
  1286. <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">
  1287. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1288. </div>
  1289. <div>
  1290. <div class="flex items-center gap-2">
  1291. <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'}">
  1292. <span>${parent.name}</span>
  1293. <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>
  1294. </span>
  1295. ${hasVlans ? `
  1296. <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>
  1297. ` : `
  1298. <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>
  1299. `}
  1300. </div>
  1301. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1302. </div>
  1303. </div>
  1304. </td>
  1305. <td class="py-3 px-4 font-sans">
  1306. <div class="flex items-center gap-1.5">
  1307. ${getRoleBadge(parent.role || 'LAN')}
  1308. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1309. </div>
  1310. </td>
  1311. <td class="py-3 px-4">
  1312. ${parent.ipv4 && parent.ipv4.length > 0
  1313. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1314. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1315. }
  1316. ${(() => {
  1317. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1318. if (!c) return '';
  1319. 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');
  1320. 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>`;
  1321. })()}
  1322. </td>
  1323. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1324. <div>${parent.mac || 'N/A'}</div>
  1325. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1326. </td>
  1327. <td class="py-3 px-4 text-[11px]">
  1328. <div class="flex items-center space-x-2">
  1329. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1330. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1331. </div>
  1332. </td>
  1333. <td class="py-3 px-4 font-sans">
  1334. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1335. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1336. 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'
  1337. }" title="Click to toggle link status">
  1338. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1339. <span>${parent.state}</span>
  1340. </button>
  1341. </td>
  1342. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1343. ${(() => {
  1344. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1345. if (c) {
  1346. 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>`;
  1347. }
  1348. if (!supportsDHCPClient(parent)) {
  1349. return '';
  1350. }
  1351. 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>`;
  1352. })()}
  1353. ${canHaveVlan ? `
  1354. <button onclick="openVlanModal('${parent.name}')"
  1355. 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">
  1356. + Add VLAN
  1357. </button>
  1358. ` : ''}
  1359. <button onclick="openIfaceModal('${parent.name}')"
  1360. 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">
  1361. Edit
  1362. </button>
  1363. </td>
  1364. `;
  1365. tbody.appendChild(parentRow);
  1366. if (isExpanded) {
  1367. const drawerRow = document.createElement('tr');
  1368. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1369. const drawerCell = document.createElement('td');
  1370. drawerCell.colSpan = 8;
  1371. drawerCell.className = 'p-0';
  1372. drawerCell.innerHTML = `
  1373. <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">
  1374. <div class="flex items-center justify-between mb-3">
  1375. <div class="flex items-center space-x-3">
  1376. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1377. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1378. </span>
  1379. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1380. ${childVlans.length} Attached
  1381. </span>
  1382. </div>
  1383. <button onclick="openVlanModal('${parent.name}')"
  1384. 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">
  1385. <span>+ Create VLAN on ${parent.name}</span>
  1386. </button>
  1387. </div>
  1388. ${childVlans.length === 0 ? `
  1389. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1390. <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>
  1391. <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">
  1392. <span>+ Create Your First VLAN on ${parent.name}</span>
  1393. </button>
  1394. </div>
  1395. ` : `
  1396. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1397. <table class="w-full text-left text-xs font-mono">
  1398. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1399. <tr>
  1400. <th class="py-2.5 px-4">VLAN ID</th>
  1401. <th class="py-2.5 px-4">Interface Device</th>
  1402. <th class="py-2.5 px-4">Subnet Gateway</th>
  1403. <th class="py-2.5 px-4">Role / Alias</th>
  1404. <th class="py-2.5 px-4">MTU</th>
  1405. <th class="py-2.5 px-4">Throughput</th>
  1406. <th class="py-2.5 px-4">Status</th>
  1407. <th class="py-2.5 px-4 text-right">Actions</th>
  1408. </tr>
  1409. </thead>
  1410. <tbody class="divide-y divide-slate-800/70">
  1411. ${childVlans.map(v => {
  1412. const isVlanUp = v.state === 'UP';
  1413. return `
  1414. <tr class="hover:bg-slate-800/40 transition">
  1415. <td class="py-2.5 px-4">
  1416. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1417. VLAN ${v.vlan_id}
  1418. </span>
  1419. </td>
  1420. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1421. <span class="text-cyan-500">└─</span>
  1422. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1423. <span>${v.name}</span>
  1424. <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>
  1425. </span>
  1426. </td>
  1427. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1428. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1429. ${(() => {
  1430. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1431. if (!c) return '';
  1432. 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';
  1433. 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>`;
  1434. })()}
  1435. </td>
  1436. <td class="py-2.5 px-4 font-sans text-slate-300">
  1437. <div class="flex items-center gap-1.5">
  1438. ${getRoleBadge(v.role || 'LAN')}
  1439. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1440. </div>
  1441. </td>
  1442. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1443. <td class="py-2.5 px-4 text-[11px]">
  1444. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1445. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1446. </td>
  1447. <td class="py-2.5 px-4 font-sans">
  1448. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1449. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1450. 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'
  1451. }">
  1452. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1453. <span>${v.state}</span>
  1454. </button>
  1455. </td>
  1456. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1457. ${(() => {
  1458. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1459. if (c) {
  1460. 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>`;
  1461. }
  1462. if (!supportsDHCPClient(v)) {
  1463. return '';
  1464. }
  1465. 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>`;
  1466. })()}
  1467. <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>
  1468. <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>
  1469. </td>
  1470. </tr>
  1471. `;
  1472. }).join('')}
  1473. </tbody>
  1474. </table>
  1475. </div>
  1476. `}
  1477. </div>
  1478. `;
  1479. drawerRow.appendChild(drawerCell);
  1480. tbody.appendChild(drawerRow);
  1481. }
  1482. });
  1483. }
  1484. // Render VLANs Dedicated View
  1485. function renderVlansList() {
  1486. const tbody = document.getElementById('vlans-table-body');
  1487. if (!tbody) return;
  1488. const emptyState = document.getElementById('vlans-empty-state');
  1489. const countBadge = document.getElementById('vlans-table-count');
  1490. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1491. const allVlans = state.vlans || [];
  1492. if (countBadge) countBadge.innerText = allVlans.length;
  1493. const filtered = allVlans.filter(v => {
  1494. if (!query) return true;
  1495. return v.name.toLowerCase().includes(query) ||
  1496. String(v.vlan_id).includes(query) ||
  1497. (v.description || '').toLowerCase().includes(query) ||
  1498. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1499. });
  1500. if (allVlans.length === 0) {
  1501. emptyState.classList.remove('hidden');
  1502. tbody.innerHTML = '';
  1503. return;
  1504. }
  1505. emptyState.classList.add('hidden');
  1506. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1507. if (tbody.dataset.sig === sig) return;
  1508. tbody.dataset.sig = sig;
  1509. tbody.innerHTML = '';
  1510. filtered.forEach(v => {
  1511. const isUp = v.state === 'UP';
  1512. const tr = document.createElement('tr');
  1513. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1514. tr.innerHTML = `
  1515. <td class="py-3 px-4">
  1516. <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">
  1517. VLAN ${v.vlan_id}
  1518. </span>
  1519. </td>
  1520. <td class="py-3 px-4 font-bold text-white">
  1521. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1522. <span>${v.name}</span>
  1523. <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>
  1524. </span>
  1525. </td>
  1526. <td class="py-3 px-4 text-slate-300">
  1527. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1528. </td>
  1529. <td class="py-3 px-4 text-emerald-400 font-medium">
  1530. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1531. </td>
  1532. <td class="py-3 px-4 text-slate-300 font-sans">
  1533. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1534. </td>
  1535. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1536. <td class="py-3 px-4 font-sans">
  1537. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1538. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1539. 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'
  1540. }">
  1541. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1542. <span>${v.state}</span>
  1543. </button>
  1544. </td>
  1545. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1546. <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>
  1547. <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>
  1548. </td>
  1549. `;
  1550. tbody.appendChild(tr);
  1551. });
  1552. }
  1553. // Toggle interface UP / DOWN
  1554. async function toggleInterfaceState(name, newState) {
  1555. try {
  1556. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1557. method: 'POST',
  1558. headers: { 'Content-Type': 'application/json' },
  1559. body: JSON.stringify({ state: newState })
  1560. });
  1561. const data = await res.json();
  1562. if (res.ok) {
  1563. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1564. fetchData(false);
  1565. } else {
  1566. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1567. }
  1568. } catch (err) {
  1569. showToast('Error', err.message, 'error');
  1570. }
  1571. }
  1572. // ---------------- MikroTik Flag & Utilities ----------------
  1573. function renderMikroTikFlag(running, disabled) {
  1574. if (running) {
  1575. 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>`;
  1576. }
  1577. if (disabled) {
  1578. 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>`;
  1579. }
  1580. 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>`;
  1581. }
  1582. function copyToClipboard(text, label = 'Text') {
  1583. navigator.clipboard.writeText(text).then(() => {
  1584. showToast('Copied', `${label} copied to clipboard`, 'success');
  1585. }).catch(() => {
  1586. prompt('Copy value:', text);
  1587. });
  1588. }
  1589. // ======================== PPP Profiles Shared Helper ========================
  1590. async function fetchPPPProfilesList() {
  1591. try {
  1592. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1593. if (res.ok) {
  1594. state.pppProfiles = await res.json();
  1595. }
  1596. } catch (err) {
  1597. console.error('Failed to load PPP profiles:', err);
  1598. }
  1599. }
  1600. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1601. const sel = document.getElementById(selectId);
  1602. if (!sel) return;
  1603. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1604. { name: 'default', use_encryption: 'no' },
  1605. { name: 'default-encryption', use_encryption: 'required' }
  1606. ];
  1607. sel.innerHTML = '';
  1608. profiles.forEach(p => {
  1609. const opt = document.createElement('option');
  1610. opt.value = p.name;
  1611. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1612. opt.innerText = `${p.name}${encBadge}`;
  1613. sel.appendChild(opt);
  1614. });
  1615. if (selectedVal) {
  1616. sel.value = selectedVal;
  1617. } else {
  1618. sel.value = defaultVal;
  1619. }
  1620. if (!sel.value && sel.options.length > 0) {
  1621. sel.selectedIndex = 0;
  1622. }
  1623. }
  1624. // ======================== PPPoE Multi-Instance ========================
  1625. async function loadPPPoE(populateInputs = true) {
  1626. try {
  1627. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1628. await fetchPPPProfilesList();
  1629. }
  1630. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1631. const list = await res.json();
  1632. state.pppoeList = Array.isArray(list) ? list : [];
  1633. const badge = document.getElementById('pppoe-count-badge');
  1634. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1635. const tbody = document.getElementById('pppoe-table-body');
  1636. const empty = document.getElementById('pppoe-empty');
  1637. if (!tbody) return;
  1638. tbody.innerHTML = '';
  1639. if (state.pppoeList.length === 0) {
  1640. if (empty) empty.classList.remove('hidden');
  1641. } else {
  1642. if (empty) empty.classList.add('hidden');
  1643. state.pppoeList.forEach(inst => {
  1644. const tr = document.createElement('tr');
  1645. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1646. tr.innerHTML = `
  1647. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1648. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1649. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1650. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1651. <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>
  1652. <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>
  1653. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1654. <td class="py-2.5 px-3 text-center">
  1655. <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'}">
  1656. ${inst.default_route ? 'Yes' : 'No'}
  1657. </span>
  1658. </td>
  1659. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1660. ${inst.running ? `
  1661. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1662. ` : `
  1663. <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>
  1664. `}
  1665. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1666. ${inst.disabled ? 'Enable' : 'Disable'}
  1667. </button>
  1668. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1669. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1670. </td>
  1671. `;
  1672. tbody.appendChild(tr);
  1673. });
  1674. }
  1675. } catch (err) {
  1676. console.error('Failed to load PPPoE:', err);
  1677. }
  1678. }
  1679. function openAddPPPoEModal() {
  1680. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1681. document.getElementById('pppoe-modal-edit-orig').value = '';
  1682. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1683. document.getElementById('pppoe-modal-name').readOnly = false;
  1684. document.getElementById('pppoe-modal-user').value = '';
  1685. document.getElementById('pppoe-modal-pass').value = '';
  1686. document.getElementById('pppoe-modal-service').value = '';
  1687. document.getElementById('pppoe-modal-mtu').value = '1492';
  1688. document.getElementById('pppoe-modal-defroute').checked = true;
  1689. document.getElementById('pppoe-modal-reconnect').checked = true;
  1690. document.getElementById('pppoe-modal-disabled').checked = false;
  1691. // Populate profiles
  1692. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1693. // Populate interfaces
  1694. const sel = document.getElementById('pppoe-modal-iface');
  1695. sel.innerHTML = '';
  1696. (state.interfaces || []).forEach(i => {
  1697. if (i.name === 'lo') return;
  1698. const opt = document.createElement('option');
  1699. opt.value = i.name;
  1700. opt.innerText = `${i.name} (${i.role || i.type})`;
  1701. sel.appendChild(opt);
  1702. });
  1703. document.getElementById('pppoe-modal').classList.remove('hidden');
  1704. }
  1705. function openEditPPPoEModal(name) {
  1706. const inst = (state.pppoeList || []).find(i => i.name === name);
  1707. if (!inst) return;
  1708. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1709. document.getElementById('pppoe-modal-edit-orig').value = name;
  1710. document.getElementById('pppoe-modal-name').value = inst.name;
  1711. document.getElementById('pppoe-modal-name').readOnly = true;
  1712. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1713. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1714. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1715. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1716. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1717. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1718. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1719. // Populate profiles
  1720. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1721. const sel = document.getElementById('pppoe-modal-iface');
  1722. sel.innerHTML = '';
  1723. (state.interfaces || []).forEach(i => {
  1724. if (i.name === 'lo') return;
  1725. const opt = document.createElement('option');
  1726. opt.value = i.name;
  1727. opt.innerText = `${i.name} (${i.role || i.type})`;
  1728. if (i.name === inst.interface) opt.selected = true;
  1729. sel.appendChild(opt);
  1730. });
  1731. document.getElementById('pppoe-modal').classList.remove('hidden');
  1732. }
  1733. function closePPPoEModal() {
  1734. document.getElementById('pppoe-modal').classList.add('hidden');
  1735. }
  1736. async function submitSavePPPoE(e) {
  1737. e.preventDefault();
  1738. const name = document.getElementById('pppoe-modal-name').value.trim();
  1739. const iface = document.getElementById('pppoe-modal-iface').value;
  1740. const user = document.getElementById('pppoe-modal-user').value.trim();
  1741. const pass = document.getElementById('pppoe-modal-pass').value;
  1742. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1743. const service = document.getElementById('pppoe-modal-service').value.trim();
  1744. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1745. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1746. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1747. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1748. try {
  1749. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1750. method: 'POST',
  1751. headers: { 'Content-Type': 'application/json' },
  1752. body: JSON.stringify({
  1753. name,
  1754. interface: iface,
  1755. username: user,
  1756. password: pass,
  1757. profile: profile,
  1758. service_name: service,
  1759. mtu,
  1760. default_route: defRoute,
  1761. auto_reconnect: reconnect,
  1762. disabled
  1763. })
  1764. });
  1765. if (res.ok) {
  1766. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1767. closePPPoEModal();
  1768. loadPPPoE(false);
  1769. fetchData(false);
  1770. } else {
  1771. const err = await res.json();
  1772. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1773. }
  1774. } catch (err) {
  1775. showToast('Error', err.message, 'error');
  1776. }
  1777. }
  1778. async function connectPPPoEInstance(name) {
  1779. try {
  1780. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1781. if (res.ok) {
  1782. showToast('Connecting', `Dialing ${name}...`, 'info');
  1783. setTimeout(() => loadPPPoE(false), 2000);
  1784. }
  1785. } catch (err) {
  1786. showToast('Error', err.message, 'error');
  1787. }
  1788. }
  1789. async function disconnectPPPoEInstance(name) {
  1790. try {
  1791. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1792. if (res.ok) {
  1793. showToast('Disconnected', `${name} session terminated`, 'info');
  1794. setTimeout(() => loadPPPoE(false), 1000);
  1795. }
  1796. } catch (err) {
  1797. showToast('Error', err.message, 'error');
  1798. }
  1799. }
  1800. async function togglePPPoEState(name, enable) {
  1801. try {
  1802. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1803. method: 'POST',
  1804. headers: { 'Content-Type': 'application/json' },
  1805. body: JSON.stringify({ enabled: enable })
  1806. });
  1807. if (res.ok) {
  1808. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1809. loadPPPoE(false);
  1810. }
  1811. } catch (err) {
  1812. showToast('Error', err.message, 'error');
  1813. }
  1814. }
  1815. async function deletePPPoEInstance(name) {
  1816. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1817. try {
  1818. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1819. if (res.ok) {
  1820. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1821. loadPPPoE(false);
  1822. fetchData(false);
  1823. }
  1824. } catch (err) {
  1825. showToast('Error', err.message, 'error');
  1826. }
  1827. }
  1828. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1829. state.wgSubTab = 'ifaces';
  1830. function switchWGSubTab(tab) {
  1831. state.wgSubTab = tab;
  1832. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1833. const peersPanel = document.getElementById('wg-subtab-peers');
  1834. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1835. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1836. if (tab === 'ifaces') {
  1837. ifacesPanel?.classList.remove('hidden');
  1838. peersPanel?.classList.add('hidden');
  1839. 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';
  1840. 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';
  1841. } else {
  1842. ifacesPanel?.classList.add('hidden');
  1843. peersPanel?.classList.remove('hidden');
  1844. 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';
  1845. 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';
  1846. renderWGPeers();
  1847. }
  1848. }
  1849. async function loadWireGuard(populateInputs = true) {
  1850. try {
  1851. const [ifacesRes, peersRes] = await Promise.all([
  1852. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1853. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1854. ]);
  1855. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1856. const peers = peersRes.ok ? await peersRes.json() : [];
  1857. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1858. state.wgPeers = Array.isArray(peers) ? peers : [];
  1859. // Badges
  1860. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1861. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1862. const peersCountBadge = document.getElementById('wg-peers-count');
  1863. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1864. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1865. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1866. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1867. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1868. // Render Interfaces
  1869. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1870. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1871. if (ifacesTbody) {
  1872. ifacesTbody.innerHTML = '';
  1873. if (state.wgInterfaces.length === 0) {
  1874. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1875. } else {
  1876. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1877. state.wgInterfaces.forEach(iface => {
  1878. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1879. const tr = document.createElement('tr');
  1880. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1881. tr.innerHTML = `
  1882. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1883. <td class="py-2.5 px-3">
  1884. <div class="flex items-center gap-1.5">
  1885. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1886. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1887. </div>
  1888. </td>
  1889. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1890. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1891. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1892. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1893. ${(iface.public_key || '').substring(0, 10)}... 📋
  1894. </span>
  1895. </td>
  1896. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1897. <td class="py-2.5 px-3 text-center">
  1898. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1899. </td>
  1900. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1901. ${iface.running ? `
  1902. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1903. ` : `
  1904. <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>
  1905. `}
  1906. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1907. ${iface.disabled ? 'Enable' : 'Disable'}
  1908. </button>
  1909. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1910. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1911. </td>
  1912. `;
  1913. ifacesTbody.appendChild(tr);
  1914. });
  1915. }
  1916. }
  1917. // Populate filter dropdown in peers tab
  1918. const filterSel = document.getElementById('wg-peers-filter-iface');
  1919. if (filterSel) {
  1920. const currentVal = filterSel.value;
  1921. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1922. state.wgInterfaces.forEach(i => {
  1923. const opt = document.createElement('option');
  1924. opt.value = i.name;
  1925. opt.innerText = i.name;
  1926. if (i.name === currentVal) opt.selected = true;
  1927. filterSel.appendChild(opt);
  1928. });
  1929. }
  1930. renderWGPeers();
  1931. } catch (err) {
  1932. console.error('Failed to load WireGuard:', err);
  1933. }
  1934. }
  1935. function formatWGPeerEndpoint(address, port) {
  1936. if (!address || address === '(none)') return '--';
  1937. let addr = address.trim();
  1938. let p = port || 0;
  1939. while (addr.includes(':') && !addr.startsWith('[')) {
  1940. const lastColon = addr.lastIndexOf(':');
  1941. const maybePort = addr.substring(lastColon + 1);
  1942. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1943. if (!p) p = parseInt(maybePort, 10);
  1944. addr = addr.substring(0, lastColon);
  1945. } else {
  1946. break;
  1947. }
  1948. }
  1949. return p ? `${addr}:${p}` : addr;
  1950. }
  1951. function renderWGPeers() {
  1952. const filterSel = document.getElementById('wg-peers-filter-iface');
  1953. const selectedIface = filterSel ? filterSel.value : '';
  1954. const tbody = document.getElementById('wg-peers-table-body');
  1955. const empty = document.getElementById('wg-peers-empty');
  1956. if (!tbody) return;
  1957. tbody.innerHTML = '';
  1958. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1959. if (filtered.length === 0) {
  1960. if (empty) empty.classList.remove('hidden');
  1961. } else {
  1962. if (empty) empty.classList.add('hidden');
  1963. filtered.forEach(p => {
  1964. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1965. const tr = document.createElement('tr');
  1966. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1967. tr.innerHTML = `
  1968. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1969. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1970. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1971. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1972. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1973. ${(p.public_key || '').substring(0, 10)}... 📋
  1974. </span>
  1975. </td>
  1976. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1977. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1978. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1979. <td class="py-2.5 px-3 font-mono text-[11px]">
  1980. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1981. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1982. </td>
  1983. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1984. <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">
  1985. ${p.disabled ? 'Enable' : 'Disable'}
  1986. </button>
  1987. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1988. <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>
  1989. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1990. </td>
  1991. `;
  1992. tbody.appendChild(tr);
  1993. });
  1994. }
  1995. }
  1996. function openAddWGInterfaceModal() {
  1997. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1998. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1999. const nameEl = document.getElementById('wg-iface-modal-name');
  2000. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  2001. nameEl.readOnly = false;
  2002. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  2003. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  2004. document.getElementById('wg-iface-modal-mtu').value = '1420';
  2005. document.getElementById('wg-iface-modal-comment').value = '';
  2006. document.getElementById('wg-iface-modal-pubkey').value = '';
  2007. document.getElementById('wg-iface-modal-privkey').value = '';
  2008. document.getElementById('wg-iface-modal-disabled').checked = false;
  2009. generateWGInterfaceKeys();
  2010. document.getElementById('wg-iface-modal').classList.remove('hidden');
  2011. }
  2012. function openEditWGInterfaceModal(name) {
  2013. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  2014. if (!iface) return;
  2015. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  2016. document.getElementById('wg-iface-modal-edit-orig').value = name;
  2017. const nameEl = document.getElementById('wg-iface-modal-name');
  2018. nameEl.value = iface.name;
  2019. nameEl.readOnly = false; // ALLOW RENAMING
  2020. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  2021. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  2022. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  2023. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  2024. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  2025. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  2026. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  2027. document.getElementById('wg-iface-modal').classList.remove('hidden');
  2028. }
  2029. function closeAddWGInterfaceModal() {
  2030. document.getElementById('wg-iface-modal').classList.add('hidden');
  2031. }
  2032. async function generateWGInterfaceKeys() {
  2033. try {
  2034. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2035. const keys = await res.json();
  2036. if (res.ok) {
  2037. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  2038. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  2039. }
  2040. } catch (err) {
  2041. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2042. }
  2043. }
  2044. async function onWGInterfacePrivKeyInput() {
  2045. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  2046. if (!privKey) return;
  2047. try {
  2048. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  2049. method: 'POST',
  2050. headers: { 'Content-Type': 'application/json' },
  2051. body: JSON.stringify({ private_key: privKey })
  2052. });
  2053. if (res.ok) {
  2054. const data = await res.json();
  2055. if (data.public_key) {
  2056. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  2057. }
  2058. }
  2059. } catch (err) {
  2060. // Ignore while typing
  2061. }
  2062. }
  2063. function toggleWGPrivKeyVisibility() {
  2064. const el = document.getElementById('wg-iface-modal-privkey');
  2065. const btn = document.getElementById('btn-toggle-wg-privkey');
  2066. if (el.type === 'password') {
  2067. el.type = 'text';
  2068. btn.innerText = '🙈 Hide';
  2069. } else {
  2070. el.type = 'password';
  2071. btn.innerText = '👁️ Show';
  2072. }
  2073. }
  2074. function copyWGInterfacePubKey() {
  2075. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  2076. if (pub) copyToClipboard(pub, 'Interface Public Key');
  2077. }
  2078. async function submitSaveWGInterface(e) {
  2079. e.preventDefault();
  2080. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  2081. const name = document.getElementById('wg-iface-modal-name').value.trim();
  2082. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  2083. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  2084. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  2085. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  2086. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  2087. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  2088. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  2089. try {
  2090. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  2091. method: 'POST',
  2092. headers: { 'Content-Type': 'application/json' },
  2093. body: JSON.stringify({
  2094. orig_name: origName,
  2095. name,
  2096. listen_port: port,
  2097. address: addr,
  2098. mtu,
  2099. comment,
  2100. public_key: pub,
  2101. private_key: priv,
  2102. disabled
  2103. })
  2104. });
  2105. const data = await res.json();
  2106. if (res.ok) {
  2107. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  2108. closeAddWGInterfaceModal();
  2109. loadWireGuard(false);
  2110. fetchData(false);
  2111. } else {
  2112. showToast('Error', data.error || 'Failed to save interface', 'error');
  2113. }
  2114. } catch (err) {
  2115. showToast('Error', err.message, 'error');
  2116. }
  2117. }
  2118. async function startWGInterface(name) {
  2119. try {
  2120. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2121. if (res.ok) {
  2122. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2123. loadWireGuard(false);
  2124. fetchData(false);
  2125. }
  2126. } catch (err) {
  2127. showToast('Error', err.message, 'error');
  2128. }
  2129. }
  2130. async function stopWGInterface(name) {
  2131. try {
  2132. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2133. if (res.ok) {
  2134. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2135. loadWireGuard(false);
  2136. fetchData(false);
  2137. }
  2138. } catch (err) {
  2139. showToast('Error', err.message, 'error');
  2140. }
  2141. }
  2142. async function toggleWGInterfaceState(name, enable) {
  2143. try {
  2144. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2145. method: 'POST',
  2146. headers: { 'Content-Type': 'application/json' },
  2147. body: JSON.stringify({ enabled: enable })
  2148. });
  2149. if (res.ok) {
  2150. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2151. loadWireGuard(false);
  2152. fetchData(false);
  2153. }
  2154. } catch (err) {
  2155. showToast('Error', err.message, 'error');
  2156. }
  2157. }
  2158. async function deleteWGInterface(name) {
  2159. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2160. try {
  2161. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2162. if (res.ok) {
  2163. showToast('Deleted', `Interface ${name} removed`, 'success');
  2164. loadWireGuard(false);
  2165. fetchData(false);
  2166. }
  2167. } catch (err) {
  2168. showToast('Error', err.message, 'error');
  2169. }
  2170. }
  2171. function populateWGPeerIfaceSelect(selectedIface = '') {
  2172. const sel = document.getElementById('wg-peer-modal-iface');
  2173. if (!sel) return;
  2174. sel.innerHTML = '';
  2175. (state.wgInterfaces || []).forEach(i => {
  2176. const opt = document.createElement('option');
  2177. opt.value = i.name;
  2178. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2179. if (i.name === selectedIface) opt.selected = true;
  2180. sel.appendChild(opt);
  2181. });
  2182. }
  2183. function openAddWGPeerModal() {
  2184. if ((state.wgInterfaces || []).length === 0) {
  2185. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2186. openAddWGInterfaceModal();
  2187. return;
  2188. }
  2189. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2190. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2191. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2192. populateWGPeerIfaceSelect();
  2193. document.getElementById('wg-peer-modal-name').value = '';
  2194. document.getElementById('wg-peer-modal-pubkey').value = '';
  2195. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2196. document.getElementById('wg-peer-modal-endpoint').value = '';
  2197. document.getElementById('wg-peer-modal-port').value = '';
  2198. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2199. document.getElementById('wg-peer-modal-preshared').value = '';
  2200. document.getElementById('wg-peer-modal-disabled').checked = false;
  2201. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2202. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2203. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2204. }
  2205. function openEditWGPeerModal(ifaceName, pubKey) {
  2206. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2207. if (!peer) {
  2208. showToast('Not Found', 'Peer not found', 'warning');
  2209. return;
  2210. }
  2211. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2212. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2213. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2214. populateWGPeerIfaceSelect(peer.interface);
  2215. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2216. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2217. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2218. let epHost = (peer.endpoint_address || '').trim();
  2219. let epPort = peer.endpoint_port || '';
  2220. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2221. const lastColon = epHost.lastIndexOf(':');
  2222. const maybePort = epHost.substring(lastColon + 1);
  2223. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2224. if (!epPort) epPort = parseInt(maybePort, 10);
  2225. epHost = epHost.substring(0, lastColon);
  2226. } else {
  2227. break;
  2228. }
  2229. }
  2230. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2231. document.getElementById('wg-peer-modal-port').value = epPort;
  2232. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2233. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2234. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2235. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2236. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2237. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2238. }
  2239. function closeAddWGPeerModal() {
  2240. document.getElementById('wg-peer-modal').classList.add('hidden');
  2241. }
  2242. async function generatePeerKeypairHelper() {
  2243. try {
  2244. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2245. const keys = await res.json();
  2246. if (res.ok) {
  2247. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2248. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2249. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2250. checkWGPeerKeyValidity();
  2251. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2252. }
  2253. } catch (err) {
  2254. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2255. }
  2256. }
  2257. function copyGeneratedPeerPrivKey() {
  2258. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2259. if (priv) copyToClipboard(priv, 'Client Private Key');
  2260. }
  2261. async function generatePeerPSK() {
  2262. try {
  2263. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2264. const keys = await res.json();
  2265. if (res.ok && keys.private_key) {
  2266. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2267. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2268. }
  2269. } catch (err) {
  2270. showToast('Error', err.message, 'error');
  2271. }
  2272. }
  2273. function checkWGPeerKeyValidity() {
  2274. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2275. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2276. const warningEl = document.getElementById('wg-peer-key-warning');
  2277. if (!warningEl) return;
  2278. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2279. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2280. warningEl.classList.remove('hidden');
  2281. } else {
  2282. warningEl.classList.add('hidden');
  2283. }
  2284. }
  2285. async function submitSaveWGPeer(e) {
  2286. e.preventDefault();
  2287. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2288. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2289. const iface = document.getElementById('wg-peer-modal-iface').value;
  2290. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2291. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2292. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2293. .split(',')
  2294. .map(s => s.trim())
  2295. .filter(s => s.length > 0);
  2296. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2297. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2298. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2299. const lastColon = epHost.lastIndexOf(':');
  2300. const maybePort = epHost.substring(lastColon + 1);
  2301. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2302. if (!epPort) epPort = parseInt(maybePort, 10);
  2303. epHost = epHost.substring(0, lastColon);
  2304. } else {
  2305. break;
  2306. }
  2307. }
  2308. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2309. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2310. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2311. // Validation
  2312. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2313. if (targetIface && targetIface.public_key === pub) {
  2314. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2315. return;
  2316. }
  2317. try {
  2318. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2319. method: 'POST',
  2320. headers: { 'Content-Type': 'application/json' },
  2321. body: JSON.stringify({
  2322. orig_interface: origIface,
  2323. orig_public_key: origPubKey,
  2324. interface: iface,
  2325. name,
  2326. public_key: pub,
  2327. allowed_ips: allowed,
  2328. endpoint_address: epHost,
  2329. endpoint_port: epPort,
  2330. persistent_keepalive: keepalive,
  2331. preshared_key: psk,
  2332. disabled
  2333. })
  2334. });
  2335. const data = await res.json();
  2336. if (res.ok) {
  2337. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2338. closeAddWGPeerModal();
  2339. loadWireGuard(false);
  2340. } else {
  2341. showToast('Error', data.error || 'Failed to save peer', 'error');
  2342. }
  2343. } catch (err) {
  2344. showToast('Error', err.message, 'error');
  2345. }
  2346. }
  2347. async function toggleWGPeerState(iface, pubkey, enable) {
  2348. try {
  2349. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2350. method: 'POST',
  2351. headers: { 'Content-Type': 'application/json' },
  2352. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2353. });
  2354. const data = await res.json();
  2355. if (res.ok) {
  2356. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2357. loadWireGuard(false);
  2358. } else {
  2359. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2360. }
  2361. } catch (err) {
  2362. showToast('Error', err.message, 'error');
  2363. }
  2364. }
  2365. async function deleteWGPeer(iface, pubkey) {
  2366. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2367. try {
  2368. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2369. method: 'POST',
  2370. headers: { 'Content-Type': 'application/json' },
  2371. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2372. });
  2373. const data = await res.json();
  2374. if (res.ok) {
  2375. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2376. loadWireGuard(false);
  2377. } else {
  2378. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2379. }
  2380. } catch (err) {
  2381. showToast('Error', err.message, 'error');
  2382. }
  2383. }
  2384. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2385. function switchIpsecModalTab(tab) {
  2386. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2387. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2388. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2389. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2390. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2391. if (tab === 'p1') {
  2392. if (p1Tab) {
  2393. 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';
  2394. }
  2395. if (p2Tab) {
  2396. 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';
  2397. }
  2398. if (p1Content) p1Content.classList.remove('hidden');
  2399. if (p2Content) p2Content.classList.add('hidden');
  2400. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2401. } else {
  2402. if (p1Tab) {
  2403. 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';
  2404. }
  2405. if (p2Tab) {
  2406. 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';
  2407. }
  2408. if (p1Content) p1Content.classList.add('hidden');
  2409. if (p2Content) p2Content.classList.remove('hidden');
  2410. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2411. }
  2412. }
  2413. function toggleIpsecPhaseStep() {
  2414. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2415. if (p1Content && !p1Content.classList.contains('hidden')) {
  2416. switchIpsecModalTab('p2');
  2417. } else {
  2418. switchIpsecModalTab('p1');
  2419. }
  2420. }
  2421. function toggleIpsecPskVisibility() {
  2422. const pskInput = document.getElementById('ipsec-modal-psk');
  2423. if (!pskInput) return;
  2424. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2425. }
  2426. function addIpsecLocalSubnet(val = '') {
  2427. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2428. if (!container) return;
  2429. const row = document.createElement('div');
  2430. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2431. row.innerHTML = `
  2432. <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">
  2433. <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>
  2434. `;
  2435. container.appendChild(row);
  2436. }
  2437. function addIpsecRemoteSubnet(val = '') {
  2438. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2439. if (!container) return;
  2440. const row = document.createElement('div');
  2441. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2442. row.innerHTML = `
  2443. <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">
  2444. <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>
  2445. `;
  2446. container.appendChild(row);
  2447. }
  2448. function updateIpsecEspProposalFromPFS(val) {
  2449. const prop = document.getElementById('ipsec-modal-espprop');
  2450. if (!prop) return;
  2451. if (val === 'none') {
  2452. prop.value = 'aes256-sha256,aes128-sha256,default';
  2453. } else {
  2454. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2455. }
  2456. }
  2457. function updateIpsecIkeProposalFromDH(dh) {
  2458. const el = document.getElementById('ipsec-modal-ikeprop');
  2459. if (el) {
  2460. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2461. }
  2462. }
  2463. function safeSetVal(id, val) {
  2464. const el = document.getElementById(id);
  2465. if (el) el.value = val;
  2466. }
  2467. function safeSetChecked(id, val) {
  2468. const el = document.getElementById(id);
  2469. if (el) el.checked = !!val;
  2470. }
  2471. function safeGetVal(id, def = '') {
  2472. const el = document.getElementById(id);
  2473. return el ? el.value : def;
  2474. }
  2475. async function loadIPSec(populateInputs = true) {
  2476. try {
  2477. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2478. const list = await res.json();
  2479. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2480. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2481. const badge = document.getElementById('ipsec-sas-badge');
  2482. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2483. const tbody = document.getElementById('ipsec-table-body');
  2484. const empty = document.getElementById('ipsec-empty');
  2485. if (!tbody) return;
  2486. tbody.innerHTML = '';
  2487. if (state.ipsecTunnels.length === 0) {
  2488. if (empty) empty.classList.remove('hidden');
  2489. } else {
  2490. if (empty) empty.classList.add('hidden');
  2491. state.ipsecTunnels.forEach(c => {
  2492. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2493. const tr = document.createElement('tr');
  2494. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2495. // Local subnets tags
  2496. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2497. 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('');
  2498. // Remote subnets tags
  2499. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2500. 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('');
  2501. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2502. const p2Name = c.phase2_name || `${c.name}_p2`;
  2503. tr.innerHTML = `
  2504. <td class="py-2.5 px-3 text-center">
  2505. ${isEstablished ? `
  2506. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2507. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2508. <span>UP</span>
  2509. </span>
  2510. ` : (c.disabled ? `
  2511. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2512. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2513. <span>DOWN</span>
  2514. </span>
  2515. ` : `
  2516. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2517. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2518. <span>IDLE</span>
  2519. </span>
  2520. `)}
  2521. </td>
  2522. <td class="py-2.5 px-4 font-bold text-white">
  2523. <div class="flex items-center gap-2">
  2524. <span class="text-amber-400">🛡</span>
  2525. <div>
  2526. <div>${escapeHtml(c.name)}</div>
  2527. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2528. </div>
  2529. </div>
  2530. </td>
  2531. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2532. <td class="py-2.5 px-4 font-sans">
  2533. <div class="flex items-center gap-1.5">
  2534. <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>
  2535. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2536. </div>
  2537. </td>
  2538. <td class="py-2.5 px-4">
  2539. <div class="space-y-1">
  2540. <div class="flex items-center flex-wrap gap-1">
  2541. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2542. ${localBadges}
  2543. </div>
  2544. <div class="flex items-center flex-wrap gap-1">
  2545. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2546. ${remoteBadges}
  2547. </div>
  2548. </div>
  2549. </td>
  2550. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2551. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2552. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2553. </div>
  2554. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2555. </td>
  2556. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2557. ${isEstablished ? `
  2558. <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>
  2559. ` : `
  2560. <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>
  2561. `}
  2562. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2563. ${c.disabled ? 'Enable' : 'Disable'}
  2564. </button>
  2565. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2566. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2567. </td>
  2568. `;
  2569. tbody.appendChild(tr);
  2570. });
  2571. }
  2572. } catch (err) {
  2573. console.error('Failed to load IPSec:', err);
  2574. }
  2575. }
  2576. function openAddIPSecModal() {
  2577. const modal = document.getElementById('ipsec-modal');
  2578. if (!modal) return;
  2579. const title = document.getElementById('ipsec-modal-title');
  2580. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2581. // Phase 1 Fields
  2582. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2583. const nameEl = document.getElementById('ipsec-modal-name');
  2584. if (nameEl) nameEl.readOnly = false;
  2585. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2586. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2587. safeSetVal('ipsec-modal-remotegw', '');
  2588. safeSetVal('ipsec-modal-localaddrs', '');
  2589. safeSetVal('ipsec-modal-comments', '');
  2590. safeSetVal('ipsec-modal-psk', '');
  2591. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2592. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2593. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2594. safeSetVal('ipsec-modal-localid', '');
  2595. safeSetVal('ipsec-modal-remoteid', '');
  2596. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2597. // Phase 2 Fields
  2598. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2599. safeSetVal('ipsec-modal-espkeylife', '28800');
  2600. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2601. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2602. safeSetChecked('ipsec-modal-autostart', true);
  2603. safeSetChecked('ipsec-modal-disabled', false);
  2604. // Clear & Populate default dynamic subnets
  2605. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2606. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2607. if (localContainer) {
  2608. localContainer.innerHTML = '';
  2609. addIpsecLocalSubnet('192.168.10.0/24');
  2610. }
  2611. if (remoteContainer) {
  2612. remoteContainer.innerHTML = '';
  2613. addIpsecRemoteSubnet('192.168.20.0/24');
  2614. }
  2615. switchIpsecModalTab('p1');
  2616. modal.classList.remove('hidden');
  2617. }
  2618. function openEditIPSecModal(name) {
  2619. const modal = document.getElementById('ipsec-modal');
  2620. if (!modal) return;
  2621. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2622. if (!conn) return;
  2623. const title = document.getElementById('ipsec-modal-title');
  2624. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2625. // Phase 1 Fields
  2626. safeSetVal('ipsec-modal-name', conn.name);
  2627. const nameEl = document.getElementById('ipsec-modal-name');
  2628. if (nameEl) nameEl.readOnly = true;
  2629. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2630. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2631. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2632. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2633. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2634. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2635. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2636. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2637. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2638. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2639. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2640. // Phase 2 Fields
  2641. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2642. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2643. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2644. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2645. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2646. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2647. // Populate dynamic subnets
  2648. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2649. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2650. if (localContainer) {
  2651. localContainer.innerHTML = '';
  2652. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2653. locals.forEach(s => addIpsecLocalSubnet(s));
  2654. }
  2655. if (remoteContainer) {
  2656. remoteContainer.innerHTML = '';
  2657. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2658. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2659. }
  2660. switchIpsecModalTab('p1');
  2661. modal.classList.remove('hidden');
  2662. }
  2663. function closeAddIPSecModal() {
  2664. const modal = document.getElementById('ipsec-modal');
  2665. if (modal) modal.classList.add('hidden');
  2666. }
  2667. async function submitSaveIPSec(e) {
  2668. if (e) e.preventDefault();
  2669. const name = safeGetVal('ipsec-modal-name').trim();
  2670. if (!name) {
  2671. showToast('Error', 'Tunnel name is required', 'error');
  2672. return;
  2673. }
  2674. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2675. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2676. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2677. const comments = safeGetVal('ipsec-modal-comments').trim();
  2678. const psk = safeGetVal('ipsec-modal-psk');
  2679. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2680. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2681. const localId = safeGetVal('ipsec-modal-localid').trim();
  2682. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2683. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2684. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2685. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2686. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2687. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2688. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2689. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2690. // Scrape dynamic local and remote subnets
  2691. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2692. const localSubnets = [];
  2693. localInputs.forEach(inp => {
  2694. const v = inp.value.trim();
  2695. if (v) localSubnets.push(v);
  2696. });
  2697. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2698. const remoteSubnets = [];
  2699. remoteInputs.forEach(inp => {
  2700. const v = inp.value.trim();
  2701. if (v) remoteSubnets.push(v);
  2702. });
  2703. try {
  2704. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2705. method: 'POST',
  2706. headers: { 'Content-Type': 'application/json' },
  2707. body: JSON.stringify({
  2708. name,
  2709. comment: comments,
  2710. ike_version: ikeVersion,
  2711. local_addrs: localAddrs,
  2712. remote_addrs: remotegw,
  2713. preshared_key: psk,
  2714. ike_proposals: ikeProposals,
  2715. ike_keylife: ikeKeylife,
  2716. local_id: localId,
  2717. remote_id: remoteId,
  2718. dpd: dpd,
  2719. phase2_name: phase2Name,
  2720. esp_proposals: espProposals,
  2721. esp_keylife: espKeylife,
  2722. pfs_group: pfsGroup,
  2723. pfs: pfsGroup !== 'none',
  2724. local_subnets: localSubnets,
  2725. remote_subnets: remoteSubnets,
  2726. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2727. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2728. auto_start: autostart,
  2729. disabled
  2730. })
  2731. });
  2732. if (res.ok) {
  2733. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2734. closeAddIPSecModal();
  2735. loadIPSec(false);
  2736. } else {
  2737. const err = await res.json();
  2738. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2739. }
  2740. } catch (err) {
  2741. showToast('Error', err.message, 'error');
  2742. }
  2743. }
  2744. async function startIPSecTunnel(name) {
  2745. try {
  2746. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2747. if (res.ok) {
  2748. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2749. setTimeout(() => loadIPSec(false), 2000);
  2750. }
  2751. } catch (err) {
  2752. showToast('Error', err.message, 'error');
  2753. }
  2754. }
  2755. async function stopIPSecTunnel(name) {
  2756. try {
  2757. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2758. if (res.ok) {
  2759. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2760. loadIPSec(false);
  2761. }
  2762. } catch (err) {
  2763. showToast('Error', err.message, 'error');
  2764. }
  2765. }
  2766. async function toggleIPSecState(name, enable) {
  2767. try {
  2768. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2769. method: 'POST',
  2770. headers: { 'Content-Type': 'application/json' },
  2771. body: JSON.stringify({ enabled: enable })
  2772. });
  2773. if (res.ok) {
  2774. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2775. loadIPSec(false);
  2776. }
  2777. } catch (err) {
  2778. showToast('Error', err.message, 'error');
  2779. }
  2780. }
  2781. async function deleteIPSecConn(name) {
  2782. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2783. try {
  2784. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2785. if (res.ok) {
  2786. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2787. loadIPSec(false);
  2788. fetchData(false);
  2789. }
  2790. } catch (err) {
  2791. showToast('Error', err.message, 'error');
  2792. }
  2793. }
  2794. // ======================== L2TP Multi-Instance ========================
  2795. async function loadL2TP(populateInputs = true) {
  2796. try {
  2797. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2798. await fetchPPPProfilesList();
  2799. }
  2800. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2801. const list = await res.json();
  2802. state.l2tpList = Array.isArray(list) ? list : [];
  2803. const badge = document.getElementById('l2tp-count-badge');
  2804. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2805. const tbody = document.getElementById('l2tp-table-body');
  2806. const empty = document.getElementById('l2tp-empty');
  2807. if (!tbody) return;
  2808. tbody.innerHTML = '';
  2809. if (state.l2tpList.length === 0) {
  2810. if (empty) empty.classList.remove('hidden');
  2811. } else {
  2812. if (empty) empty.classList.add('hidden');
  2813. state.l2tpList.forEach(inst => {
  2814. const tr = document.createElement('tr');
  2815. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2816. tr.innerHTML = `
  2817. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2818. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2819. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2820. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2821. <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>
  2822. <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>
  2823. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2824. <td class="py-2.5 px-3 text-center">
  2825. <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'}">
  2826. ${inst.default_route ? 'Yes' : 'No'}
  2827. </span>
  2828. </td>
  2829. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2830. ${inst.running ? `
  2831. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2832. ` : `
  2833. <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>
  2834. `}
  2835. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2836. ${inst.disabled ? 'Enable' : 'Disable'}
  2837. </button>
  2838. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2839. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2840. </td>
  2841. `;
  2842. tbody.appendChild(tr);
  2843. });
  2844. }
  2845. } catch (err) {
  2846. console.error('Failed to load L2TP:', err);
  2847. }
  2848. }
  2849. async function openAddL2TPModal() {
  2850. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2851. await fetchPPPProfilesList();
  2852. }
  2853. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2854. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2855. document.getElementById('l2tp-modal-name').readOnly = false;
  2856. document.getElementById('l2tp-modal-server').value = '';
  2857. document.getElementById('l2tp-modal-user').value = '';
  2858. document.getElementById('l2tp-modal-pass').value = '';
  2859. document.getElementById('l2tp-modal-ipsec').value = '';
  2860. document.getElementById('l2tp-modal-defroute').checked = true;
  2861. document.getElementById('l2tp-modal-disabled').checked = false;
  2862. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2863. document.getElementById('l2tp-modal').classList.remove('hidden');
  2864. }
  2865. async function openEditL2TPModal(name) {
  2866. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2867. await fetchPPPProfilesList();
  2868. }
  2869. const inst = (state.l2tpList || []).find(i => i.name === name);
  2870. if (!inst) return;
  2871. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2872. document.getElementById('l2tp-modal-name').value = inst.name;
  2873. document.getElementById('l2tp-modal-name').readOnly = true;
  2874. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2875. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2876. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2877. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2878. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2879. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2880. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2881. document.getElementById('l2tp-modal').classList.remove('hidden');
  2882. }
  2883. function closeL2TPModal() {
  2884. document.getElementById('l2tp-modal').classList.add('hidden');
  2885. }
  2886. async function submitSaveL2TP(e) {
  2887. e.preventDefault();
  2888. const name = document.getElementById('l2tp-modal-name').value.trim();
  2889. const server = document.getElementById('l2tp-modal-server').value.trim();
  2890. const user = document.getElementById('l2tp-modal-user').value.trim();
  2891. const pass = document.getElementById('l2tp-modal-pass').value;
  2892. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2893. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2894. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2895. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2896. try {
  2897. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2898. method: 'POST',
  2899. headers: { 'Content-Type': 'application/json' },
  2900. body: JSON.stringify({
  2901. name,
  2902. connect_to: server,
  2903. username: user,
  2904. password: pass,
  2905. profile: profile,
  2906. ipsec_secret: ipsec,
  2907. default_route: defRoute,
  2908. disabled
  2909. })
  2910. });
  2911. if (res.ok) {
  2912. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2913. closeL2TPModal();
  2914. loadL2TP(false);
  2915. fetchData(false);
  2916. }
  2917. } catch (err) {
  2918. showToast('Error', err.message, 'error');
  2919. }
  2920. }
  2921. async function connectL2TPInstance(name) {
  2922. try {
  2923. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2924. if (res.ok) {
  2925. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2926. setTimeout(() => loadL2TP(false), 2000);
  2927. }
  2928. } catch (err) {
  2929. showToast('Error', err.message, 'error');
  2930. }
  2931. }
  2932. async function disconnectL2TPInstance(name) {
  2933. try {
  2934. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2935. if (res.ok) {
  2936. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2937. loadL2TP(false);
  2938. }
  2939. } catch (err) {
  2940. showToast('Error', err.message, 'error');
  2941. }
  2942. }
  2943. async function toggleL2TPState(name, enable) {
  2944. try {
  2945. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2946. method: 'POST',
  2947. headers: { 'Content-Type': 'application/json' },
  2948. body: JSON.stringify({ enabled: enable })
  2949. });
  2950. if (res.ok) {
  2951. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2952. loadL2TP(false);
  2953. }
  2954. } catch (err) {
  2955. showToast('Error', err.message, 'error');
  2956. }
  2957. }
  2958. async function deleteL2TPInstance(name) {
  2959. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2960. try {
  2961. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2962. if (res.ok) {
  2963. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2964. loadL2TP(false);
  2965. fetchData(false);
  2966. }
  2967. } catch (err) {
  2968. showToast('Error', err.message, 'error');
  2969. }
  2970. }
  2971. // ======================== PPTP Multi-Instance ========================
  2972. async function loadPPTP(populateInputs = true) {
  2973. try {
  2974. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2975. await fetchPPPProfilesList();
  2976. }
  2977. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2978. const list = await res.json();
  2979. state.pptpList = Array.isArray(list) ? list : [];
  2980. const badge = document.getElementById('pptp-count-badge');
  2981. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2982. const tbody = document.getElementById('pptp-table-body');
  2983. const empty = document.getElementById('pptp-empty');
  2984. if (!tbody) return;
  2985. tbody.innerHTML = '';
  2986. if (state.pptpList.length === 0) {
  2987. if (empty) empty.classList.remove('hidden');
  2988. } else {
  2989. if (empty) empty.classList.add('hidden');
  2990. state.pptpList.forEach(inst => {
  2991. const tr = document.createElement('tr');
  2992. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2993. tr.innerHTML = `
  2994. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2995. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2996. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2997. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2998. <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>
  2999. <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>
  3000. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  3001. <td class="py-2.5 px-3 text-center">
  3002. <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'}">
  3003. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  3004. </span>
  3005. </td>
  3006. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  3007. ${inst.running ? `
  3008. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  3009. ` : `
  3010. <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>
  3011. `}
  3012. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  3013. ${inst.disabled ? 'Enable' : 'Disable'}
  3014. </button>
  3015. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3016. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3017. </td>
  3018. `;
  3019. tbody.appendChild(tr);
  3020. });
  3021. }
  3022. } catch (err) {
  3023. console.error('Failed to load PPTP:', err);
  3024. }
  3025. }
  3026. async function openAddPPTPModal() {
  3027. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  3028. await fetchPPPProfilesList();
  3029. }
  3030. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  3031. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  3032. document.getElementById('pptp-modal-name').readOnly = false;
  3033. document.getElementById('pptp-modal-server').value = '';
  3034. document.getElementById('pptp-modal-user').value = '';
  3035. document.getElementById('pptp-modal-pass').value = '';
  3036. document.getElementById('pptp-modal-mppe').checked = true;
  3037. document.getElementById('pptp-modal-defroute').checked = true;
  3038. document.getElementById('pptp-modal-disabled').checked = false;
  3039. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  3040. document.getElementById('pptp-modal').classList.remove('hidden');
  3041. }
  3042. async function openEditPPTPModal(name) {
  3043. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  3044. await fetchPPPProfilesList();
  3045. }
  3046. const inst = (state.pptpList || []).find(i => i.name === name);
  3047. if (!inst) return;
  3048. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  3049. document.getElementById('pptp-modal-name').value = inst.name;
  3050. document.getElementById('pptp-modal-name').readOnly = true;
  3051. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  3052. document.getElementById('pptp-modal-user').value = inst.username || '';
  3053. document.getElementById('pptp-modal-pass').value = inst.password || '';
  3054. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  3055. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  3056. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  3057. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  3058. document.getElementById('pptp-modal').classList.remove('hidden');
  3059. }
  3060. function closePPTPModal() {
  3061. document.getElementById('pptp-modal').classList.add('hidden');
  3062. }
  3063. async function submitSavePPTP(e) {
  3064. e.preventDefault();
  3065. const name = document.getElementById('pptp-modal-name').value.trim();
  3066. const server = document.getElementById('pptp-modal-server').value.trim();
  3067. const user = document.getElementById('pptp-modal-user').value.trim();
  3068. const pass = document.getElementById('pptp-modal-pass').value;
  3069. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  3070. const mppe = document.getElementById('pptp-modal-mppe').checked;
  3071. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  3072. const disabled = document.getElementById('pptp-modal-disabled').checked;
  3073. try {
  3074. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  3075. method: 'POST',
  3076. headers: { 'Content-Type': 'application/json' },
  3077. body: JSON.stringify({
  3078. name,
  3079. connect_to: server,
  3080. username: user,
  3081. password: pass,
  3082. profile: profile,
  3083. require_mppe: mppe,
  3084. default_route: defRoute,
  3085. auto_reconnect: true,
  3086. disabled
  3087. })
  3088. });
  3089. if (res.ok) {
  3090. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  3091. closePPTPModal();
  3092. loadPPTP(false);
  3093. fetchData(false);
  3094. }
  3095. } catch (err) {
  3096. showToast('Error', err.message, 'error');
  3097. }
  3098. }
  3099. async function connectPPTPInstance(name) {
  3100. try {
  3101. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  3102. if (res.ok) {
  3103. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  3104. setTimeout(() => loadPPTP(false), 2000);
  3105. }
  3106. } catch (err) {
  3107. showToast('Error', err.message, 'error');
  3108. }
  3109. }
  3110. async function disconnectPPTPInstance(name) {
  3111. try {
  3112. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3113. if (res.ok) {
  3114. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3115. loadPPTP(false);
  3116. }
  3117. } catch (err) {
  3118. showToast('Error', err.message, 'error');
  3119. }
  3120. }
  3121. async function togglePPTPState(name, enable) {
  3122. try {
  3123. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3124. method: 'POST',
  3125. headers: { 'Content-Type': 'application/json' },
  3126. body: JSON.stringify({ enabled: enable })
  3127. });
  3128. if (res.ok) {
  3129. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3130. loadPPTP(false);
  3131. }
  3132. } catch (err) {
  3133. showToast('Error', err.message, 'error');
  3134. }
  3135. }
  3136. async function deletePPTPInstance(name) {
  3137. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3138. try {
  3139. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3140. if (res.ok) {
  3141. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3142. loadPPTP(false);
  3143. fetchData(false);
  3144. }
  3145. } catch (err) {
  3146. showToast('Error', err.message, 'error');
  3147. }
  3148. }
  3149. // ---------------- Modal & Helper Functions ----------------
  3150. function openVlanModal(defaultParent = '') {
  3151. const select = document.getElementById('vlan-parent');
  3152. select.innerHTML = '';
  3153. const allIfaces = state.interfaces || [];
  3154. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3155. if (eligible.length === 0) {
  3156. const opt = document.createElement('option');
  3157. opt.value = '';
  3158. opt.innerText = 'No VLAN-capable interfaces available';
  3159. select.appendChild(opt);
  3160. } else {
  3161. eligible.forEach(i => {
  3162. const opt = document.createElement('option');
  3163. opt.value = i.name;
  3164. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3165. if (i.name === defaultParent) opt.selected = true;
  3166. select.appendChild(opt);
  3167. });
  3168. }
  3169. document.getElementById('vlan-id').value = '';
  3170. document.getElementById('vlan-name').value = '';
  3171. document.getElementById('vlan-ip').value = '';
  3172. document.getElementById('vlan-desc').value = '';
  3173. populateRoleSelects('LAN');
  3174. autoSuggestVlanName();
  3175. document.getElementById('vlan-modal').classList.remove('hidden');
  3176. }
  3177. function closeVlanModal() {
  3178. document.getElementById('vlan-modal').classList.add('hidden');
  3179. }
  3180. function autoSuggestVlanName() {
  3181. const parent = document.getElementById('vlan-parent').value;
  3182. if (!parent) return;
  3183. const id = document.getElementById('vlan-id').value;
  3184. const nameInput = document.getElementById('vlan-name');
  3185. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3186. }
  3187. function setSubnetPreset(cidr) {
  3188. const ipInput = document.getElementById('vlan-ip');
  3189. const id = document.getElementById('vlan-id').value || '10';
  3190. ipInput.value = `192.168.${id}.1${cidr}`;
  3191. }
  3192. async function submitCreateVlan(e) {
  3193. e.preventDefault();
  3194. const btn = document.getElementById('vlan-submit-btn');
  3195. btn.disabled = true;
  3196. btn.innerText = 'Creating...';
  3197. const parent = document.getElementById('vlan-parent').value;
  3198. if (!parent) {
  3199. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3200. btn.disabled = false;
  3201. btn.innerText = 'Create VLAN';
  3202. return;
  3203. }
  3204. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3205. const name = document.getElementById('vlan-name').value.trim();
  3206. const ip = document.getElementById('vlan-ip').value.trim();
  3207. const role = document.getElementById('vlan-role').value;
  3208. const desc = document.getElementById('vlan-desc').value.trim();
  3209. try {
  3210. const res = await fetch(`${API_BASE}/vlans`, {
  3211. method: 'POST',
  3212. headers: { 'Content-Type': 'application/json' },
  3213. body: JSON.stringify({
  3214. parent_name: parent,
  3215. vlan_id: id,
  3216. name: name,
  3217. ip_address: ip,
  3218. role: role,
  3219. description: desc,
  3220. mtu: 1500,
  3221. auto_up: true
  3222. })
  3223. });
  3224. const data = await res.json();
  3225. if (res.ok) {
  3226. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3227. state.expandedParents.add(parent);
  3228. closeVlanModal();
  3229. await fetchData(true);
  3230. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3231. } else {
  3232. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3233. }
  3234. } catch (err) {
  3235. showToast('Error', err.message, 'error');
  3236. } finally {
  3237. btn.disabled = false;
  3238. btn.innerText = 'Create VLAN';
  3239. }
  3240. }
  3241. async function confirmDeleteVlan(name) {
  3242. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3243. try {
  3244. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3245. if (res.ok) {
  3246. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3247. closeIfaceModal();
  3248. fetchData(true);
  3249. }
  3250. } catch (err) {
  3251. showToast('Error', err.message, 'error');
  3252. }
  3253. }
  3254. function openIfaceModal(name) {
  3255. const iface = (state.interfaces || []).find(i => i.name === name);
  3256. if (!iface) return;
  3257. state.currentModalIface = iface.name;
  3258. document.getElementById('modal-iface-name').innerText = iface.name;
  3259. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3260. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3261. populateRoleSelects(iface.role || 'LAN');
  3262. document.getElementById('modal-iface-desc').value = iface.description || '';
  3263. const nameInput = document.getElementById('modal-iface-new-name');
  3264. const renameBtn = document.getElementById('modal-btn-rename');
  3265. const renameHelp = document.getElementById('modal-iface-rename-help');
  3266. if (nameInput) {
  3267. nameInput.value = iface.name;
  3268. if (iface.name === 'lo' || iface.type === 'loopback') {
  3269. nameInput.disabled = true;
  3270. if (renameBtn) renameBtn.disabled = true;
  3271. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3272. } else {
  3273. nameInput.disabled = false;
  3274. if (renameBtn) renameBtn.disabled = false;
  3275. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3276. }
  3277. }
  3278. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3279. if (iface.is_vlan) {
  3280. delBtn.classList.remove('hidden');
  3281. } else {
  3282. delBtn.classList.add('hidden');
  3283. }
  3284. renderModalIPs(iface);
  3285. document.getElementById('iface-modal').classList.remove('hidden');
  3286. }
  3287. function renderModalIPs(iface) {
  3288. const container = document.getElementById('modal-ip-list');
  3289. container.innerHTML = '';
  3290. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3291. if (addrs.length === 0) {
  3292. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3293. return;
  3294. }
  3295. addrs.forEach(addr => {
  3296. const row = document.createElement('div');
  3297. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3298. row.innerHTML = `
  3299. <span class="text-white">${addr}</span>
  3300. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3301. `;
  3302. container.appendChild(row);
  3303. });
  3304. }
  3305. function closeIfaceModal() {
  3306. document.getElementById('iface-modal').classList.add('hidden');
  3307. state.currentModalIface = null;
  3308. }
  3309. async function setIfaceState(name, newState) {
  3310. const target = name || state.currentModalIface;
  3311. if (!target) return;
  3312. await toggleInterfaceState(target, newState);
  3313. const updated = (state.interfaces || []).find(i => i.name === target);
  3314. if (updated) openIfaceModal(target);
  3315. }
  3316. async function applyMTU() {
  3317. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3318. try {
  3319. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3320. method: 'POST',
  3321. headers: { 'Content-Type': 'application/json' },
  3322. body: JSON.stringify({ mtu })
  3323. });
  3324. if (res.ok) {
  3325. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3326. fetchData(false);
  3327. }
  3328. } catch (err) {
  3329. showToast('Error', err.message, 'error');
  3330. }
  3331. }
  3332. async function addInterfaceIP() {
  3333. const ip = document.getElementById('modal-new-ip').value.trim();
  3334. if (!ip) return;
  3335. try {
  3336. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3337. method: 'POST',
  3338. headers: { 'Content-Type': 'application/json' },
  3339. body: JSON.stringify({ ip })
  3340. });
  3341. if (res.ok) {
  3342. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3343. document.getElementById('modal-new-ip').value = '';
  3344. await fetchData(false);
  3345. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3346. if (iface) renderModalIPs(iface);
  3347. } else {
  3348. const err = await res.json();
  3349. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3350. }
  3351. } catch (err) {
  3352. showToast('Error', err.message, 'error');
  3353. }
  3354. }
  3355. async function removeInterfaceIP(ip) {
  3356. if (!confirm(`Remove IP ${ip}?`)) return;
  3357. try {
  3358. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3359. method: 'DELETE',
  3360. headers: { 'Content-Type': 'application/json' },
  3361. body: JSON.stringify({ ip })
  3362. });
  3363. if (res.ok) {
  3364. showToast('IP Removed', `Removed ${ip}`, 'success');
  3365. await fetchData(false);
  3366. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3367. if (iface) renderModalIPs(iface);
  3368. }
  3369. } catch (err) {
  3370. showToast('Error', err.message, 'error');
  3371. }
  3372. }
  3373. async function renameInterface() {
  3374. const oldName = state.currentModalIface;
  3375. const newNameInput = document.getElementById('modal-iface-new-name');
  3376. const newName = (newNameInput?.value || '').trim();
  3377. if (!oldName) return;
  3378. if (!newName) {
  3379. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3380. return;
  3381. }
  3382. if (newName === oldName) {
  3383. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3384. return;
  3385. }
  3386. if (newName.length > 15) {
  3387. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3388. return;
  3389. }
  3390. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3391. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3392. return;
  3393. }
  3394. const renameBtn = document.getElementById('modal-btn-rename');
  3395. if (renameBtn) {
  3396. renameBtn.disabled = true;
  3397. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3398. }
  3399. try {
  3400. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3401. method: 'POST',
  3402. headers: { 'Content-Type': 'application/json' },
  3403. body: JSON.stringify({ new_name: newName })
  3404. });
  3405. const data = await res.json();
  3406. if (!res.ok) {
  3407. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3408. return;
  3409. }
  3410. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3411. state.currentModalIface = newName;
  3412. document.getElementById('modal-iface-name').innerText = newName;
  3413. // Refresh application state
  3414. await fetchData(false);
  3415. const updated = (state.interfaces || []).find(i => i.name === newName);
  3416. if (updated) {
  3417. openIfaceModal(newName);
  3418. } else {
  3419. closeIfaceModal();
  3420. }
  3421. } catch (err) {
  3422. showToast('Error', err.message, 'error');
  3423. } finally {
  3424. if (renameBtn) {
  3425. renameBtn.disabled = false;
  3426. renameBtn.innerHTML = `
  3427. <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>
  3428. <span>Rename</span>
  3429. `;
  3430. }
  3431. }
  3432. }
  3433. async function saveInterfaceMetadata() {
  3434. const oldName = state.currentModalIface;
  3435. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3436. const role = document.getElementById('modal-iface-role').value;
  3437. const desc = document.getElementById('modal-iface-desc').value.trim();
  3438. let targetName = oldName;
  3439. // If user changed the name before clicking Save Changes, execute rename first
  3440. if (newName && newName !== oldName && oldName !== 'lo') {
  3441. try {
  3442. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3443. method: 'POST',
  3444. headers: { 'Content-Type': 'application/json' },
  3445. body: JSON.stringify({ new_name: newName })
  3446. });
  3447. const data = await renameRes.json();
  3448. if (!renameRes.ok) {
  3449. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3450. return;
  3451. }
  3452. targetName = newName;
  3453. state.currentModalIface = newName;
  3454. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3455. } catch (err) {
  3456. showToast('Error', err.message, 'error');
  3457. return;
  3458. }
  3459. }
  3460. try {
  3461. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3462. method: 'POST',
  3463. headers: { 'Content-Type': 'application/json' },
  3464. body: JSON.stringify({ role, description: desc })
  3465. });
  3466. if (res.ok) {
  3467. showToast('Saved', 'Interface configuration updated', 'success');
  3468. closeIfaceModal();
  3469. fetchData(false);
  3470. } else {
  3471. const err = await res.json();
  3472. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3473. }
  3474. } catch (err) {
  3475. showToast('Error', err.message, 'error');
  3476. }
  3477. }
  3478. // ======================== IPTABLES FIREWALL ========================
  3479. state.fwSubTab = 'filter';
  3480. state.routesSubTab = 'routes';
  3481. function nativeNATChain(chain) {
  3482. const value = (chain || '').toLowerCase();
  3483. if (value === 'dstnat') return 'prerouting';
  3484. if (value === 'srcnat') return 'postrouting';
  3485. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3486. }
  3487. function nativeFirewallTarget(action) {
  3488. const name = (action || '').toLowerCase();
  3489. 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();
  3490. }
  3491. function renderRuleFlag(disabled, hasComment) {
  3492. let flags = '';
  3493. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3494. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3495. return flags || '<span class="text-slate-600">-</span>';
  3496. }
  3497. function renderActionBadge(action) {
  3498. const act = (action || '').toLowerCase();
  3499. let color = 'bg-slate-800 text-slate-300';
  3500. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3501. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3502. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3503. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3504. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3505. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3506. }
  3507. function switchFWSubTab(tab) {
  3508. state.fwSubTab = tab;
  3509. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3510. tabs.forEach(t => {
  3511. const panel = document.getElementById(`fw-subtab-${t}`);
  3512. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3513. if (panel) {
  3514. if (t === tab) panel.classList.remove('hidden');
  3515. else panel.classList.add('hidden');
  3516. }
  3517. if (btn) {
  3518. if (t === tab) {
  3519. 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';
  3520. } else {
  3521. 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';
  3522. }
  3523. }
  3524. });
  3525. const addBtn = document.getElementById('fw-primary-add-btn');
  3526. if (addBtn) {
  3527. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3528. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3529. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3530. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3531. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3532. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3533. }
  3534. if (tab === 'filter') renderFilterRules();
  3535. else if (tab === 'nat') renderNATRules();
  3536. else if (tab === 'mangle') renderMangleRules();
  3537. else if (tab === 'addrlist') renderAddressLists();
  3538. else if (tab === 'geo') loadGeoIP();
  3539. else if (tab === 'connections') loadConnections();
  3540. setTimeout(initTableSorting, 50);
  3541. }
  3542. function openCurrentFWModal() {
  3543. if (state.fwSubTab === 'filter') openAddFilterModal();
  3544. else if (state.fwSubTab === 'nat') openAddNATModal();
  3545. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3546. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3547. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3548. else if (state.fwSubTab === 'connections') loadConnections();
  3549. }
  3550. async function loadFirewall(populateDropdowns = true) {
  3551. try {
  3552. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3553. fetch(`${API_BASE}/firewall/summary`),
  3554. fetch(`${API_BASE}/firewall/filter`),
  3555. fetch(`${API_BASE}/firewall/nat`),
  3556. fetch(`${API_BASE}/firewall/mangle`),
  3557. fetch(`${API_BASE}/firewall/address-lists`),
  3558. fetch(`${API_BASE}/firewall/geoip/status`),
  3559. fetch(`${API_BASE}/firewall/geoip/countries`)
  3560. ]);
  3561. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3562. const applyError = document.getElementById('fw-apply-error');
  3563. if (applyError) {
  3564. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3565. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3566. }
  3567. if (filterRes.ok) state.filterRules = await filterRes.json();
  3568. if (natRes.ok) state.natRules = await natRes.json();
  3569. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3570. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3571. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3572. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3573. 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); }
  3574. // Badges
  3575. const bFilter = document.getElementById('fw-badge-filter');
  3576. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3577. const bNat = document.getElementById('fw-badge-nat');
  3578. if (bNat) bNat.innerText = (state.natRules || []).length;
  3579. const bMangle = document.getElementById('fw-badge-mangle');
  3580. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3581. const bAddr = document.getElementById('fw-badge-addrlist');
  3582. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3583. const bGeo = document.getElementById('fw-badge-geo');
  3584. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3585. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3586. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3587. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3588. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3589. const tbodyFilter = document.getElementById('filter-table-body');
  3590. if (tbodyFilter) {
  3591. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3592. tbodyFilter.dataset.sig = sigFilter;
  3593. renderFilterRules();
  3594. } else {
  3595. // In-place live stats update (ZERO flicker)
  3596. (state.filterRules || []).forEach(r => {
  3597. const p = document.getElementById(`filter-pkts-${r.id}`);
  3598. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3599. const b = document.getElementById(`filter-bytes-${r.id}`);
  3600. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3601. });
  3602. }
  3603. }
  3604. const tbodyNat = document.getElementById('nat-table-body');
  3605. if (tbodyNat) {
  3606. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3607. tbodyNat.dataset.sig = sigNat;
  3608. renderNATRules();
  3609. } else {
  3610. (state.natRules || []).forEach(r => {
  3611. const p = document.getElementById(`nat-pkts-${r.id}`);
  3612. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3613. const b = document.getElementById(`nat-bytes-${r.id}`);
  3614. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3615. });
  3616. }
  3617. }
  3618. const tbodyMangle = document.getElementById('mangle-table-body');
  3619. if (tbodyMangle) {
  3620. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3621. tbodyMangle.dataset.sig = sigMangle;
  3622. renderMangleRules();
  3623. } else {
  3624. (state.mangleRules || []).forEach(r => {
  3625. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3626. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3627. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3628. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3629. });
  3630. }
  3631. }
  3632. const tbodyAddr = document.getElementById('addrlist-table-body');
  3633. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3634. tbodyAddr.dataset.sig = sigAddr;
  3635. renderAddressLists();
  3636. }
  3637. renderGeoCountries();
  3638. if (state.fwSubTab === 'connections') {
  3639. loadConnections();
  3640. }
  3641. } catch (err) {
  3642. console.error('Failed to load firewall:', err);
  3643. }
  3644. }
  3645. // ----------------- Filter Rules -----------------
  3646. function renderFilterRules() {
  3647. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3648. const tbody = document.getElementById('filter-table-body');
  3649. const empty = document.getElementById('filter-empty');
  3650. if (!tbody) return;
  3651. tbody.innerHTML = '';
  3652. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3653. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3654. if (rules.length === 0) {
  3655. empty?.classList.remove('hidden');
  3656. return;
  3657. }
  3658. empty?.classList.add('hidden');
  3659. rules.forEach((raw, idx) => {
  3660. const r = safeFirewallRow(raw);
  3661. const tr = document.createElement('tr');
  3662. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3663. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3664. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3665. let actionExtra = '';
  3666. if (r.action === 'reject') {
  3667. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3668. } else if (r.action === 'jump') {
  3669. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3670. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3671. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3672. } else if (r.action === 'log' && r.log_prefix) {
  3673. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3674. }
  3675. tr.innerHTML = `
  3676. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3677. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3678. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3679. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3680. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3681. <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>
  3682. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3683. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3684. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3685. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3686. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3687. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3688. </td>
  3689. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3690. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3691. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3692. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3693. <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>
  3694. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3695. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3696. </td>
  3697. `;
  3698. tbody.appendChild(tr);
  3699. });
  3700. }
  3701. function formatTarget(addr, list, geo) {
  3702. const parts = [];
  3703. if (addr) parts.push(`<span>${addr}</span>`);
  3704. if (list) {
  3705. const inv = list.startsWith('!') ? '!' : '';
  3706. const clean = list.replace(/^!/, '');
  3707. 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>`);
  3708. }
  3709. if (geo) {
  3710. const inv = geo.startsWith('!') ? '!' : '';
  3711. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3712. 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>`);
  3713. }
  3714. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3715. return parts.join(' ');
  3716. }
  3717. function populateInterfaceSelect(selectId, currentVal = '') {
  3718. const sel = document.getElementById(selectId);
  3719. if (!sel) return;
  3720. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3721. const sdwanNames = new Set((state.sdwanGroups || []).map(g => g.name));
  3722. (state.interfaces || []).filter(i => !sdwanNames.has(i.name)).forEach(i => {
  3723. const opt = document.createElement('option');
  3724. opt.value = i.name;
  3725. opt.innerText = `${i.name} (${i.role || i.type})`;
  3726. if (i.name === currentVal) opt.selected = true;
  3727. sel.appendChild(opt);
  3728. });
  3729. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3730. const optgroup = document.createElement('optgroup');
  3731. optgroup.label = 'SD-WAN Groups';
  3732. state.sdwanGroups.forEach(g => {
  3733. const opt = document.createElement('option');
  3734. opt.value = g.name;
  3735. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3736. if (g.name === currentVal) opt.selected = true;
  3737. optgroup.appendChild(opt);
  3738. });
  3739. sel.appendChild(optgroup);
  3740. }
  3741. }
  3742. function populateAddressListSelect(selectId, currentVal = '') {
  3743. const sel = document.getElementById(selectId);
  3744. if (!sel) return;
  3745. sel.innerHTML = '<option value="">(None)</option>';
  3746. const cleanVal = (currentVal || '').replace(/^!/, '');
  3747. 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_'));
  3748. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3749. customNames.forEach(name => {
  3750. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3751. const opt = document.createElement('option');
  3752. opt.value = name;
  3753. opt.innerText = `${name} (${count} entries)`;
  3754. if (name === cleanVal) opt.selected = true;
  3755. sel.appendChild(opt);
  3756. });
  3757. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3758. const opt = document.createElement('option');
  3759. opt.value = cleanVal;
  3760. opt.innerText = cleanVal;
  3761. opt.selected = true;
  3762. sel.appendChild(opt);
  3763. }
  3764. populateCommonAddrListDatalist();
  3765. }
  3766. function populateCommonAddrListDatalist() {
  3767. const dl = document.getElementById('fw-addrlist-datalist');
  3768. if (!dl) return;
  3769. dl.innerHTML = '';
  3770. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3771. names.forEach(name => {
  3772. const opt = document.createElement('option');
  3773. opt.value = name;
  3774. dl.appendChild(opt);
  3775. });
  3776. }
  3777. function populateGeoIPSelect(selectId, currentVal = '') {
  3778. const sel = document.getElementById(selectId);
  3779. if (!sel) return;
  3780. sel.innerHTML = '<option value="">(None)</option>';
  3781. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3782. // Presets optgroup
  3783. const grpPresets = document.createElement('optgroup');
  3784. grpPresets.label = '⚡ Regional Presets';
  3785. const presets = [
  3786. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3787. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3788. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3789. ];
  3790. presets.forEach(p => {
  3791. const opt = document.createElement('option');
  3792. opt.value = p.code;
  3793. opt.innerText = p.label;
  3794. if (p.code === cleanVal) opt.selected = true;
  3795. grpPresets.appendChild(opt);
  3796. });
  3797. sel.appendChild(grpPresets);
  3798. // All Countries optgroup
  3799. const grpCountries = document.createElement('optgroup');
  3800. grpCountries.label = '🌍 All Countries';
  3801. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3802. countries.forEach(c => {
  3803. const opt = document.createElement('option');
  3804. opt.value = c.code;
  3805. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3806. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3807. if (c.code === cleanVal) opt.selected = true;
  3808. grpCountries.appendChild(opt);
  3809. });
  3810. sel.appendChild(grpCountries);
  3811. }
  3812. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3813. function switchFwRuleTab(tab) {
  3814. state.activeFwRuleTab = tab;
  3815. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3816. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3817. btn.classList.add('text-slate-400', 'border-transparent');
  3818. });
  3819. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3820. if (activeBtn) {
  3821. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3822. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3823. }
  3824. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3825. const activePane = document.getElementById(`fw-pane-${tab}`);
  3826. if (activePane) activePane.classList.remove('hidden');
  3827. if (tab === 'statistics') {
  3828. startFwStatPolling();
  3829. } else {
  3830. stopFwStatPolling();
  3831. }
  3832. }
  3833. function toggleFwField(fieldKey, expand) {
  3834. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3835. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3836. if (!plusBtn || !fieldBox) return;
  3837. if (expand) {
  3838. plusBtn.classList.add('hidden');
  3839. fieldBox.classList.remove('hidden');
  3840. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3841. if (valInput) valInput.focus();
  3842. } else {
  3843. fieldBox.classList.add('hidden');
  3844. plusBtn.classList.remove('hidden');
  3845. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3846. if (valInput) {
  3847. if (valInput.tagName === 'SELECT') {
  3848. valInput.selectedIndex = 0;
  3849. } else {
  3850. valInput.value = '';
  3851. }
  3852. }
  3853. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3854. if (invInput) invInput.checked = false;
  3855. if (fieldKey === 'cs') {
  3856. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3857. const el = document.getElementById(id);
  3858. if (el) el.checked = false;
  3859. });
  3860. }
  3861. if (fieldKey === 'natstate') {
  3862. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3863. const el = document.getElementById(id);
  3864. if (el) el.checked = false;
  3865. });
  3866. }
  3867. if (fieldKey === 'days') {
  3868. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3869. const el = document.getElementById(`fw-day-${d}`);
  3870. if (el) el.checked = true;
  3871. });
  3872. }
  3873. }
  3874. }
  3875. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3876. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3877. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3878. toggleFwField(fieldKey, true);
  3879. let strVal = String(value);
  3880. if (hasInvert) {
  3881. const inv = strVal.startsWith('!');
  3882. if (inv) strVal = strVal.slice(1);
  3883. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3884. if (invEl) invEl.checked = inv;
  3885. else if (inv) strVal = '!'+strVal;
  3886. }
  3887. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3888. 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; }
  3889. } else {
  3890. toggleFwField(fieldKey, false);
  3891. }
  3892. }
  3893. function getFwFieldVal(fieldKey, hasInvert = false) {
  3894. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3895. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3896. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3897. let v = valEl ? valEl.value.trim() : '';
  3898. if (!v) return '';
  3899. if (hasInvert) {
  3900. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3901. if (invEl && invEl.checked) {
  3902. v = '!' + v.replace(/^!/, '');
  3903. }
  3904. }
  3905. return v;
  3906. }
  3907. function toggleMaximizeFilterModal() {
  3908. const win = document.getElementById('filter-modal-window');
  3909. if (!win) return;
  3910. if (win.classList.contains('max-w-[720px]')) {
  3911. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3912. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3913. } else {
  3914. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3915. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3916. }
  3917. }
  3918. const FW_NATIVE_CHAINS = {
  3919. filter: [
  3920. { id: 'forward', label: 'FORWARD (routed through router)' },
  3921. { id: 'input', label: 'INPUT (destined to this router)' },
  3922. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3923. ],
  3924. nat: [
  3925. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3926. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3927. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3928. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3929. ],
  3930. mangle: [
  3931. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3932. { id: 'input', label: 'INPUT (destined to this machine)' },
  3933. { id: 'forward', label: 'FORWARD (routed through router)' },
  3934. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3935. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3936. ]
  3937. };
  3938. function populateChainDropdown(table, currentChain) {
  3939. const sel = document.getElementById(`${table}-modal-chain-select`);
  3940. if (!sel) return;
  3941. const cur = (currentChain || '').trim();
  3942. const lower = cur.toLowerCase();
  3943. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3944. const rules = state[rulesKey] || [];
  3945. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3946. const customChains = new Set();
  3947. rules.forEach(r => {
  3948. if (r.chain) {
  3949. const c = r.chain.trim();
  3950. const l = c.toLowerCase();
  3951. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3952. customChains.add(c);
  3953. }
  3954. }
  3955. });
  3956. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3957. if (isCurrentCustom) {
  3958. customChains.add(cur);
  3959. }
  3960. let html = '';
  3961. FW_NATIVE_CHAINS[table].forEach(c => {
  3962. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3963. });
  3964. if (customChains.size > 0) {
  3965. html += `<optgroup label="Custom Chains">`;
  3966. customChains.forEach(c => {
  3967. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3968. });
  3969. html += `</optgroup>`;
  3970. }
  3971. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3972. sel.innerHTML = html;
  3973. if (isCurrentCustom) {
  3974. sel.value = cur;
  3975. } else if (nativeIds.includes(lower)) {
  3976. sel.value = lower;
  3977. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3978. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3979. } else {
  3980. sel.value = nativeIds[0];
  3981. }
  3982. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3983. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3984. if (isCurrentCustom || sel.value === '__custom__') {
  3985. if (customWrap) customWrap.classList.remove('hidden');
  3986. if (customInput) customInput.value = cur;
  3987. } else {
  3988. if (customWrap) customWrap.classList.add('hidden');
  3989. if (customInput) customInput.value = '';
  3990. }
  3991. const chainInput = document.getElementById(`${table}-modal-chain`);
  3992. if (chainInput) chainInput.value = cur || sel.value;
  3993. }
  3994. function syncFilterChainFromSelect() {
  3995. const sel = document.getElementById('filter-modal-chain-select');
  3996. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3997. const customInput = document.getElementById('filter-modal-custom-input');
  3998. const chainInput = document.getElementById('filter-modal-chain');
  3999. if (!sel || !chainInput) return;
  4000. if (sel.value === '__custom__') {
  4001. if (customWrap) customWrap.classList.remove('hidden');
  4002. if (customInput) {
  4003. customInput.value = '';
  4004. customInput.focus();
  4005. }
  4006. chainInput.value = '';
  4007. } else {
  4008. if (customWrap) customWrap.classList.add('hidden');
  4009. chainInput.value = sel.value;
  4010. }
  4011. handleFilterChainChange();
  4012. }
  4013. function syncFilterCustomChainInput() {
  4014. const customInput = document.getElementById('filter-modal-custom-input');
  4015. const chainInput = document.getElementById('filter-modal-chain');
  4016. if (customInput && chainInput) {
  4017. chainInput.value = customInput.value.trim();
  4018. }
  4019. handleFilterChainChange();
  4020. }
  4021. function handleFilterChainChange() {
  4022. const chainInput = document.getElementById('filter-modal-chain');
  4023. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  4024. const sel = document.getElementById('filter-modal-chain-select');
  4025. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4026. if (['forward', 'input', 'output'].includes(chain)) {
  4027. sel.value = chain;
  4028. }
  4029. }
  4030. const hintEl = document.getElementById('filter-chain-hint');
  4031. if (hintEl) {
  4032. if (chain === 'forward') {
  4033. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  4034. } else if (chain === 'input') {
  4035. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  4036. } else if (chain === 'output') {
  4037. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  4038. } else {
  4039. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  4040. }
  4041. }
  4042. const rowIn = document.getElementById('fw-row-iniface');
  4043. const rowInList = document.getElementById('fw-row-inifacelist');
  4044. const rowOut = document.getElementById('fw-row-outiface');
  4045. const rowOutList = document.getElementById('fw-row-outifacelist');
  4046. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  4047. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  4048. const rowSrcMac = document.getElementById('fw-row-srcmac');
  4049. if (chain === 'input') {
  4050. if (rowIn) rowIn.classList.remove('hidden');
  4051. if (rowInList) rowInList.classList.remove('hidden');
  4052. if (rowOut) rowOut.classList.add('hidden');
  4053. if (rowOutList) rowOutList.classList.add('hidden');
  4054. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4055. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4056. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4057. } else if (chain === 'output') {
  4058. if (rowIn) rowIn.classList.add('hidden');
  4059. if (rowInList) rowInList.classList.add('hidden');
  4060. if (rowOut) rowOut.classList.remove('hidden');
  4061. if (rowOutList) rowOutList.classList.remove('hidden');
  4062. if (rowInBridge) rowInBridge.classList.add('hidden');
  4063. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4064. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4065. } else {
  4066. if (rowIn) rowIn.classList.remove('hidden');
  4067. if (rowInList) rowInList.classList.remove('hidden');
  4068. if (rowOut) rowOut.classList.remove('hidden');
  4069. if (rowOutList) rowOutList.classList.remove('hidden');
  4070. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4071. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4072. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4073. }
  4074. checkFilterActionChainCompatibility();
  4075. }
  4076. function checkFilterActionChainCompatibility() {
  4077. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  4078. const warnBox = document.getElementById('filter-action-incompatible-warn');
  4079. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  4080. if (!warnBox || !warnMsg) return;
  4081. if (chain === 'prerouting' || chain === 'postrouting') {
  4082. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  4083. warnBox.classList.remove('hidden');
  4084. } else {
  4085. warnBox.classList.add('hidden');
  4086. }
  4087. }
  4088. function openAddFilterModal() {
  4089. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  4090. switchFwRuleTab('general');
  4091. setFirewallDays('fw', '');
  4092. const badge = document.getElementById('fw-modal-badge');
  4093. if (badge) badge.innerText = 'New...';
  4094. document.getElementById('filter-modal-id').value = '';
  4095. document.getElementById('filter-modal-family').value = '4';
  4096. document.getElementById('filter-modal-enabled').checked = true;
  4097. document.getElementById('filter-modal-comment').value = '';
  4098. document.getElementById('filter-modal-chain').value = 'forward';
  4099. populateChainDropdown('filter', 'forward');
  4100. handleFilterChainChange();
  4101. document.getElementById('filter-modal-action').value = 'accept';
  4102. document.getElementById('filter-modal-log').checked = false;
  4103. populateInterfaceSelect('fw-val-iniface');
  4104. populateInterfaceSelect('fw-val-outiface');
  4105. populateAddressListSelect('fw-val-srclist');
  4106. populateAddressListSelect('fw-val-dstlist');
  4107. populateGeoIPSelect('fw-val-srcgeo');
  4108. populateGeoIPSelect('fw-val-dstgeo');
  4109. const allFieldKeys = [
  4110. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4111. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4112. 'routingmark', 'conntype', 'cs', 'natstate',
  4113. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4114. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4115. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4116. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4117. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4118. ];
  4119. allFieldKeys.forEach(k => toggleFwField(k, false));
  4120. resetRuleCounterDisplay();
  4121. toggleFilterActionFields();
  4122. refreshFirewallRejectTypes();
  4123. document.getElementById('filter-modal').classList.remove('hidden');
  4124. }
  4125. function openEditFilterModal(id) {
  4126. id = decodeURIComponent(id);
  4127. const r = (state.filterRules || []).find(rule => rule.id === id);
  4128. if (!r) return;
  4129. switchFwRuleTab('general');
  4130. const badge = document.getElementById('fw-modal-badge');
  4131. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4132. document.getElementById('filter-modal-id').value = r.id;
  4133. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4134. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4135. document.getElementById('filter-modal-comment').value = r.comment || '';
  4136. const filterChain = r.chain || 'forward';
  4137. document.getElementById('filter-modal-chain').value = filterChain;
  4138. populateChainDropdown('filter', filterChain);
  4139. handleFilterChainChange();
  4140. setFirewallActionSelection('filter', r.action || 'accept');
  4141. document.getElementById('filter-modal-log').checked = !!r.log;
  4142. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4143. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4144. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4145. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4146. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4147. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4148. setFwFieldVal('src', r.src_address, true);
  4149. setFwFieldVal('dst', r.dst_address, true);
  4150. setFwFieldVal('srclist', r.src_address_list, true);
  4151. setFwFieldVal('dstlist', r.dst_address_list, true);
  4152. setFwFieldVal('srcgeo', r.src_geoip, true);
  4153. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4154. if (r.protocol && r.protocol !== 'all') {
  4155. setFwFieldVal('proto', r.protocol, true);
  4156. } else {
  4157. toggleFwField('proto', false);
  4158. }
  4159. setFwFieldVal('sport', r.src_port, true);
  4160. setFwFieldVal('dport', r.dst_port, true);
  4161. setFwFieldVal('anyport', r.any_port, true);
  4162. setFwFieldVal('iniface', r.in_interface, true);
  4163. setFwFieldVal('outiface', r.out_interface, true);
  4164. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4165. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4166. setFwFieldVal('pktmark', r.packet_mark, true);
  4167. setFwFieldVal('connmark', r.connection_mark, true);
  4168. setFwFieldVal('routingmark', r.routing_mark, true);
  4169. setFwFieldVal('conntype', r.connection_type, false);
  4170. const states = r.connection_state || [];
  4171. if (states.length > 0) {
  4172. toggleFwField('cs', true);
  4173. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4174. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4175. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4176. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4177. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4178. } else {
  4179. toggleFwField('cs', false);
  4180. }
  4181. const natStates = r.connection_nat_state || [];
  4182. if (natStates.length > 0) {
  4183. toggleFwField('natstate', true);
  4184. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4185. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4186. } else {
  4187. toggleFwField('natstate', false);
  4188. }
  4189. // Advanced tab fields
  4190. setFwFieldVal('layer7', r.layer7_protocol, false);
  4191. setFwFieldVal('content', r.content, false);
  4192. setFwFieldVal('connbytes', r.connection_bytes, false);
  4193. setFwFieldVal('connrate', r.connection_rate, false);
  4194. setFwFieldVal('pcc', r.pcc, false);
  4195. setFwFieldVal('srcmac', r.src_mac_address, true);
  4196. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4197. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4198. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4199. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4200. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4201. setFwFieldVal('tlshost', r.tls_host, false);
  4202. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4203. setFwFieldVal('priority', r.priority, false);
  4204. setFwFieldVal('dscp', r.dscp, false);
  4205. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4206. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4207. setFwFieldVal('pktsize', r.packet_size, false);
  4208. setFwFieldVal('random', r.random, false);
  4209. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4210. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4211. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4212. setFwFieldVal('ttl', r.ttl, false);
  4213. // Extra tab fields
  4214. setFwFieldVal('time', r.time, false);
  4215. if (r.days) {
  4216. toggleFwField('days', true);
  4217. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4218. const chk = document.getElementById(`fw-day-${d}`);
  4219. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4220. });
  4221. } else {
  4222. toggleFwField('days', false);
  4223. }
  4224. setFwFieldVal('limit', r.limit, false);
  4225. setFwFieldVal('dstlimit', r.dst_limit, false);
  4226. setFwFieldVal('psd', r.psd, false);
  4227. // Action fields
  4228. if (r.reject_with) {
  4229. const rwEl = document.getElementById('filter-modal-rejectwith');
  4230. if (rwEl) rwEl.value = r.reject_with;
  4231. }
  4232. if (r.jump_target) {
  4233. const jtEl = document.getElementById('filter-modal-jumptarget');
  4234. if (jtEl) jtEl.value = r.jump_target;
  4235. }
  4236. if (r.address_list) {
  4237. const alEl = document.getElementById('filter-modal-action-addrlist');
  4238. if (alEl) alEl.value = r.address_list;
  4239. }
  4240. if (r.address_list_timeout) {
  4241. const toEl = document.getElementById('filter-modal-action-timeout');
  4242. if (toEl) toEl.value = r.address_list_timeout;
  4243. }
  4244. setFwFieldVal('logprefix', r.log_prefix, false);
  4245. // Statistics
  4246. const bEl = document.getElementById('fw-stat-bytes');
  4247. const pEl = document.getElementById('fw-stat-packets');
  4248. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4249. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4250. state.fwLastBytes = r.bytes || 0;
  4251. state.fwLastPackets = r.packets || 0;
  4252. state.fwLastTimestamp = Date.now();
  4253. state.fwStatRateHistory = new Array(30).fill(0);
  4254. state.fwStatPktHistory = new Array(30).fill(0);
  4255. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4256. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4257. toggleFilterActionFields();
  4258. refreshFirewallRejectTypes();
  4259. document.getElementById('filter-modal').classList.remove('hidden');
  4260. }
  4261. function closeFilterModal() {
  4262. stopFwStatPolling();
  4263. document.getElementById('filter-modal').classList.add('hidden');
  4264. }
  4265. function toggleFilterActionFields() {
  4266. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4267. const rejectBox = document.getElementById('filter-action-reject-box');
  4268. const jumpBox = document.getElementById('filter-action-jump-box');
  4269. const addrBox = document.getElementById('filter-action-addrlist-box');
  4270. if (rejectBox) {
  4271. if (act === 'reject') rejectBox.classList.remove('hidden');
  4272. else rejectBox.classList.add('hidden');
  4273. }
  4274. if (jumpBox) {
  4275. if (act === 'jump') jumpBox.classList.remove('hidden');
  4276. else jumpBox.classList.add('hidden');
  4277. }
  4278. if (addrBox) {
  4279. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4280. addrBox.classList.remove('hidden');
  4281. } else {
  4282. addrBox.classList.add('hidden');
  4283. }
  4284. }
  4285. if (act === 'log') {
  4286. const logEl = document.getElementById('filter-modal-log');
  4287. if (logEl) logEl.checked = true;
  4288. toggleFwField('logprefix', true);
  4289. }
  4290. }
  4291. function toggleFwLogPrefix() {
  4292. const isLog = document.getElementById('filter-modal-log')?.checked;
  4293. toggleFwField('logprefix', !!isLog);
  4294. }
  4295. function copyFilterRule() {
  4296. document.getElementById('filter-modal-id').value = '';
  4297. const badge = document.getElementById('fw-modal-badge');
  4298. if (badge) badge.innerText = 'New...';
  4299. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4300. }
  4301. function resetRuleCounterDisplay() {
  4302. state.fwStatRateHistory = new Array(30).fill(0);
  4303. state.fwStatPktHistory = new Array(30).fill(0);
  4304. state.fwLastBytes = 0;
  4305. state.fwLastPackets = 0;
  4306. state.fwLastTimestamp = Date.now();
  4307. const bEl = document.getElementById('fw-stat-bytes');
  4308. const pEl = document.getElementById('fw-stat-packets');
  4309. const rEl = document.getElementById('fw-stat-rate');
  4310. const prEl = document.getElementById('fw-stat-pktrate');
  4311. if (bEl) bEl.value = '0 B';
  4312. if (pEl) pEl.value = '0';
  4313. if (rEl) rEl.value = '0 bps';
  4314. if (prEl) prEl.value = '0 p/s';
  4315. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4316. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4317. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4318. }
  4319. async function resetAllFwCounters() {
  4320. try {
  4321. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4322. if (res.ok) {
  4323. resetRuleCounterDisplay();
  4324. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4325. loadFirewall(false);
  4326. }
  4327. } catch (err) {
  4328. showToast('Error', err.message, 'error');
  4329. }
  4330. }
  4331. async function applyFilterRule(closeAfter = false) {
  4332. const id = document.getElementById('filter-modal-id').value;
  4333. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4334. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4335. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4336. const chainLower = chain.toLowerCase();
  4337. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4338. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4339. switchFwRuleTab('general');
  4340. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4341. return;
  4342. }
  4343. const action = document.getElementById('filter-modal-action').value;
  4344. const comment = document.getElementById('filter-modal-comment').value.trim();
  4345. const enabled = document.getElementById('filter-modal-enabled').checked;
  4346. const src = getFwFieldVal('src', true);
  4347. const dst = getFwFieldVal('dst', true);
  4348. const srclist = getFwFieldVal('srclist', true);
  4349. const dstlist = getFwFieldVal('dstlist', true);
  4350. const srcgeo = getFwFieldVal('srcgeo', true);
  4351. const dstgeo = getFwFieldVal('dstgeo', true);
  4352. const proto = getFwFieldVal('proto', true);
  4353. const sport = getFwFieldVal('sport', true);
  4354. const dport = getFwFieldVal('dport', true);
  4355. const anyport = getFwFieldVal('anyport', true);
  4356. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4357. switchFwRuleTab('general'); toggleFwField('proto', true);
  4358. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4359. }
  4360. let iniface = getFwFieldVal('iniface', true);
  4361. let outiface = getFwFieldVal('outiface', true);
  4362. let inifacelist = getFwFieldVal('inifacelist', true);
  4363. let outifacelist = getFwFieldVal('outifacelist', true);
  4364. if (chainLower === 'input') {
  4365. outiface = '';
  4366. outifacelist = '';
  4367. } else if (chainLower === 'output') {
  4368. iniface = '';
  4369. inifacelist = '';
  4370. }
  4371. const pktmark = getFwFieldVal('pktmark', true);
  4372. const connmark = getFwFieldVal('connmark', true);
  4373. const routingmark = getFwFieldVal('routingmark', true);
  4374. const conntype = getFwFieldVal('conntype', false);
  4375. const states = [];
  4376. const csBox = document.getElementById('fw-field-cs');
  4377. if (csBox && !csBox.classList.contains('hidden')) {
  4378. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4379. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4380. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4381. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4382. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4383. }
  4384. const natStates = [];
  4385. const natBox = document.getElementById('fw-field-natstate');
  4386. if (natBox && !natBox.classList.contains('hidden')) {
  4387. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4388. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4389. }
  4390. const payload = {
  4391. ip_version: Number(document.getElementById('filter-modal-family').value),
  4392. id,
  4393. chain,
  4394. action,
  4395. protocol: proto || 'all',
  4396. src_address: src,
  4397. dst_address: dst,
  4398. src_port: sport,
  4399. dst_port: dport,
  4400. any_port: anyport,
  4401. in_interface: iniface,
  4402. out_interface: outiface,
  4403. in_interface_list: inifacelist,
  4404. out_interface_list: outifacelist,
  4405. packet_mark: pktmark,
  4406. connection_mark: connmark,
  4407. routing_mark: routingmark,
  4408. connection_type: conntype,
  4409. connection_state: states,
  4410. connection_nat_state: natStates,
  4411. src_address_list: srclist,
  4412. dst_address_list: dstlist,
  4413. src_geoip: srcgeo,
  4414. dst_geoip: dstgeo,
  4415. comment,
  4416. disabled: !enabled,
  4417. // Advanced tab
  4418. content: getFwFieldVal('content', false),
  4419. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4420. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4421. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4422. ipsec_policy: getFwFieldVal('ipsec', false),
  4423. dscp: getFwFieldVal('dscp', false),
  4424. tcp_mss: getFwFieldVal('tcpmss', false),
  4425. tos: document.getElementById('fw-val-tos')?.value || '',
  4426. packet_size: getFwFieldVal('pktsize', false),
  4427. random: getFwFieldVal('random', false),
  4428. tcp_flags: getFwFieldVal('tcpflags', false),
  4429. icmp_options: getFwFieldVal('icmpoptions', false),
  4430. ttl: getFwFieldVal('ttl', false),
  4431. days: selectedDays,
  4432. // Extra tab
  4433. time: getFwFieldVal('time', false),
  4434. limit: getFwFieldVal('limit', false),
  4435. // Action tab
  4436. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4437. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4438. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4439. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4440. log: document.getElementById('filter-modal-log')?.checked || false,
  4441. log_prefix: getFwFieldVal('logprefix', false)
  4442. };
  4443. try {
  4444. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4445. method: 'POST',
  4446. headers: { 'Content-Type': 'application/json' },
  4447. body: JSON.stringify(payload)
  4448. });
  4449. if (res.ok) {
  4450. const data = await res.json();
  4451. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4452. loadFirewall(false);
  4453. if (closeAfter) {
  4454. closeFilterModal();
  4455. } else {
  4456. if (data.id) {
  4457. document.getElementById('filter-modal-id').value = data.id;
  4458. const badge = document.getElementById('fw-modal-badge');
  4459. if (badge) badge.innerText = `#${data.id}`;
  4460. }
  4461. }
  4462. } else {
  4463. const err = await res.json();
  4464. showToast('Error', err.message || 'Failed to save rule', 'error');
  4465. }
  4466. } catch (err) {
  4467. showToast('Error', err.message, 'error');
  4468. }
  4469. }
  4470. function submitSaveFilterRule(e) {
  4471. if (e && e.preventDefault) e.preventDefault();
  4472. return applyFilterRule(true);
  4473. }
  4474. function startFwStatPolling() {
  4475. stopFwStatPolling();
  4476. pollRuleStats();
  4477. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4478. }
  4479. function stopFwStatPolling() {
  4480. if (state.fwStatInterval) {
  4481. clearInterval(state.fwStatInterval);
  4482. state.fwStatInterval = null;
  4483. }
  4484. }
  4485. async function pollRuleStats() {
  4486. const id = document.getElementById('filter-modal-id')?.value;
  4487. if (!id) {
  4488. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4489. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4490. return;
  4491. }
  4492. try {
  4493. const res = await fetch(`${API_BASE}/firewall/filter`);
  4494. if (!res.ok) return;
  4495. const rules = await res.json();
  4496. const r = rules.find(x => x.id === id);
  4497. if (!r) return;
  4498. const now = Date.now();
  4499. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4500. state.fwLastTimestamp = now;
  4501. const curBytes = r.bytes || 0;
  4502. const curPackets = r.packets || 0;
  4503. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4504. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4505. state.fwLastBytes = curBytes;
  4506. state.fwLastPackets = curPackets;
  4507. const rateBps = Math.round((deltaBytes * 8) / dt);
  4508. const ratePkt = Math.round(deltaPkts / dt);
  4509. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4510. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4511. state.fwStatRateHistory.push(rateBps);
  4512. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4513. state.fwStatPktHistory.push(ratePkt);
  4514. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4515. const bEl = document.getElementById('fw-stat-bytes');
  4516. const pEl = document.getElementById('fw-stat-packets');
  4517. const rEl = document.getElementById('fw-stat-rate');
  4518. const prEl = document.getElementById('fw-stat-pktrate');
  4519. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4520. if (pEl) pEl.value = curPackets.toLocaleString();
  4521. if (rEl) rEl.value = formatBps(rateBps);
  4522. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4523. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4524. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4525. } catch (e) {
  4526. console.error('Error polling rule stats', e);
  4527. }
  4528. }
  4529. function formatBps(bps) {
  4530. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4531. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4532. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4533. return bps + ' bps';
  4534. }
  4535. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4536. const svg = document.getElementById(svgId);
  4537. if (!svg) return;
  4538. const w = 500;
  4539. const h = 100;
  4540. const paddingRight = 45;
  4541. const graphWidth = w - paddingRight;
  4542. const maxVal = Math.max(5, ...dataArray);
  4543. const currentVal = dataArray[dataArray.length - 1] || 0;
  4544. const leg = document.getElementById(legendId);
  4545. if (leg) {
  4546. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4547. }
  4548. let gridLines = '';
  4549. for (let i = 0; i <= 5; i++) {
  4550. const y = 8 + (i * (h - 18) / 5);
  4551. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4552. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4553. gridLines += `
  4554. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4555. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4556. `;
  4557. }
  4558. const step = graphWidth / (dataArray.length - 1);
  4559. const points = dataArray.map((val, idx) => {
  4560. const x = idx * step;
  4561. const y = (h - 10) - (val / maxVal) * (h - 20);
  4562. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4563. });
  4564. const polylineStr = points.join(' ');
  4565. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4566. svg.innerHTML = `
  4567. ${gridLines}
  4568. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4569. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4570. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4571. `;
  4572. }
  4573. async function moveFilterRule(id, dir) {
  4574. id = decodeURIComponent(id);
  4575. try {
  4576. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4577. method: 'POST',
  4578. headers: { 'Content-Type': 'application/json' },
  4579. body: JSON.stringify({ direction: dir })
  4580. });
  4581. if (!res.ok) throw new Error(await responseError(res));
  4582. await loadFirewall(false);
  4583. } catch (err) {
  4584. showToast('Error', err.message, 'error');
  4585. }
  4586. }
  4587. async function toggleFilterRuleState(id, disabled) {
  4588. id = decodeURIComponent(id);
  4589. try {
  4590. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4591. method: 'POST',
  4592. headers: { 'Content-Type': 'application/json' },
  4593. body: JSON.stringify({ disabled })
  4594. });
  4595. if (!res.ok) throw new Error(await responseError(res));
  4596. await loadFirewall(false);
  4597. } catch (err) {
  4598. showToast('Error', err.message, 'error');
  4599. }
  4600. }
  4601. async function deleteFilterRule(id) {
  4602. id = decodeURIComponent(id);
  4603. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4604. try {
  4605. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4606. if (!res.ok) throw new Error(await responseError(res));
  4607. {
  4608. showToast('Deleted', 'Filter rule removed', 'success');
  4609. loadFirewall(false);
  4610. }
  4611. } catch (err) {
  4612. showToast('Error', err.message, 'error');
  4613. }
  4614. }
  4615. // ----------------- NAT Rules -----------------
  4616. function renderNATRules() {
  4617. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4618. const tbody = document.getElementById('nat-table-body');
  4619. const empty = document.getElementById('nat-empty');
  4620. if (!tbody) return;
  4621. tbody.innerHTML = '';
  4622. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4623. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4624. if (rules.length === 0) {
  4625. empty?.classList.remove('hidden');
  4626. return;
  4627. }
  4628. empty?.classList.add('hidden');
  4629. rules.forEach((raw, idx) => {
  4630. const r = safeFirewallRow(raw);
  4631. const tr = document.createElement('tr');
  4632. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4633. let toTarget = '-';
  4634. if (r.action === 'jump') {
  4635. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4636. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4637. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4638. } else if (r.action === 'redirect') {
  4639. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4640. } else if (r.action === 'masquerade') {
  4641. 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>`;
  4642. } else if (r.action === 'log') {
  4643. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4644. } else {
  4645. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4646. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4647. }
  4648. 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(' ');
  4649. tr.innerHTML = `
  4650. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4651. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4652. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4653. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4654. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4655. <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>
  4656. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4657. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4658. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4659. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4660. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4661. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4662. </td>
  4663. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4664. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4665. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4666. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4667. <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>
  4668. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4669. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4670. </td>
  4671. `;
  4672. tbody.appendChild(tr);
  4673. });
  4674. }
  4675. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4676. function switchNATRuleTab(tab) {
  4677. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4678. state.activeNATRuleTab = tab;
  4679. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4680. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4681. btn.classList.add('text-slate-400', 'border-transparent');
  4682. });
  4683. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4684. if (activeBtn) {
  4685. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4686. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4687. }
  4688. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4689. const activePane = document.getElementById(`nat-pane-${tab}`);
  4690. if (activePane) activePane.classList.remove('hidden');
  4691. if (tab === 'statistics') {
  4692. startNATStatPolling();
  4693. } else {
  4694. stopNATStatPolling();
  4695. }
  4696. }
  4697. function toggleNATField(fieldKey, expand) {
  4698. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4699. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4700. if (!plusBtn || !fieldBox) return;
  4701. if (expand) {
  4702. plusBtn.classList.add('hidden');
  4703. fieldBox.classList.remove('hidden');
  4704. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4705. if (valInput) valInput.focus();
  4706. } else {
  4707. fieldBox.classList.add('hidden');
  4708. plusBtn.classList.remove('hidden');
  4709. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4710. if (valInput) {
  4711. if (valInput.tagName === 'SELECT') {
  4712. valInput.selectedIndex = 0;
  4713. } else {
  4714. valInput.value = '';
  4715. }
  4716. }
  4717. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4718. if (invInput) invInput.checked = false;
  4719. if (fieldKey === 'days') {
  4720. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4721. const el = document.getElementById(`nat-day-${d}`);
  4722. if (el) el.checked = true;
  4723. });
  4724. }
  4725. }
  4726. }
  4727. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4728. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4729. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4730. toggleNATField(fieldKey, true);
  4731. let strVal = String(value);
  4732. if (hasInvert) {
  4733. const inv = strVal.startsWith('!');
  4734. if (inv) strVal = strVal.slice(1);
  4735. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4736. if (invEl) invEl.checked = inv;
  4737. else if (inv) strVal = '!'+strVal;
  4738. }
  4739. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4740. 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; }
  4741. } else {
  4742. toggleNATField(fieldKey, false);
  4743. }
  4744. }
  4745. function getNATFieldVal(fieldKey, hasInvert = false) {
  4746. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4747. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4748. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4749. let v = valEl ? valEl.value.trim() : '';
  4750. if (!v) return '';
  4751. if (hasInvert) {
  4752. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4753. if (invEl && invEl.checked) {
  4754. v = '!' + v.replace(/^!/, '');
  4755. }
  4756. }
  4757. return v;
  4758. }
  4759. function toggleMaximizeNATModal() {
  4760. const win = document.getElementById('nat-modal-window');
  4761. if (!win) return;
  4762. if (win.classList.contains('max-w-[720px]')) {
  4763. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4764. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4765. } else {
  4766. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4767. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4768. }
  4769. }
  4770. function syncNATChainFromSelect() {
  4771. const sel = document.getElementById('nat-modal-chain-select');
  4772. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4773. const customInput = document.getElementById('nat-modal-custom-input');
  4774. const chainInput = document.getElementById('nat-modal-chain');
  4775. if (!sel || !chainInput) return;
  4776. if (sel.value === '__custom__') {
  4777. if (customWrap) customWrap.classList.remove('hidden');
  4778. if (customInput) {
  4779. customInput.value = '';
  4780. customInput.focus();
  4781. }
  4782. chainInput.value = '';
  4783. } else {
  4784. if (customWrap) customWrap.classList.add('hidden');
  4785. chainInput.value = sel.value;
  4786. const actEl = document.getElementById('nat-modal-action');
  4787. if (actEl) {
  4788. const curAct = actEl.value;
  4789. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4790. actEl.value = 'dst-nat';
  4791. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4792. actEl.value = 'masquerade';
  4793. }
  4794. }
  4795. }
  4796. handleNATChainChange();
  4797. }
  4798. function syncNATCustomChainInput() {
  4799. const customInput = document.getElementById('nat-modal-custom-input');
  4800. const chainInput = document.getElementById('nat-modal-chain');
  4801. if (customInput && chainInput) {
  4802. chainInput.value = customInput.value.trim();
  4803. }
  4804. handleNATChainChange();
  4805. }
  4806. function handleNATChainChange() {
  4807. const chainInput = document.getElementById('nat-modal-chain');
  4808. const rawChain = (chainInput?.value || 'postrouting').trim();
  4809. const chain = nativeNATChain(rawChain).toLowerCase();
  4810. const sel = document.getElementById('nat-modal-chain-select');
  4811. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4812. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4813. sel.value = chain;
  4814. }
  4815. }
  4816. const hintEl = document.getElementById('nat-chain-hint');
  4817. if (hintEl) {
  4818. if (chain === 'prerouting') {
  4819. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4820. } else if (chain === 'postrouting') {
  4821. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4822. } else if (chain === 'output') {
  4823. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4824. } else if (chain === 'input') {
  4825. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4826. } else {
  4827. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4828. }
  4829. }
  4830. const rowIn = document.getElementById('nat-row-iniface');
  4831. const rowInList = document.getElementById('nat-row-inifacelist');
  4832. const rowOut = document.getElementById('nat-row-outiface');
  4833. const rowOutList = document.getElementById('nat-row-outifacelist');
  4834. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4835. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4836. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4837. if (chain === 'prerouting' || chain === 'input') {
  4838. if (rowIn) rowIn.classList.remove('hidden');
  4839. if (rowInList) rowInList.classList.remove('hidden');
  4840. if (rowOut) rowOut.classList.add('hidden');
  4841. if (rowOutList) rowOutList.classList.add('hidden');
  4842. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4843. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4844. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4845. } else if (chain === 'postrouting' || chain === 'output') {
  4846. if (rowIn) rowIn.classList.add('hidden');
  4847. if (rowInList) rowInList.classList.add('hidden');
  4848. if (rowOut) rowOut.classList.remove('hidden');
  4849. if (rowOutList) rowOutList.classList.remove('hidden');
  4850. if (rowInBridge) rowInBridge.classList.add('hidden');
  4851. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4852. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4853. } else {
  4854. if (rowIn) rowIn.classList.remove('hidden');
  4855. if (rowInList) rowInList.classList.remove('hidden');
  4856. if (rowOut) rowOut.classList.remove('hidden');
  4857. if (rowOutList) rowOutList.classList.remove('hidden');
  4858. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4859. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4860. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4861. }
  4862. checkNATActionChainCompatibility();
  4863. toggleNATActionFields();
  4864. }
  4865. function checkNATActionChainCompatibility() {
  4866. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4867. const chain = nativeNATChain(rawChain).toLowerCase();
  4868. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4869. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4870. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4871. if (!warnBox || !warnMsg) return;
  4872. let msg = '';
  4873. if (['dst-nat', 'redirect'].includes(action)) {
  4874. if (chain !== 'prerouting' && chain !== 'output') {
  4875. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4876. }
  4877. } else if (action === 'masquerade') {
  4878. if (chain !== 'postrouting') {
  4879. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4880. }
  4881. } else if (action === 'src-nat') {
  4882. if (chain !== 'postrouting' && chain !== 'input') {
  4883. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4884. }
  4885. }
  4886. if (msg) {
  4887. warnMsg.textContent = msg;
  4888. warnBox.classList.remove('hidden');
  4889. } else {
  4890. warnBox.classList.add('hidden');
  4891. }
  4892. }
  4893. function toggleNATActionFields() {
  4894. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4895. const rowAddr = document.getElementById('nat-row-toaddr');
  4896. const rowPort = document.getElementById('nat-row-toport');
  4897. const jumpBox = document.getElementById('nat-action-jump-box');
  4898. const addrBox = document.getElementById('nat-action-addrlist-box');
  4899. // Hide all dynamic rows first
  4900. if (rowAddr) rowAddr.classList.add('hidden');
  4901. if (rowPort) rowPort.classList.add('hidden');
  4902. if (jumpBox) jumpBox.classList.add('hidden');
  4903. if (addrBox) addrBox.classList.add('hidden');
  4904. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4905. if (rowAddr) rowAddr.classList.remove('hidden');
  4906. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4907. } else if (act === 'redirect' || act === 'masquerade') {
  4908. if (rowPort) rowPort.classList.remove('hidden');
  4909. } else if (act === 'jump') {
  4910. if (jumpBox) jumpBox.classList.remove('hidden');
  4911. } else if (act.includes('address-list') || act.includes('address list')) {
  4912. if (addrBox) addrBox.classList.remove('hidden');
  4913. }
  4914. if (act === 'log') {
  4915. const logEl = document.getElementById('nat-modal-log');
  4916. if (logEl) logEl.checked = true;
  4917. toggleNATField('logprefix', true);
  4918. }
  4919. }
  4920. function handleNATActionChange() {
  4921. toggleNATActionFields();
  4922. checkNATActionChainCompatibility();
  4923. }
  4924. function toggleNATLogPrefix() {
  4925. const isLog = document.getElementById('nat-modal-log')?.checked;
  4926. toggleNATField('logprefix', !!isLog);
  4927. }
  4928. function openAddNATModal() {
  4929. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4930. switchNATRuleTab('general');
  4931. setFirewallDays('nat', '');
  4932. const badge = document.getElementById('nat-modal-badge');
  4933. if (badge) badge.innerText = 'New...';
  4934. document.getElementById('nat-modal-id').value = '';
  4935. document.getElementById('nat-modal-family').value = '4';
  4936. document.getElementById('nat-modal-enabled').checked = true;
  4937. document.getElementById('nat-modal-comment').value = '';
  4938. document.getElementById('nat-modal-chain').value = 'postrouting';
  4939. populateChainDropdown('nat', 'postrouting');
  4940. handleNATChainChange();
  4941. document.getElementById('nat-modal-action').value = 'masquerade';
  4942. document.getElementById('nat-modal-toaddr').value = '';
  4943. document.getElementById('nat-modal-toport').value = '';
  4944. document.getElementById('nat-modal-log').checked = false;
  4945. populateInterfaceSelect('nat-val-iniface');
  4946. populateInterfaceSelect('nat-val-outiface');
  4947. populateAddressListSelect('nat-val-srclist');
  4948. populateAddressListSelect('nat-val-dstlist');
  4949. populateGeoIPSelect('nat-val-srcgeo');
  4950. populateGeoIPSelect('nat-val-dstgeo');
  4951. const allFieldKeys = [
  4952. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4953. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4954. 'routingmark', 'conntype',
  4955. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4956. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4957. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4958. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4959. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4960. ];
  4961. allFieldKeys.forEach(k => toggleNATField(k, false));
  4962. resetNATCounterDisplay();
  4963. toggleNATActionFields();
  4964. document.getElementById('nat-modal').classList.remove('hidden');
  4965. }
  4966. function openEditNATModal(id) {
  4967. id = decodeURIComponent(id);
  4968. const r = (state.natRules || []).find(rule => rule.id === id);
  4969. if (!r) return;
  4970. setFirewallDays('nat', r.days || '');
  4971. switchNATRuleTab('general');
  4972. const badge = document.getElementById('nat-modal-badge');
  4973. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4974. document.getElementById('nat-modal-id').value = r.id;
  4975. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4976. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4977. document.getElementById('nat-modal-comment').value = r.comment || '';
  4978. const natChain = nativeNATChain(r.chain || 'postrouting');
  4979. document.getElementById('nat-modal-chain').value = natChain;
  4980. populateChainDropdown('nat', natChain);
  4981. handleNATChainChange();
  4982. setFirewallActionSelection('nat', r.action || 'accept');
  4983. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4984. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4985. document.getElementById('nat-modal-log').checked = !!r.log;
  4986. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4987. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4988. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4989. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4990. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4991. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4992. setNATFieldVal('src', r.src_address, true);
  4993. setNATFieldVal('dst', r.dst_address, true);
  4994. setNATFieldVal('srclist', r.src_address_list, true);
  4995. setNATFieldVal('dstlist', r.dst_address_list, true);
  4996. setNATFieldVal('srcgeo', r.src_geoip, true);
  4997. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4998. if (r.protocol && r.protocol !== 'all') {
  4999. setNATFieldVal('proto', r.protocol, true);
  5000. } else {
  5001. toggleNATField('proto', false);
  5002. }
  5003. setNATFieldVal('sport', r.src_port, true);
  5004. setNATFieldVal('dport', r.dst_port, true);
  5005. setNATFieldVal('anyport', r.any_port, true);
  5006. setNATFieldVal('iniface', r.in_interface, true);
  5007. setNATFieldVal('outiface', r.out_interface, true);
  5008. setNATFieldVal('inifacelist', r.in_interface_list, true);
  5009. setNATFieldVal('outifacelist', r.out_interface_list, true);
  5010. setNATFieldVal('pktmark', r.packet_mark, true);
  5011. setNATFieldVal('connmark', r.connection_mark, true);
  5012. setNATFieldVal('routingmark', r.routing_mark, true);
  5013. setNATFieldVal('conntype', r.connection_type, false);
  5014. // Advanced tab fields
  5015. setNATFieldVal('layer7', r.layer7_protocol, false);
  5016. setNATFieldVal('content', r.content, false);
  5017. setNATFieldVal('connbytes', r.connection_bytes, false);
  5018. setNATFieldVal('connrate', r.connection_rate, false);
  5019. setNATFieldVal('pcc', r.pcc, false);
  5020. setNATFieldVal('srcmac', r.src_mac_address, true);
  5021. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  5022. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  5023. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5024. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5025. setNATFieldVal('ipsec', r.ipsec_policy, false);
  5026. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  5027. setNATFieldVal('priority', r.priority, false);
  5028. setNATFieldVal('dscp', r.dscp, false);
  5029. setNATFieldVal('tcpmss', r.tcp_mss, false);
  5030. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5031. setNATFieldVal('pktsize', r.packet_size, false);
  5032. setNATFieldVal('random', r.random, false);
  5033. setNATFieldVal('icmpoptions', r.icmp_options, false);
  5034. setNATFieldVal('ipv4options', r.ipv4_options, false);
  5035. setNATFieldVal('ttl', r.ttl, false);
  5036. // Extra tab fields
  5037. setNATFieldVal('time', r.time, false);
  5038. if (r.days) {
  5039. toggleNATField('days', true);
  5040. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  5041. const chk = document.getElementById(`nat-day-${d}`);
  5042. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  5043. });
  5044. } else {
  5045. toggleNATField('days', false);
  5046. }
  5047. setNATFieldVal('limit', r.limit, false);
  5048. setNATFieldVal('dstlimit', r.dst_limit, false);
  5049. setNATFieldVal('psd', r.psd, false);
  5050. // Action fields
  5051. if (r.jump_target) {
  5052. const jtEl = document.getElementById('nat-modal-jumptarget');
  5053. if (jtEl) jtEl.value = r.jump_target;
  5054. }
  5055. if (r.address_list) {
  5056. const alEl = document.getElementById('nat-modal-action-addrlist');
  5057. if (alEl) alEl.value = r.address_list;
  5058. }
  5059. if (r.address_list_timeout) {
  5060. const toEl = document.getElementById('nat-modal-action-timeout');
  5061. if (toEl) toEl.value = r.address_list_timeout;
  5062. }
  5063. setNATFieldVal('logprefix', r.log_prefix, false);
  5064. // Statistics
  5065. const bEl = document.getElementById('nat-stat-bytes');
  5066. const pEl = document.getElementById('nat-stat-packets');
  5067. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5068. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5069. state.natLastBytes = r.bytes || 0;
  5070. state.natLastPackets = r.packets || 0;
  5071. state.natLastTimestamp = Date.now();
  5072. state.natStatRateHistory = new Array(30).fill(0);
  5073. state.natStatPktHistory = new Array(30).fill(0);
  5074. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5075. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5076. toggleNATActionFields();
  5077. document.getElementById('nat-modal').classList.remove('hidden');
  5078. }
  5079. function closeNATModal() {
  5080. stopNATStatPolling();
  5081. document.getElementById('nat-modal').classList.add('hidden');
  5082. }
  5083. function copyNATRule() {
  5084. document.getElementById('nat-modal-id').value = '';
  5085. const badge = document.getElementById('nat-modal-badge');
  5086. if (badge) badge.innerText = 'New...';
  5087. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  5088. }
  5089. function resetNATCounterDisplay() {
  5090. state.natStatRateHistory = new Array(30).fill(0);
  5091. state.natStatPktHistory = new Array(30).fill(0);
  5092. state.natLastBytes = 0;
  5093. state.natLastPackets = 0;
  5094. state.natLastTimestamp = Date.now();
  5095. const bEl = document.getElementById('nat-stat-bytes');
  5096. const pEl = document.getElementById('nat-stat-packets');
  5097. const rEl = document.getElementById('nat-stat-rate');
  5098. const prEl = document.getElementById('nat-stat-pktrate');
  5099. if (bEl) bEl.value = '0 B';
  5100. if (pEl) pEl.value = '0';
  5101. if (rEl) rEl.value = '0 bps';
  5102. if (prEl) prEl.value = '0 p/s';
  5103. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5104. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5105. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5106. }
  5107. async function applyNATRule(closeAfter = false) {
  5108. const id = document.getElementById('nat-modal-id').value;
  5109. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5110. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5111. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5112. const chainLower = nativeNATChain(chain).toLowerCase();
  5113. const action = document.getElementById('nat-modal-action').value;
  5114. const comment = document.getElementById('nat-modal-comment').value.trim();
  5115. const enabled = document.getElementById('nat-modal-enabled').checked;
  5116. const src = getNATFieldVal('src', true);
  5117. const dst = getNATFieldVal('dst', true);
  5118. const srclist = getNATFieldVal('srclist', true);
  5119. const dstlist = getNATFieldVal('dstlist', true);
  5120. const srcgeo = getNATFieldVal('srcgeo', true);
  5121. const dstgeo = getNATFieldVal('dstgeo', true);
  5122. const proto = getNATFieldVal('proto', true);
  5123. const sport = getNATFieldVal('sport', true);
  5124. const dport = getNATFieldVal('dport', true);
  5125. const anyport = getNATFieldVal('anyport', true);
  5126. let iniface = getNATFieldVal('iniface', true);
  5127. let outiface = getNATFieldVal('outiface', true);
  5128. let inifacelist = getNATFieldVal('inifacelist', true);
  5129. let outifacelist = getNATFieldVal('outifacelist', true);
  5130. if (chainLower === 'prerouting' || chainLower === 'input') {
  5131. outiface = '';
  5132. outifacelist = '';
  5133. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5134. iniface = '';
  5135. inifacelist = '';
  5136. }
  5137. const pktmark = getNATFieldVal('pktmark', true);
  5138. const connmark = getNATFieldVal('connmark', true);
  5139. const routingmark = getNATFieldVal('routingmark', true);
  5140. const conntype = getNATFieldVal('conntype', false);
  5141. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5142. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5143. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5144. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5145. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5146. switchNATRuleTab('general');
  5147. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5148. return;
  5149. }
  5150. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5151. switchNATRuleTab('general');
  5152. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5153. return;
  5154. }
  5155. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5156. switchNATRuleTab('general');
  5157. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5158. return;
  5159. }
  5160. 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; }
  5161. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5162. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5163. 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;
  5164. }
  5165. const payload = {
  5166. ip_version: Number(document.getElementById('nat-modal-family').value),
  5167. id,
  5168. chain,
  5169. action,
  5170. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5171. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5172. protocol: proto || 'all',
  5173. src_address: src,
  5174. dst_address: dst,
  5175. src_port: sport,
  5176. dst_port: dport,
  5177. any_port: anyport,
  5178. in_interface: iniface,
  5179. out_interface: outiface,
  5180. in_interface_list: inifacelist,
  5181. out_interface_list: outifacelist,
  5182. packet_mark: pktmark,
  5183. connection_mark: connmark,
  5184. routing_mark: routingmark,
  5185. connection_type: conntype,
  5186. src_address_list: srclist,
  5187. dst_address_list: dstlist,
  5188. src_geoip: srcgeo,
  5189. dst_geoip: dstgeo,
  5190. comment,
  5191. disabled: !enabled,
  5192. // Advanced tab
  5193. content: getNATFieldVal('content', false),
  5194. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5195. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5196. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5197. ipsec_policy: getNATFieldVal('ipsec', false),
  5198. dscp: getNATFieldVal('dscp', false),
  5199. tcp_mss: getNATFieldVal('tcpmss', false),
  5200. tos: document.getElementById('nat-val-tos')?.value || '',
  5201. packet_size: getNATFieldVal('pktsize', false),
  5202. random: getNATFieldVal('random', false),
  5203. icmp_options: getNATFieldVal('icmpoptions', false),
  5204. ttl: getNATFieldVal('ttl', false),
  5205. days: selectedDays,
  5206. // Extra tab
  5207. time: getNATFieldVal('time', false),
  5208. limit: getNATFieldVal('limit', false),
  5209. // Action tab
  5210. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5211. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5212. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5213. log: document.getElementById('nat-modal-log')?.checked || false,
  5214. log_prefix: getNATFieldVal('logprefix', false)
  5215. };
  5216. try {
  5217. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5218. method: 'POST',
  5219. headers: { 'Content-Type': 'application/json' },
  5220. body: JSON.stringify(payload)
  5221. });
  5222. if (res.ok) {
  5223. const data = await res.json();
  5224. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5225. loadFirewall(false);
  5226. if (closeAfter) {
  5227. closeNATModal();
  5228. } else {
  5229. if (data.id) {
  5230. document.getElementById('nat-modal-id').value = data.id;
  5231. const badge = document.getElementById('nat-modal-badge');
  5232. if (badge) badge.innerText = `#${data.id}`;
  5233. }
  5234. }
  5235. } else {
  5236. const err = await res.json();
  5237. showToast('Error', err.message || 'Failed to save rule', 'error');
  5238. }
  5239. } catch (err) {
  5240. showToast('Error', err.message, 'error');
  5241. }
  5242. }
  5243. function submitSaveNATRule(e) {
  5244. if (e && e.preventDefault) e.preventDefault();
  5245. return applyNATRule(true);
  5246. }
  5247. function startNATStatPolling() {
  5248. stopNATStatPolling();
  5249. pollNATRuleStats();
  5250. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5251. }
  5252. function stopNATStatPolling() {
  5253. if (state.natStatInterval) {
  5254. clearInterval(state.natStatInterval);
  5255. state.natStatInterval = null;
  5256. }
  5257. }
  5258. async function pollNATRuleStats() {
  5259. const id = document.getElementById('nat-modal-id')?.value;
  5260. if (!id) {
  5261. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5262. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5263. return;
  5264. }
  5265. try {
  5266. const res = await fetch(`${API_BASE}/firewall/nat`);
  5267. if (!res.ok) return;
  5268. const rules = await res.json();
  5269. const r = rules.find(x => x.id === id);
  5270. if (!r) return;
  5271. const now = Date.now();
  5272. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5273. state.natLastTimestamp = now;
  5274. const curBytes = r.bytes || 0;
  5275. const curPackets = r.packets || 0;
  5276. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5277. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5278. state.natLastBytes = curBytes;
  5279. state.natLastPackets = curPackets;
  5280. const rateBps = Math.round((deltaBytes * 8) / dt);
  5281. const ratePkt = Math.round(deltaPkts / dt);
  5282. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5283. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5284. state.natStatRateHistory.push(rateBps);
  5285. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5286. state.natStatPktHistory.push(ratePkt);
  5287. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5288. const bEl = document.getElementById('nat-stat-bytes');
  5289. const pEl = document.getElementById('nat-stat-packets');
  5290. const rEl = document.getElementById('nat-stat-rate');
  5291. const prEl = document.getElementById('nat-stat-pktrate');
  5292. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5293. if (pEl) pEl.value = curPackets.toLocaleString();
  5294. if (rEl) rEl.value = formatBps(rateBps);
  5295. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5296. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5297. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5298. } catch (e) {
  5299. console.error('Error polling NAT rule stats', e);
  5300. }
  5301. }
  5302. async function moveNATRule(id, dir) {
  5303. id = decodeURIComponent(id);
  5304. try {
  5305. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5306. method: 'POST',
  5307. headers: { 'Content-Type': 'application/json' },
  5308. body: JSON.stringify({ direction: dir })
  5309. });
  5310. if (!res.ok) throw new Error(await responseError(res));
  5311. await loadFirewall(false);
  5312. } catch (err) {
  5313. showToast('Error', err.message, 'error');
  5314. }
  5315. }
  5316. async function toggleNATRuleState(id, disabled) {
  5317. id = decodeURIComponent(id);
  5318. try {
  5319. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5320. method: 'POST',
  5321. headers: { 'Content-Type': 'application/json' },
  5322. body: JSON.stringify({ disabled })
  5323. });
  5324. if (!res.ok) throw new Error(await responseError(res));
  5325. await loadFirewall(false);
  5326. } catch (err) {
  5327. showToast('Error', err.message, 'error');
  5328. }
  5329. }
  5330. async function deleteNATRule(id) {
  5331. id = decodeURIComponent(id);
  5332. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5333. try {
  5334. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5335. if (!res.ok) throw new Error(await responseError(res));
  5336. {
  5337. showToast('Deleted', 'NAT rule removed', 'success');
  5338. loadFirewall(false);
  5339. }
  5340. } catch (err) {
  5341. showToast('Error', err.message, 'error');
  5342. }
  5343. }
  5344. // ----------------- Mangle Rules -----------------
  5345. function renderMangleRules() {
  5346. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5347. const tbody = document.getElementById('mangle-table-body');
  5348. const empty = document.getElementById('mangle-empty');
  5349. if (!tbody) return;
  5350. tbody.innerHTML = '';
  5351. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5352. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5353. if (rules.length === 0) {
  5354. empty?.classList.remove('hidden');
  5355. return;
  5356. }
  5357. empty?.classList.add('hidden');
  5358. rules.forEach((raw, idx) => {
  5359. const r = safeFirewallRow(raw);
  5360. const tr = document.createElement('tr');
  5361. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5362. let markVal = '<span class="text-slate-500">-</span>';
  5363. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5364. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5365. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5366. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5367. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5368. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5369. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5370. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5371. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5372. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5373. 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>`;
  5374. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5375. tr.innerHTML = `
  5376. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5377. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5378. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5379. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5380. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5381. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5382. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5383. <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>
  5384. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5385. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5386. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5387. </td>
  5388. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5389. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5390. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5391. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5392. <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>
  5393. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5394. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5395. </td>
  5396. `;
  5397. tbody.appendChild(tr);
  5398. });
  5399. }
  5400. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5401. function switchMangleRuleTab(tab) {
  5402. state.activeMangleRuleTab = tab;
  5403. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5404. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5405. btn.classList.add('text-slate-400', 'border-transparent');
  5406. });
  5407. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5408. if (activeBtn) {
  5409. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5410. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5411. }
  5412. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5413. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5414. if (activePane) activePane.classList.remove('hidden');
  5415. if (tab === 'statistics') {
  5416. startMangleStatPolling();
  5417. } else {
  5418. stopMangleStatPolling();
  5419. }
  5420. }
  5421. function toggleMangleField(fieldKey, expand) {
  5422. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5423. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5424. if (!plusBtn || !fieldBox) return;
  5425. if (expand) {
  5426. plusBtn.classList.add('hidden');
  5427. fieldBox.classList.remove('hidden');
  5428. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5429. if (valInput) valInput.focus();
  5430. } else {
  5431. fieldBox.classList.add('hidden');
  5432. plusBtn.classList.remove('hidden');
  5433. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5434. if (valInput) {
  5435. if (valInput.tagName === 'SELECT') {
  5436. valInput.selectedIndex = 0;
  5437. } else {
  5438. valInput.value = '';
  5439. }
  5440. }
  5441. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5442. if (invInput) invInput.checked = false;
  5443. if (fieldKey === 'cs') {
  5444. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5445. const el = document.getElementById(id);
  5446. if (el) el.checked = false;
  5447. });
  5448. }
  5449. if (fieldKey === 'natstate') {
  5450. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5451. const el = document.getElementById(id);
  5452. if (el) el.checked = false;
  5453. });
  5454. }
  5455. }
  5456. }
  5457. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5458. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5459. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5460. toggleMangleField(fieldKey, true);
  5461. let strVal = String(value);
  5462. if (hasInvert) {
  5463. const inv = strVal.startsWith('!');
  5464. if (inv) strVal = strVal.slice(1);
  5465. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5466. if (invEl) invEl.checked = inv;
  5467. else if (inv) strVal = '!'+strVal;
  5468. }
  5469. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5470. 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; }
  5471. } else {
  5472. toggleMangleField(fieldKey, false);
  5473. }
  5474. }
  5475. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5476. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5477. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5478. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5479. let v = valEl ? valEl.value.trim() : '';
  5480. if (!v) return '';
  5481. if (hasInvert) {
  5482. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5483. if (invEl && invEl.checked) {
  5484. v = '!' + v.replace(/^!/, '');
  5485. }
  5486. }
  5487. return v;
  5488. }
  5489. function toggleMaximizeMangleModal() {
  5490. const win = document.getElementById('mangle-modal-window');
  5491. if (!win) return;
  5492. if (win.classList.contains('max-w-[720px]')) {
  5493. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5494. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5495. } else {
  5496. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5497. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5498. }
  5499. }
  5500. function syncMangleChainFromSelect() {
  5501. const sel = document.getElementById('mangle-modal-chain-select');
  5502. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5503. const customInput = document.getElementById('mangle-modal-custom-input');
  5504. const chainInput = document.getElementById('mangle-modal-chain');
  5505. if (!sel || !chainInput) return;
  5506. if (sel.value === '__custom__') {
  5507. if (customWrap) customWrap.classList.remove('hidden');
  5508. if (customInput) {
  5509. customInput.value = '';
  5510. customInput.focus();
  5511. }
  5512. chainInput.value = '';
  5513. } else {
  5514. if (customWrap) customWrap.classList.add('hidden');
  5515. chainInput.value = sel.value;
  5516. }
  5517. handleMangleChainChange();
  5518. }
  5519. function syncMangleCustomChainInput() {
  5520. const customInput = document.getElementById('mangle-modal-custom-input');
  5521. const chainInput = document.getElementById('mangle-modal-chain');
  5522. if (customInput && chainInput) {
  5523. chainInput.value = customInput.value.trim();
  5524. }
  5525. handleMangleChainChange();
  5526. }
  5527. function handleMangleChainChange() {
  5528. const chainInput = document.getElementById('mangle-modal-chain');
  5529. const rawChain = (chainInput?.value || 'prerouting').trim();
  5530. const chain = rawChain.toLowerCase();
  5531. const sel = document.getElementById('mangle-modal-chain-select');
  5532. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5533. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5534. sel.value = chain;
  5535. }
  5536. }
  5537. const hintEl = document.getElementById('mangle-chain-hint');
  5538. if (hintEl) {
  5539. if (chain === 'prerouting') {
  5540. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5541. } else if (chain === 'input') {
  5542. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5543. } else if (chain === 'forward') {
  5544. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5545. } else if (chain === 'output') {
  5546. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5547. } else if (chain === 'postrouting') {
  5548. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5549. } else {
  5550. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5551. }
  5552. }
  5553. const rowIn = document.getElementById('mangle-row-iniface');
  5554. const rowInList = document.getElementById('mangle-row-inifacelist');
  5555. const rowOut = document.getElementById('mangle-row-outiface');
  5556. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5557. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5558. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5559. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5560. if (chain === 'prerouting' || chain === 'input') {
  5561. if (rowIn) rowIn.classList.remove('hidden');
  5562. if (rowInList) rowInList.classList.remove('hidden');
  5563. if (rowOut) rowOut.classList.add('hidden');
  5564. if (rowOutList) rowOutList.classList.add('hidden');
  5565. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5566. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5567. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5568. } else if (chain === 'output' || chain === 'postrouting') {
  5569. if (rowIn) rowIn.classList.add('hidden');
  5570. if (rowInList) rowInList.classList.add('hidden');
  5571. if (rowOut) rowOut.classList.remove('hidden');
  5572. if (rowOutList) rowOutList.classList.remove('hidden');
  5573. if (rowInBridge) rowInBridge.classList.add('hidden');
  5574. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5575. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5576. } else {
  5577. if (rowIn) rowIn.classList.remove('hidden');
  5578. if (rowInList) rowInList.classList.remove('hidden');
  5579. if (rowOut) rowOut.classList.remove('hidden');
  5580. if (rowOutList) rowOutList.classList.remove('hidden');
  5581. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5582. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5583. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5584. }
  5585. checkMangleActionChainCompatibility();
  5586. toggleMangleActionFields();
  5587. }
  5588. function checkMangleActionChainCompatibility() {
  5589. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5590. const chain = rawChain.toLowerCase();
  5591. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5592. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5593. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5594. if (!warnBox || !warnMsg) return;
  5595. let msg = '';
  5596. if (action === 'set-priority' && chain !== 'postrouting') {
  5597. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5598. }
  5599. if (msg) {
  5600. warnMsg.textContent = msg;
  5601. warnBox.classList.remove('hidden');
  5602. } else {
  5603. warnBox.classList.add('hidden');
  5604. }
  5605. }
  5606. function toggleMangleActionFields() {
  5607. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5608. // Hide all dynamic rows first
  5609. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5610. const el = document.getElementById(`mangle-row-${id}`);
  5611. if (el) el.classList.add('hidden');
  5612. });
  5613. const jumpBox = document.getElementById('mangle-action-jump-box');
  5614. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5615. if (jumpBox) jumpBox.classList.add('hidden');
  5616. if (addrBox) addrBox.classList.add('hidden');
  5617. // Activate matching rows
  5618. if (act === 'mark-connection') {
  5619. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5620. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5621. } else if (act === 'mark-routing') {
  5622. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5623. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5624. } else if (act === 'mark-packet') {
  5625. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5626. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5627. } else if (act === 'change-mss') {
  5628. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5629. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5630. } else if (act === 'change-dscp') {
  5631. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5632. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5633. } else if (act === 'change-ttl') {
  5634. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5635. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5636. } else if (act === 'set-priority') {
  5637. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5638. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5639. } else if (act === 'route') {
  5640. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5641. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5642. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5643. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5644. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5645. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5646. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5647. } else if (act === 'jump') {
  5648. if (jumpBox) jumpBox.classList.remove('hidden');
  5649. } else if (act.includes('address-list') || act.includes('address list')) {
  5650. if (addrBox) addrBox.classList.remove('hidden');
  5651. }
  5652. if (act === 'log') {
  5653. const logEl = document.getElementById('mangle-modal-log');
  5654. if (logEl) logEl.checked = true;
  5655. toggleMangleField('logprefix', true);
  5656. }
  5657. checkMangleActionChainCompatibility();
  5658. }
  5659. function toggleMangleLogPrefix() {
  5660. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5661. toggleMangleField('logprefix', !!isLog);
  5662. }
  5663. const allMangleFieldKeys = [
  5664. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5665. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5666. 'routingmark', 'conntype', 'cs', 'natstate',
  5667. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5668. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5669. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5670. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5671. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5672. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5673. ];
  5674. function openAddMangleModal() {
  5675. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5676. switchMangleRuleTab('general');
  5677. const badge = document.getElementById('mangle-modal-badge');
  5678. if (badge) badge.innerText = 'New...';
  5679. document.getElementById('mangle-modal-id').value = '';
  5680. document.getElementById('mangle-modal-family').value = '4';
  5681. document.getElementById('mangle-modal-enabled').checked = true;
  5682. document.getElementById('mangle-modal-comment').value = '';
  5683. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5684. populateChainDropdown('mangle', 'prerouting');
  5685. handleMangleChainChange();
  5686. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5687. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5688. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5689. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5690. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5691. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5692. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5693. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5694. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5695. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5696. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5697. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5698. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5699. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5700. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5701. populateInterfaceSelect('mangle-val-iniface');
  5702. populateInterfaceSelect('mangle-val-outiface');
  5703. populateAddressListSelect('mangle-val-srclist');
  5704. populateAddressListSelect('mangle-val-dstlist');
  5705. populateGeoIPSelect('mangle-val-srcgeo');
  5706. populateGeoIPSelect('mangle-val-dstgeo');
  5707. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5708. resetMangleCounterDisplay();
  5709. toggleMangleActionFields();
  5710. document.getElementById('mangle-modal').classList.remove('hidden');
  5711. }
  5712. function openEditMangleModal(id) {
  5713. id = decodeURIComponent(id);
  5714. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5715. if (!r) return;
  5716. switchMangleRuleTab('general');
  5717. const badge = document.getElementById('mangle-modal-badge');
  5718. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5719. document.getElementById('mangle-modal-id').value = r.id;
  5720. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5721. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5722. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5723. const mangleChain = r.chain || 'prerouting';
  5724. document.getElementById('mangle-modal-chain').value = mangleChain;
  5725. populateChainDropdown('mangle', mangleChain);
  5726. handleMangleChainChange();
  5727. setFirewallActionSelection('mangle', r.action || 'accept');
  5728. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5729. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5730. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5731. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5732. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5733. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5734. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5735. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5736. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5737. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5738. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5739. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5740. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5741. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5742. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5743. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5744. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5745. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5746. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5747. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5748. setMangleFieldVal('src', r.src_address, true);
  5749. setMangleFieldVal('dst', r.dst_address, true);
  5750. setMangleFieldVal('srclist', r.src_address_list, true);
  5751. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5752. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5753. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5754. if (r.protocol && r.protocol !== 'all') {
  5755. setMangleFieldVal('proto', r.protocol, true);
  5756. } else {
  5757. toggleMangleField('proto', false);
  5758. }
  5759. setMangleFieldVal('sport', r.src_port, true);
  5760. setMangleFieldVal('dport', r.dst_port, true);
  5761. setMangleFieldVal('anyport', r.any_port, true);
  5762. setMangleFieldVal('iniface', r.in_interface, true);
  5763. setMangleFieldVal('outiface', r.out_interface, true);
  5764. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5765. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5766. setMangleFieldVal('pktmark', r.packet_mark, true);
  5767. setMangleFieldVal('connmark', r.connection_mark, true);
  5768. setMangleFieldVal('routingmark', r.routing_mark, true);
  5769. setMangleFieldVal('conntype', r.connection_type, false);
  5770. // Connection State
  5771. const states = r.connection_state || [];
  5772. if (states.length > 0) {
  5773. toggleMangleField('cs', true);
  5774. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5775. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5776. if (el) el.checked = states.includes(s);
  5777. });
  5778. } else {
  5779. toggleMangleField('cs', false);
  5780. }
  5781. // Connection NAT State
  5782. const natStates = r.connection_nat_state || [];
  5783. if (natStates.length > 0) {
  5784. toggleMangleField('natstate', true);
  5785. ['srcnat', 'dstnat'].forEach(s => {
  5786. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5787. if (el) el.checked = natStates.includes(s);
  5788. });
  5789. } else {
  5790. toggleMangleField('natstate', false);
  5791. }
  5792. // Advanced tab fields
  5793. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5794. setMangleFieldVal('content', r.content, false);
  5795. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5796. setMangleFieldVal('connrate', r.connection_rate, false);
  5797. setMangleFieldVal('pcc', r.pcc, false);
  5798. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5799. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5800. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5801. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5802. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5803. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5804. setMangleFieldVal('tlshost', r.tls_host, false);
  5805. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5806. setMangleFieldVal('priority', r.priority, false);
  5807. setMangleFieldVal('dscp', r.dscp, false);
  5808. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5809. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5810. setMangleFieldVal('pktsize', r.packet_size, false);
  5811. setMangleFieldVal('random', r.random, false);
  5812. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5813. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5814. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5815. setMangleFieldVal('ttl', r.ttl, false);
  5816. // Extra tab fields
  5817. setMangleFieldVal('nth', r.nth, false);
  5818. setMangleFieldVal('connlimit', r.connection_limit, false);
  5819. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5820. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5821. setMangleFieldVal('hotspot', r.hotspot, false);
  5822. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5823. setMangleFieldVal('limit', r.limit, false);
  5824. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5825. setMangleFieldVal('time', r.time, false);
  5826. setMangleFieldVal('psd', r.psd, false);
  5827. // Action fields
  5828. if (r.jump_target) {
  5829. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5830. if (jtEl) jtEl.value = r.jump_target;
  5831. }
  5832. if (r.address_list) {
  5833. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5834. if (alEl) alEl.value = r.address_list;
  5835. }
  5836. if (r.address_list_timeout) {
  5837. const toEl = document.getElementById('mangle-modal-action-timeout');
  5838. if (toEl) toEl.value = r.address_list_timeout;
  5839. }
  5840. setMangleFieldVal('logprefix', r.log_prefix, false);
  5841. // Statistics
  5842. const bEl = document.getElementById('mangle-stat-bytes');
  5843. const pEl = document.getElementById('mangle-stat-packets');
  5844. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5845. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5846. state.mangleLastBytes = r.bytes || 0;
  5847. state.mangleLastPackets = r.packets || 0;
  5848. state.mangleLastTimestamp = Date.now();
  5849. state.mangleStatRateHistory = new Array(30).fill(0);
  5850. state.mangleStatPktHistory = new Array(30).fill(0);
  5851. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5852. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5853. toggleMangleActionFields();
  5854. document.getElementById('mangle-modal').classList.remove('hidden');
  5855. }
  5856. function closeMangleModal() {
  5857. stopMangleStatPolling();
  5858. document.getElementById('mangle-modal').classList.add('hidden');
  5859. }
  5860. function copyMangleRule() {
  5861. document.getElementById('mangle-modal-id').value = '';
  5862. const badge = document.getElementById('mangle-modal-badge');
  5863. if (badge) badge.innerText = 'New...';
  5864. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5865. }
  5866. function resetMangleCounterDisplay() {
  5867. state.mangleStatRateHistory = new Array(30).fill(0);
  5868. state.mangleStatPktHistory = new Array(30).fill(0);
  5869. state.mangleLastBytes = 0;
  5870. state.mangleLastPackets = 0;
  5871. state.mangleLastTimestamp = Date.now();
  5872. const bEl = document.getElementById('mangle-stat-bytes');
  5873. const pEl = document.getElementById('mangle-stat-packets');
  5874. const rEl = document.getElementById('mangle-stat-rate');
  5875. const prEl = document.getElementById('mangle-stat-pktrate');
  5876. if (bEl) bEl.value = '0 B';
  5877. if (pEl) pEl.value = '0';
  5878. if (rEl) rEl.value = '0 bps';
  5879. if (prEl) prEl.value = '0 p/s';
  5880. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5881. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5882. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5883. }
  5884. async function applyMangleRule(closeAfter = false) {
  5885. const id = document.getElementById('mangle-modal-id').value;
  5886. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5887. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5888. const chainLower = chain.toLowerCase();
  5889. const action = document.getElementById('mangle-modal-action').value;
  5890. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5891. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5892. const src = getMangleFieldVal('src', true);
  5893. const dst = getMangleFieldVal('dst', true);
  5894. const srclist = getMangleFieldVal('srclist', true);
  5895. const dstlist = getMangleFieldVal('dstlist', true);
  5896. const srcgeo = getMangleFieldVal('srcgeo', true);
  5897. const dstgeo = getMangleFieldVal('dstgeo', true);
  5898. const proto = getMangleFieldVal('proto', true);
  5899. const sport = getMangleFieldVal('sport', true);
  5900. const dport = getMangleFieldVal('dport', true);
  5901. const anyport = getMangleFieldVal('anyport', true);
  5902. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5903. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5904. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5905. }
  5906. let iniface = getMangleFieldVal('iniface', true);
  5907. let outiface = getMangleFieldVal('outiface', true);
  5908. let inifacelist = getMangleFieldVal('inifacelist', true);
  5909. let outifacelist = getMangleFieldVal('outifacelist', true);
  5910. if (chainLower === 'prerouting' || chainLower === 'input') {
  5911. outiface = '';
  5912. outifacelist = '';
  5913. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5914. iniface = '';
  5915. inifacelist = '';
  5916. }
  5917. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5918. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5919. switchMangleRuleTab('general');
  5920. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5921. return;
  5922. }
  5923. const pktmark = getMangleFieldVal('pktmark', true);
  5924. const connmark = getMangleFieldVal('connmark', true);
  5925. const routingmark = getMangleFieldVal('routingmark', true);
  5926. const conntype = getMangleFieldVal('conntype', false);
  5927. const states = [];
  5928. const csBox = document.getElementById('mangle-field-cs');
  5929. if (csBox && !csBox.classList.contains('hidden')) {
  5930. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5931. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5932. });
  5933. }
  5934. const natStates = [];
  5935. const natBox = document.getElementById('mangle-field-natstate');
  5936. if (natBox && !natBox.classList.contains('hidden')) {
  5937. ['srcnat', 'dstnat'].forEach(s => {
  5938. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5939. });
  5940. }
  5941. const payload = {
  5942. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5943. id,
  5944. chain,
  5945. action,
  5946. protocol: proto || 'all',
  5947. src_address: src,
  5948. dst_address: dst,
  5949. src_port: sport,
  5950. dst_port: dport,
  5951. any_port: anyport,
  5952. in_interface: iniface,
  5953. out_interface: outiface,
  5954. in_interface_list: inifacelist,
  5955. out_interface_list: outifacelist,
  5956. packet_mark: pktmark,
  5957. connection_mark: connmark,
  5958. routing_mark: routingmark,
  5959. connection_type: conntype,
  5960. connection_state: states,
  5961. connection_nat_state: natStates,
  5962. src_address_list: srclist,
  5963. dst_address_list: dstlist,
  5964. src_geoip: srcgeo,
  5965. dst_geoip: dstgeo,
  5966. comment,
  5967. disabled: !enabled,
  5968. // Advanced tab
  5969. content: getMangleFieldVal('content', false),
  5970. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5971. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5972. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5973. ipsec_policy: getMangleFieldVal('ipsec', false),
  5974. dscp: getMangleFieldVal('dscp', false),
  5975. tcp_mss: getMangleFieldVal('tcpmss', false),
  5976. tos: document.getElementById('mangle-val-tos')?.value || '',
  5977. packet_size: getMangleFieldVal('pktsize', false),
  5978. random: getMangleFieldVal('random', false),
  5979. tcp_flags: getMangleFieldVal('tcpflags', false),
  5980. icmp_options: getMangleFieldVal('icmpoptions', false),
  5981. ttl: getMangleFieldVal('ttl', false),
  5982. // Extra tab
  5983. nth: getMangleFieldVal('nth', false),
  5984. connection_limit: getMangleFieldVal('connlimit', false),
  5985. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5986. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5987. ip_fragment: getMangleFieldVal('ipfragment', false),
  5988. limit: getMangleFieldVal('limit', false),
  5989. time: getMangleFieldVal('time', false),
  5990. // Action tab
  5991. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5992. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5993. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5994. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5995. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5996. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5997. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5998. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5999. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  6000. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  6001. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  6002. log: document.getElementById('mangle-modal-log')?.checked || false,
  6003. log_prefix: getMangleFieldVal('logprefix', false)
  6004. };
  6005. try {
  6006. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  6007. method: 'POST',
  6008. headers: { 'Content-Type': 'application/json' },
  6009. body: JSON.stringify(payload)
  6010. });
  6011. if (res.ok) {
  6012. const data = await res.json();
  6013. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  6014. loadFirewall(false);
  6015. if (closeAfter) {
  6016. closeMangleModal();
  6017. } else {
  6018. if (data.id) {
  6019. document.getElementById('mangle-modal-id').value = data.id;
  6020. const badge = document.getElementById('mangle-modal-badge');
  6021. if (badge) badge.innerText = `#${data.id}`;
  6022. }
  6023. }
  6024. } else {
  6025. const err = await res.json();
  6026. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  6027. }
  6028. } catch (err) {
  6029. showToast('Error', err.message, 'error');
  6030. }
  6031. }
  6032. function submitSaveMangleRule(e) {
  6033. if (e && e.preventDefault) e.preventDefault();
  6034. return applyMangleRule(true);
  6035. }
  6036. function startMangleStatPolling() {
  6037. stopMangleStatPolling();
  6038. pollMangleRuleStats();
  6039. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  6040. }
  6041. function stopMangleStatPolling() {
  6042. if (state.mangleStatInterval) {
  6043. clearInterval(state.mangleStatInterval);
  6044. state.mangleStatInterval = null;
  6045. }
  6046. }
  6047. async function pollMangleRuleStats() {
  6048. const id = document.getElementById('mangle-modal-id')?.value;
  6049. if (!id) {
  6050. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  6051. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  6052. return;
  6053. }
  6054. try {
  6055. const res = await fetch(`${API_BASE}/firewall/mangle`);
  6056. if (!res.ok) return;
  6057. const rules = await res.json();
  6058. const r = rules.find(x => x.id === id);
  6059. if (!r) return;
  6060. const now = Date.now();
  6061. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  6062. state.mangleLastTimestamp = now;
  6063. const curBytes = r.bytes || 0;
  6064. const curPackets = r.packets || 0;
  6065. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  6066. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  6067. state.mangleLastBytes = curBytes;
  6068. state.mangleLastPackets = curPackets;
  6069. const rateBps = Math.round((deltaBytes * 8) / dt);
  6070. const ratePkt = Math.round(deltaPkts / dt);
  6071. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  6072. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  6073. state.mangleStatRateHistory.push(rateBps);
  6074. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  6075. state.mangleStatPktHistory.push(ratePkt);
  6076. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  6077. const bEl = document.getElementById('mangle-stat-bytes');
  6078. const pEl = document.getElementById('mangle-stat-packets');
  6079. const rEl = document.getElementById('mangle-stat-rate');
  6080. const prEl = document.getElementById('mangle-stat-pktrate');
  6081. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  6082. if (pEl) pEl.value = curPackets.toLocaleString();
  6083. if (rEl) rEl.value = formatBps(rateBps);
  6084. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  6085. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  6086. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  6087. } catch (e) {
  6088. console.error('Error polling Mangle rule stats', e);
  6089. }
  6090. }
  6091. async function moveMangleRule(id, dir) {
  6092. id = decodeURIComponent(id);
  6093. try {
  6094. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  6095. method: 'POST',
  6096. headers: { 'Content-Type': 'application/json' },
  6097. body: JSON.stringify({ direction: dir })
  6098. });
  6099. if (!res.ok) throw new Error(await responseError(res));
  6100. await loadFirewall(false);
  6101. } catch (err) {
  6102. showToast('Error', err.message, 'error');
  6103. }
  6104. }
  6105. async function toggleMangleRuleState(id, disabled) {
  6106. id = decodeURIComponent(id);
  6107. try {
  6108. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6109. method: 'POST',
  6110. headers: { 'Content-Type': 'application/json' },
  6111. body: JSON.stringify({ disabled })
  6112. });
  6113. if (!res.ok) throw new Error(await responseError(res));
  6114. await loadFirewall(false);
  6115. } catch (err) {
  6116. showToast('Error', err.message, 'error');
  6117. }
  6118. }
  6119. async function deleteMangleRule(id) {
  6120. id = decodeURIComponent(id);
  6121. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6122. try {
  6123. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6124. if (!res.ok) throw new Error(await responseError(res));
  6125. {
  6126. showToast('Deleted', 'Mangle rule removed', 'success');
  6127. loadFirewall(false);
  6128. }
  6129. } catch (err) {
  6130. showToast('Error', err.message, 'error');
  6131. }
  6132. }
  6133. // ----------------- Address Lists -----------------
  6134. function renderAddressLists() {
  6135. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6136. const tbody = document.getElementById('addrlist-table-body');
  6137. const empty = document.getElementById('addrlist-empty');
  6138. if (!tbody) return;
  6139. tbody.innerHTML = '';
  6140. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6141. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6142. // Update filter select
  6143. const sel = document.getElementById('addrlist-filter-name');
  6144. if (sel) {
  6145. const cur = sel.value;
  6146. sel.innerHTML = '<option value="">All Lists</option>';
  6147. const set = new Set((state.addressLists || []).map(a => a.name));
  6148. set.forEach(n => {
  6149. const opt = document.createElement('option');
  6150. opt.value = n;
  6151. opt.innerText = n;
  6152. if (n === cur) opt.selected = true;
  6153. sel.appendChild(opt);
  6154. });
  6155. }
  6156. if (entries.length === 0) {
  6157. empty?.classList.remove('hidden');
  6158. return;
  6159. }
  6160. empty?.classList.add('hidden');
  6161. entries.forEach((raw, idx) => {
  6162. const e = safeFirewallRow(raw);
  6163. const tr = document.createElement('tr');
  6164. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6165. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6166. tr.innerHTML = `
  6167. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6168. <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>
  6169. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6170. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6171. <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>
  6172. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6173. ${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>
  6174. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6175. `}
  6176. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6177. </td>
  6178. `;
  6179. tbody.appendChild(tr);
  6180. });
  6181. populateCommonAddrListDatalist();
  6182. }
  6183. function openAddAddrListModal() {
  6184. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6185. document.getElementById('addrlist-modal-id').value = '';
  6186. document.getElementById('addrlist-modal-name').value = '';
  6187. document.getElementById('addrlist-modal-addr').value = '';
  6188. document.getElementById('addrlist-modal-comment').value = '';
  6189. document.getElementById('addrlist-modal-disabled').checked = false;
  6190. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6191. if (submitBtn) submitBtn.innerText = 'Add to List';
  6192. document.getElementById('addrlist-modal').classList.remove('hidden');
  6193. }
  6194. function openEditAddrListModal(id) {
  6195. id = decodeURIComponent(id);
  6196. const e = (state.addressLists || []).find(item => item.id === id);
  6197. if (!e) return;
  6198. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6199. document.getElementById('addrlist-modal-id').value = e.id;
  6200. document.getElementById('addrlist-modal-name').value = e.name;
  6201. document.getElementById('addrlist-modal-addr').value = e.address;
  6202. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6203. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6204. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6205. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6206. document.getElementById('addrlist-modal').classList.remove('hidden');
  6207. }
  6208. function closeAddrListModal() {
  6209. document.getElementById('addrlist-modal').classList.add('hidden');
  6210. }
  6211. async function submitSaveAddrList(e) {
  6212. e.preventDefault();
  6213. const id = document.getElementById('addrlist-modal-id').value;
  6214. const name = document.getElementById('addrlist-modal-name').value.trim();
  6215. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6216. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6217. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6218. try {
  6219. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6220. method: 'POST',
  6221. headers: { 'Content-Type': 'application/json' },
  6222. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6223. });
  6224. if (res.ok) {
  6225. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6226. closeAddrListModal();
  6227. loadFirewall(false);
  6228. } else {
  6229. const err = await res.json();
  6230. showToast('Error', err.message || 'Failed to save address list', 'error');
  6231. }
  6232. } catch (err) {
  6233. showToast('Error', err.message, 'error');
  6234. }
  6235. }
  6236. async function toggleAddrListState(id, disabled) {
  6237. id = decodeURIComponent(id);
  6238. try {
  6239. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6240. method: 'POST',
  6241. headers: { 'Content-Type': 'application/json' },
  6242. body: JSON.stringify({ disabled })
  6243. });
  6244. if (res.ok) {
  6245. loadFirewall(false);
  6246. }
  6247. } catch (err) {
  6248. showToast('Error', err.message, 'error');
  6249. }
  6250. }
  6251. async function deleteAddrList(id) {
  6252. id = decodeURIComponent(id);
  6253. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6254. try {
  6255. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6256. if (res.ok) {
  6257. showToast('Deleted', 'Address list item removed', 'info');
  6258. loadFirewall(false);
  6259. }
  6260. } catch (err) {
  6261. showToast('Error', err.message, 'error');
  6262. }
  6263. }
  6264. // ----------------- Geo-Location IP Management -----------------
  6265. async function loadGeoIP() {
  6266. try {
  6267. const [statusRes, countriesRes] = await Promise.all([
  6268. fetch(`${API_BASE}/firewall/geoip/status`),
  6269. fetch(`${API_BASE}/firewall/geoip/countries`)
  6270. ]);
  6271. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6272. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6273. updateGeoHeader();
  6274. renderGeoCountries();
  6275. } catch (err) {
  6276. console.error('Failed to load GeoIP:', err);
  6277. }
  6278. }
  6279. function getGeoUsageMap() {
  6280. const usage = {};
  6281. const checkRule = (r, type) => {
  6282. ['src_geoip', 'dst_geoip'].forEach(field => {
  6283. let val = (r && r[field]) || '';
  6284. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6285. if (code) {
  6286. if (!usage[code]) usage[code] = [];
  6287. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6288. if (!usage[code].includes(label)) usage[code].push(label);
  6289. }
  6290. });
  6291. };
  6292. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6293. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6294. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6295. return usage;
  6296. }
  6297. function updateGeoHeader() {
  6298. const s = state.geoStatus || {};
  6299. const statusBadge = document.getElementById('geo-status-badge');
  6300. if (statusBadge) {
  6301. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6302. statusBadge.className = s.auto_update
  6303. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6304. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6305. }
  6306. const intervalLabel = document.getElementById('geo-interval-label');
  6307. if (intervalLabel) {
  6308. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6309. }
  6310. const usageMap = getGeoUsageMap();
  6311. const inUseCount = Object.keys(usageMap).length;
  6312. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6313. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6314. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6315. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6316. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6317. if (lastSyncEl) {
  6318. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6319. const d = new Date(s.last_updated);
  6320. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6321. } else {
  6322. lastSyncEl.innerText = 'Never (Sync Pending)';
  6323. }
  6324. }
  6325. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6326. if (nextSyncEl) {
  6327. if (s.next_update && !s.next_update.startsWith('0001')) {
  6328. const d = new Date(s.next_update);
  6329. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6330. } else {
  6331. nextSyncEl.innerText = '-';
  6332. }
  6333. }
  6334. const badge = document.getElementById('fw-badge-geo');
  6335. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6336. }
  6337. function renderGeoCountries() {
  6338. const tbody = document.getElementById('geo-table-body');
  6339. const empty = document.getElementById('geo-empty');
  6340. if (!tbody) return;
  6341. tbody.innerHTML = '';
  6342. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6343. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6344. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6345. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6346. const usageMap = getGeoUsageMap();
  6347. const countries = (state.geoCountries || []).filter(c => {
  6348. const isUsed = !!usageMap[c.code];
  6349. if (inUseOnly && !isUsed) return false;
  6350. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6351. if (continent && c.continent !== continent) return false;
  6352. if (q) {
  6353. const matchCode = c.code.toLowerCase().includes(q);
  6354. const matchName = c.name.toLowerCase().includes(q);
  6355. if (!matchCode && !matchName) return false;
  6356. }
  6357. return true;
  6358. });
  6359. if (countries.length === 0) {
  6360. empty?.classList.remove('hidden');
  6361. return;
  6362. }
  6363. empty?.classList.add('hidden');
  6364. countries.forEach(c => {
  6365. const tr = document.createElement('tr');
  6366. const isUsed = !!usageMap[c.code];
  6367. const rulesUsing = usageMap[c.code] || [];
  6368. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6369. let statusHtml = '';
  6370. if (isUsed) {
  6371. 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>`;
  6372. } else if (c.subnet_count > 0) {
  6373. 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>';
  6374. } else {
  6375. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6376. }
  6377. tr.innerHTML = `
  6378. <td class="py-2.5 px-3 text-center">
  6379. <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'}">
  6380. ${c.code}
  6381. </span>
  6382. </td>
  6383. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6384. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6385. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6386. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6387. </td>
  6388. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6389. <td class="py-2.5 px-3">
  6390. ${statusHtml}
  6391. </td>
  6392. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6393. <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>
  6394. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6395. </td>
  6396. `;
  6397. tbody.appendChild(tr);
  6398. });
  6399. }
  6400. function quickFilterGeo(preset) {
  6401. const searchInput = document.getElementById('geo-search-input');
  6402. const continentSel = document.getElementById('geo-continent-filter');
  6403. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6404. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6405. if (searchInput) searchInput.value = '';
  6406. if (continentSel) continentSel.value = '';
  6407. if (inUseCheck) inUseCheck.checked = false;
  6408. if (cachedCheck) cachedCheck.checked = false;
  6409. if (preset === 'GR') {
  6410. if (searchInput) searchInput.value = 'Greece';
  6411. } else if (preset === 'Europe') {
  6412. if (continentSel) continentSel.value = 'Europe';
  6413. } else if (preset === 'HIGHRISK') {
  6414. if (searchInput) searchInput.value = 'China';
  6415. }
  6416. renderGeoCountries();
  6417. }
  6418. async function toggleGeoCountry(code, enabled) {
  6419. try {
  6420. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6421. method: 'POST',
  6422. headers: { 'Content-Type': 'application/json' },
  6423. body: JSON.stringify({ enabled })
  6424. });
  6425. if (res.ok) {
  6426. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6427. loadGeoIP();
  6428. } else {
  6429. const err = await res.json();
  6430. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6431. }
  6432. } catch (err) {
  6433. showToast('Error', err.message, 'error');
  6434. }
  6435. }
  6436. async function updateGeoCountry(code) {
  6437. try {
  6438. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6439. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6440. if (res.ok) {
  6441. const data = await res.json();
  6442. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6443. loadGeoIP();
  6444. } else {
  6445. const err = await res.json();
  6446. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6447. }
  6448. } catch (err) {
  6449. showToast('Error', err.message, 'error');
  6450. }
  6451. }
  6452. async function triggerGeoUpdateNow() {
  6453. const spinner = document.getElementById('geo-update-spinner');
  6454. if (spinner) spinner.classList.remove('hidden');
  6455. try {
  6456. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6457. if (res.ok) {
  6458. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6459. setTimeout(() => {
  6460. loadGeoIP();
  6461. if (spinner) spinner.classList.add('hidden');
  6462. }, 2500);
  6463. } else {
  6464. const err = await res.json();
  6465. showToast('Notice', err.message || 'Update in progress', 'info');
  6466. if (spinner) spinner.classList.add('hidden');
  6467. }
  6468. } catch (err) {
  6469. showToast('Error', err.message, 'error');
  6470. if (spinner) spinner.classList.add('hidden');
  6471. }
  6472. }
  6473. async function applyGeoPreset(preset) {
  6474. try {
  6475. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6476. method: 'POST',
  6477. headers: { 'Content-Type': 'application/json' },
  6478. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6479. });
  6480. if (res.ok) {
  6481. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6482. loadGeoIP();
  6483. }
  6484. } catch (err) {
  6485. showToast('Error', err.message, 'error');
  6486. }
  6487. }
  6488. function openGeoIntervalModal() {
  6489. const s = state.geoStatus || {};
  6490. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6491. const sel = document.getElementById('geo-cfg-interval');
  6492. const customBox = document.getElementById('geo-cfg-custom-box');
  6493. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6494. const curHours = s.interval_hours || 24;
  6495. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6496. if (matchOption) {
  6497. sel.value = String(curHours);
  6498. customBox.classList.add('hidden');
  6499. } else {
  6500. sel.value = 'custom';
  6501. customHoursInput.value = curHours;
  6502. customBox.classList.remove('hidden');
  6503. }
  6504. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6505. }
  6506. function closeGeoIntervalModal() {
  6507. document.getElementById('geo-interval-modal').classList.add('hidden');
  6508. }
  6509. function toggleCustomGeoInterval() {
  6510. const val = document.getElementById('geo-cfg-interval').value;
  6511. const customBox = document.getElementById('geo-cfg-custom-box');
  6512. if (val === 'custom') {
  6513. customBox.classList.remove('hidden');
  6514. } else {
  6515. customBox.classList.add('hidden');
  6516. }
  6517. }
  6518. async function submitGeoIntervalSettings(e) {
  6519. e.preventDefault();
  6520. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6521. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6522. let hours = 24;
  6523. if (intervalVal === 'custom') {
  6524. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6525. } else {
  6526. hours = parseInt(intervalVal, 10) || 24;
  6527. }
  6528. try {
  6529. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6530. method: 'POST',
  6531. headers: { 'Content-Type': 'application/json' },
  6532. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6533. });
  6534. if (res.ok) {
  6535. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6536. closeGeoIntervalModal();
  6537. loadGeoIP();
  6538. } else {
  6539. const err = await res.json();
  6540. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6541. }
  6542. } catch (err) {
  6543. showToast('Error', err.message, 'error');
  6544. }
  6545. }
  6546. async function viewGeoSubnets(code, name) {
  6547. if (!name) {
  6548. const found = (state.geoCountries || []).find(x => x.code === code);
  6549. name = found ? found.name : code;
  6550. }
  6551. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6552. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6553. const listEl = document.getElementById('geo-subnets-list');
  6554. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6555. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6556. try {
  6557. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6558. if (res.ok) {
  6559. const data = await res.json();
  6560. const subnets = data.subnets || [];
  6561. if (subnets.length === 0) {
  6562. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6563. } else {
  6564. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6565. }
  6566. } else {
  6567. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6568. }
  6569. } catch (err) {
  6570. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6571. }
  6572. }
  6573. function closeGeoSubnetsModal() {
  6574. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6575. }
  6576. // ----------------- Active Connections Tracking -----------------
  6577. async function loadConnections() {
  6578. try {
  6579. const res = await fetch(`${API_BASE}/firewall/connections`);
  6580. const data = await res.json();
  6581. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6582. state.connections = Array.isArray(data) ? data : [];
  6583. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6584. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6585. renderConnections();
  6586. } catch (err) {
  6587. console.error('Failed to load connections:', err);
  6588. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6589. }
  6590. }
  6591. function renderConnections() {
  6592. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6593. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6594. const tbody = document.getElementById('conns-table-body');
  6595. const empty = document.getElementById('conns-empty');
  6596. if (!tbody) return;
  6597. tbody.innerHTML = '';
  6598. const conns = (state.connections || []).filter(c => {
  6599. if (protoFilter && c.protocol !== protoFilter) return false;
  6600. if (search) {
  6601. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6602. if (!line.includes(search)) return false;
  6603. }
  6604. return true;
  6605. });
  6606. if (conns.length === 0) {
  6607. empty?.classList.remove('hidden');
  6608. return;
  6609. }
  6610. empty?.classList.add('hidden');
  6611. conns.slice(0, 150).forEach(c => {
  6612. const tr = document.createElement('tr');
  6613. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6614. let stateColor = 'text-slate-400';
  6615. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6616. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6617. tr.innerHTML = `
  6618. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6619. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6620. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6621. <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>
  6622. <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>
  6623. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6624. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6625. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6626. <td class="py-2.5 px-3 text-right font-sans">
  6627. ${['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>` : ''}
  6628. </td>
  6629. `;
  6630. tbody.appendChild(tr);
  6631. });
  6632. }
  6633. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6634. try {
  6635. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6636. method: 'POST',
  6637. headers: { 'Content-Type': 'application/json' },
  6638. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6639. });
  6640. if (res.ok) {
  6641. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6642. loadConnections();
  6643. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6644. } catch (err) {
  6645. showToast('Error', err.message, 'error');
  6646. }
  6647. }
  6648. async function resetFirewallCounters() {
  6649. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6650. try {
  6651. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6652. if (res.ok) {
  6653. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6654. loadFirewall(false);
  6655. }
  6656. } catch (err) {
  6657. showToast('Error', err.message, 'error');
  6658. }
  6659. }
  6660. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6661. function switchRoutesSubTab(tab) {
  6662. state.routesSubTab = tab;
  6663. const tabs = ['routes', 'rules', 'tables'];
  6664. tabs.forEach(t => {
  6665. const panel = document.getElementById(`routes-subtab-${t}`);
  6666. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6667. if (panel) {
  6668. if (t === tab) panel.classList.remove('hidden');
  6669. else panel.classList.add('hidden');
  6670. }
  6671. if (btn) {
  6672. if (t === tab) {
  6673. 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';
  6674. } else {
  6675. 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';
  6676. }
  6677. }
  6678. });
  6679. setTimeout(initTableSorting, 50);
  6680. }
  6681. async function loadRoutes() {
  6682. try {
  6683. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6684. fetch(`${API_BASE}/routes`),
  6685. fetch(`${API_BASE}/routing/rules`),
  6686. fetch(`${API_BASE}/routing/tables`)
  6687. ]);
  6688. if (routesRes.ok) state.routes = await routesRes.json();
  6689. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6690. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6691. const bRoutes = document.getElementById('routes-badge-routes');
  6692. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6693. const showSystem = document.getElementById('prule-show-system')?.checked;
  6694. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6695. const bRules = document.getElementById('routes-badge-rules');
  6696. if (bRules) bRules.innerText = userRules.length;
  6697. const bTables = document.getElementById('routes-badge-tables');
  6698. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6699. const bRoutesCount = document.getElementById('badge-routes-count');
  6700. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6701. renderRoutesList();
  6702. renderPolicyRules();
  6703. renderRoutingTables();
  6704. } catch (err) {
  6705. console.error('Failed to load routing:', err);
  6706. }
  6707. }
  6708. function getRouteProtocolBadge(proto) {
  6709. const p = (proto || 'static').toLowerCase();
  6710. switch (p) {
  6711. case 'bgp':
  6712. 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>`;
  6713. case 'ibgp':
  6714. 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>`;
  6715. case 'ospf':
  6716. 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>`;
  6717. case 'rip':
  6718. 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>`;
  6719. case 'babel':
  6720. 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>`;
  6721. case 'eigrp':
  6722. 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>`;
  6723. case 'static':
  6724. 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>`;
  6725. case 'connected':
  6726. 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>`;
  6727. case 'dhcp':
  6728. 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>`;
  6729. case 'multicast':
  6730. 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>`;
  6731. default:
  6732. 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>`;
  6733. }
  6734. }
  6735. function renderRoutesList() {
  6736. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6737. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6738. const tbody = document.getElementById('routes-table-body');
  6739. const empty = document.getElementById('routes-empty');
  6740. if (!tbody) return;
  6741. // Update table filter select
  6742. const sel = document.getElementById('routes-filter-table');
  6743. if (sel) {
  6744. const cur = sel.value;
  6745. sel.innerHTML = '<option value="">All Tables</option>';
  6746. (state.routingTables || []).forEach(t => {
  6747. const opt = document.createElement('option');
  6748. opt.value = t.name;
  6749. opt.innerText = t.name;
  6750. if (t.name === cur) opt.selected = true;
  6751. sel.appendChild(opt);
  6752. });
  6753. }
  6754. const routes = (state.routes || []).filter(r => {
  6755. if (tableFilter && r.routing_table !== tableFilter) return false;
  6756. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6757. if (typeFilter === 'multicast' && !r.multicast) return false;
  6758. if (typeFilter === 'static' && !r.static) return false;
  6759. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6760. if (typeFilter === 'connected' && !r.connect) return false;
  6761. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6762. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6763. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6764. return true;
  6765. });
  6766. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6767. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6768. let summaryText = `${routes.length} Routes`;
  6769. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6770. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6771. const badgeEl = document.getElementById('routes-count-badge');
  6772. if (badgeEl) badgeEl.innerText = summaryText;
  6773. if (routes.length === 0) {
  6774. empty?.classList.remove('hidden');
  6775. tbody.innerHTML = '';
  6776. return;
  6777. }
  6778. empty?.classList.add('hidden');
  6779. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r =>
  6780. `${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)}`
  6781. ).join(';');
  6782. if (tbody.dataset.sig === sig) {
  6783. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6784. }
  6785. tbody.dataset.sig = sig;
  6786. tbody.innerHTML = '';
  6787. routes.forEach(r => {
  6788. const tr = document.createElement('tr');
  6789. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6790. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6791. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6792. let flags = '';
  6793. if (r.dynamic) flags += 'D';
  6794. if (r.active) flags += 'A';
  6795. if (r.connect) flags += 'C';
  6796. if (r.static) flags += 'S';
  6797. if (r.ecmp) flags += 'E';
  6798. if (r.multicast) flags += 'M';
  6799. if (r.disabled) flags += 'X';
  6800. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6801. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6802. if (r.check_gateway === 'internet') {
  6803. if (r.health_status === 'online') {
  6804. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6805. healthCell = `
  6806. <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)">
  6807. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6808. <span>Internet OK (${ms}ms)</span>
  6809. </span>
  6810. `;
  6811. } else if (r.health_status === 'offline') {
  6812. healthCell = `
  6813. <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.">
  6814. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6815. <span>Internet Down</span>
  6816. </span>
  6817. `;
  6818. } else {
  6819. healthCell = `
  6820. <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">
  6821. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6822. <span>Checking...</span>
  6823. </span>
  6824. `;
  6825. }
  6826. } else if (r.check_gateway === 'ping') {
  6827. if (r.health_status === 'online') {
  6828. healthCell = `
  6829. <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">
  6830. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6831. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6832. </span>
  6833. `;
  6834. } else if (r.health_status === 'offline') {
  6835. healthCell = `
  6836. <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">
  6837. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6838. <span>Gateway Dead</span>
  6839. </span>
  6840. `;
  6841. }
  6842. }
  6843. const flagDescriptions = [];
  6844. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6845. if (r.active) flagDescriptions.push('Active (A)');
  6846. if (r.connect) flagDescriptions.push('Connected (C)');
  6847. if (r.static) flagDescriptions.push('Static (S)');
  6848. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6849. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6850. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6851. tr.innerHTML = `
  6852. <td class="py-2.5 px-3 text-center">
  6853. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6854. 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')
  6855. }" title="Flags: ${flagDescriptions.join(', ')}">
  6856. ${flags || '-'}
  6857. </span>
  6858. </td>
  6859. <td class="py-2.5 px-3">
  6860. <div class="flex items-center gap-1.5 flex-wrap">
  6861. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6862. ${r.ecmp ? `
  6863. <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)">
  6864. <span>⚡ ECMP</span>
  6865. </span>
  6866. ` : ''}
  6867. ${r.multicast ? `
  6868. <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">
  6869. <span>IGMP</span>
  6870. </span>
  6871. ` : ''}
  6872. </div>
  6873. </td>
  6874. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6875. <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>
  6876. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6877. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6878. <td class="py-2.5 px-3 text-emerald-400 font-mono">${
  6879. (state.sdwanGroups || []).some(g => g.name === r.interface)
  6880. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/70 text-cyan-300 border border-cyan-700/50 font-bold inline-flex items-center gap-1"><span>⚡</span><span>${escapeHtml(r.interface)}</span></span>`
  6881. : (r.interface || '-')
  6882. }</td>
  6883. <td class="py-2.5 px-3">${healthCell}</td>
  6884. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6885. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6886. ${r.static ? `
  6887. <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>
  6888. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6889. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6890. ` : `
  6891. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6892. `}
  6893. </td>
  6894. `;
  6895. tbody.appendChild(tr);
  6896. });
  6897. }
  6898. function openAddRouteModal() {
  6899. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6900. document.getElementById('route-modal-id').value = '';
  6901. document.getElementById('route-modal-old-dst').value = '';
  6902. document.getElementById('route-modal-old-gw').value = '';
  6903. document.getElementById('route-modal-old-distance').value = '';
  6904. document.getElementById('route-modal-old-table').value = '';
  6905. document.getElementById('route-modal-old-iface').value = '';
  6906. const dstInput = document.getElementById('route-modal-dst');
  6907. const gwInput = document.getElementById('route-modal-gw');
  6908. const distInput = document.getElementById('route-modal-distance');
  6909. const ifaceSelect = document.getElementById('route-modal-iface');
  6910. const tableSelect = document.getElementById('route-modal-table');
  6911. const commentInput = document.getElementById('route-modal-comment');
  6912. const disCheck = document.getElementById('route-modal-disabled');
  6913. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6914. dstInput.disabled = false;
  6915. dstInput.value = '0.0.0.0/0';
  6916. gwInput.disabled = false;
  6917. gwInput.value = '';
  6918. distInput.disabled = false;
  6919. distInput.value = '1';
  6920. ifaceSelect.disabled = false;
  6921. tableSelect.disabled = false;
  6922. commentInput.disabled = false;
  6923. commentInput.value = '';
  6924. disCheck.disabled = false;
  6925. disCheck.checked = false;
  6926. if (saveBtn) saveBtn.classList.remove('hidden');
  6927. const checkGw = document.getElementById('route-modal-check-gw');
  6928. if (checkGw) checkGw.value = 'internet';
  6929. const checkTarget = document.getElementById('route-modal-check-target');
  6930. if (checkTarget) checkTarget.value = '1.1.1.1';
  6931. const checkInterval = document.getElementById('route-modal-check-interval');
  6932. if (checkInterval) checkInterval.value = '5';
  6933. const checkThresh = document.getElementById('route-modal-check-threshold');
  6934. if (checkThresh) checkThresh.value = '3';
  6935. toggleRouteCheckModeUI();
  6936. populateInterfaceSelect('route-modal-iface');
  6937. // Populate tables
  6938. tableSelect.innerHTML = '';
  6939. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6940. const opt = document.createElement('option');
  6941. opt.value = t.name;
  6942. opt.innerText = t.name;
  6943. if (t.name === 'main') opt.selected = true;
  6944. tableSelect.appendChild(opt);
  6945. });
  6946. document.getElementById('route-modal').classList.remove('hidden');
  6947. }
  6948. function openEditRouteModal(id) {
  6949. const r = (state.routes || []).find(route => route.id === id);
  6950. if (!r) return;
  6951. const isStatic = !!r.static;
  6952. document.getElementById('route-modal-title').innerText = isStatic
  6953. ? `Edit Route: ${r.dst_address}`
  6954. : `Route Properties (Read Only): ${r.dst_address}`;
  6955. document.getElementById('route-modal-id').value = r.id;
  6956. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6957. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6958. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6959. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6960. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6961. const dstInput = document.getElementById('route-modal-dst');
  6962. const gwInput = document.getElementById('route-modal-gw');
  6963. const distInput = document.getElementById('route-modal-distance');
  6964. const ifaceSelect = document.getElementById('route-modal-iface');
  6965. const tableSelect = document.getElementById('route-modal-table');
  6966. const commentInput = document.getElementById('route-modal-comment');
  6967. const disCheck = document.getElementById('route-modal-disabled');
  6968. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6969. dstInput.value = r.dst_address;
  6970. gwInput.value = r.gateway || '';
  6971. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6972. commentInput.value = r.comment || '';
  6973. disCheck.checked = !!r.disabled;
  6974. const checkGw = document.getElementById('route-modal-check-gw');
  6975. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6976. const checkTarget = document.getElementById('route-modal-check-target');
  6977. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6978. const checkInterval = document.getElementById('route-modal-check-interval');
  6979. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6980. const checkThresh = document.getElementById('route-modal-check-threshold');
  6981. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6982. toggleRouteCheckModeUI();
  6983. dstInput.disabled = !isStatic;
  6984. gwInput.disabled = !isStatic;
  6985. distInput.disabled = !isStatic;
  6986. ifaceSelect.disabled = !isStatic;
  6987. tableSelect.disabled = !isStatic;
  6988. commentInput.disabled = !isStatic;
  6989. disCheck.disabled = !isStatic;
  6990. if (checkGw) checkGw.disabled = !isStatic;
  6991. if (checkTarget) checkTarget.disabled = !isStatic;
  6992. if (checkInterval) checkInterval.disabled = !isStatic;
  6993. if (checkThresh) checkThresh.disabled = !isStatic;
  6994. if (saveBtn) {
  6995. if (isStatic) {
  6996. saveBtn.classList.remove('hidden');
  6997. } else {
  6998. saveBtn.classList.add('hidden');
  6999. }
  7000. }
  7001. populateInterfaceSelect('route-modal-iface', r.interface);
  7002. tableSelect.innerHTML = '';
  7003. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  7004. const opt = document.createElement('option');
  7005. opt.value = t.name;
  7006. opt.innerText = t.name;
  7007. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  7008. tableSelect.appendChild(opt);
  7009. });
  7010. document.getElementById('route-modal').classList.remove('hidden');
  7011. }
  7012. function closeRouteModal() {
  7013. document.getElementById('route-modal').classList.add('hidden');
  7014. }
  7015. function setRouteCheckTarget(ip) {
  7016. const inp = document.getElementById('route-modal-check-target');
  7017. if (inp) inp.value = ip;
  7018. }
  7019. function toggleRouteCheckModeUI() {
  7020. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  7021. const targetRow = document.getElementById('route-row-check-target');
  7022. const paramsRow = document.getElementById('route-row-check-params');
  7023. if (mode === 'none') {
  7024. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  7025. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  7026. } else if (mode === 'ping') {
  7027. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  7028. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  7029. } else { // internet
  7030. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  7031. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  7032. }
  7033. }
  7034. async function submitSaveRoute(e) {
  7035. e.preventDefault();
  7036. const id = document.getElementById('route-modal-id').value;
  7037. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  7038. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  7039. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  7040. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  7041. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  7042. const dst = document.getElementById('route-modal-dst').value.trim();
  7043. const gw = document.getElementById('route-modal-gw').value.trim();
  7044. const table = document.getElementById('route-modal-table').value;
  7045. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  7046. const iface = document.getElementById('route-modal-iface').value;
  7047. const comment = document.getElementById('route-modal-comment').value.trim();
  7048. const disabled = document.getElementById('route-modal-disabled').checked;
  7049. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  7050. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  7051. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  7052. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  7053. if (!dst) {
  7054. showToast('Error', 'Destination address is required', 'error');
  7055. return;
  7056. }
  7057. if (!gw && !iface) {
  7058. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  7059. return;
  7060. }
  7061. const payload = {
  7062. id,
  7063. old_dst_address: oldDst,
  7064. old_gateway: oldGw,
  7065. old_routing_table: oldTable,
  7066. old_interface: oldIface,
  7067. dst_address: dst,
  7068. gateway: gw || iface,
  7069. routing_table: table,
  7070. distance,
  7071. interface: iface,
  7072. comment,
  7073. disabled,
  7074. check_gateway,
  7075. check_target,
  7076. check_interval,
  7077. check_threshold
  7078. };
  7079. if (oldDistStr !== undefined && oldDistStr !== '') {
  7080. payload.old_distance = parseInt(oldDistStr, 10);
  7081. }
  7082. try {
  7083. const res = await fetch(`${API_BASE}/routes`, {
  7084. method: 'POST',
  7085. headers: { 'Content-Type': 'application/json' },
  7086. body: JSON.stringify(payload)
  7087. });
  7088. if (res.ok) {
  7089. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7090. closeRouteModal();
  7091. const tbody = document.getElementById('routes-table-body');
  7092. if (tbody) tbody.dataset.sig = '';
  7093. loadRoutes();
  7094. } else {
  7095. const err = await res.json().catch(() => ({}));
  7096. showToast('Error', err.message || err.error || 'Failed to save route', 'error');
  7097. }
  7098. } catch (err) {
  7099. showToast('Error', err.message, 'error');
  7100. }
  7101. }
  7102. async function toggleRouteState(id, disabled) {
  7103. try {
  7104. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7105. method: 'POST',
  7106. headers: { 'Content-Type': 'application/json' },
  7107. body: JSON.stringify({ disabled })
  7108. });
  7109. if (res.ok) {
  7110. const tbody = document.getElementById('routes-table-body');
  7111. if (tbody) tbody.dataset.sig = '';
  7112. loadRoutes();
  7113. } else {
  7114. const err = await res.json().catch(() => ({}));
  7115. showToast('Error', err.message || err.error || 'Failed to update route state', 'error');
  7116. }
  7117. } catch (err) {
  7118. showToast('Error', err.message, 'error');
  7119. }
  7120. }
  7121. async function deleteRoute(id) {
  7122. if (!confirm('Are you sure you want to delete this route?')) return;
  7123. try {
  7124. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7125. if (res.ok) {
  7126. showToast('Deleted', 'Route removed', 'success');
  7127. const tbody = document.getElementById('routes-table-body');
  7128. if (tbody) tbody.dataset.sig = '';
  7129. loadRoutes();
  7130. } else {
  7131. const err = await res.json().catch(() => ({}));
  7132. showToast('Error', err.message || err.error || 'Failed to delete route', 'error');
  7133. }
  7134. } catch (err) {
  7135. showToast('Error', err.message, 'error');
  7136. }
  7137. }
  7138. // ----------------- Policy Rules (/ip route rule) -----------------
  7139. function renderPolicyRules() {
  7140. const tbody = document.getElementById('rules-table-body');
  7141. const empty = document.getElementById('rules-empty');
  7142. if (!tbody) return;
  7143. const showSystem = document.getElementById('prule-show-system')?.checked;
  7144. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7145. const countBadge = document.getElementById('rules-count-badge');
  7146. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7147. const bRules = document.getElementById('routes-badge-rules');
  7148. if (bRules) bRules.innerText = filtered.length;
  7149. if (filtered.length === 0) {
  7150. empty?.classList.remove('hidden');
  7151. tbody.innerHTML = '';
  7152. return;
  7153. }
  7154. empty?.classList.add('hidden');
  7155. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7156. if (tbody.dataset.sig === sig) return;
  7157. tbody.dataset.sig = sig;
  7158. tbody.innerHTML = '';
  7159. filtered.forEach(pr => {
  7160. const isSys = pr.is_default || pr.is_system;
  7161. const tr = document.createElement('tr');
  7162. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7163. tr.innerHTML = `
  7164. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7165. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7166. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7167. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7168. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7169. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7170. <td class="py-2.5 px-3 text-right font-sans">
  7171. ${!pr.is_default ? `
  7172. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7173. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7174. </td>
  7175. `;
  7176. tbody.appendChild(tr);
  7177. });
  7178. }
  7179. function openAddPolicyRuleModal() {
  7180. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7181. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7182. document.getElementById('prule-modal-mark').value = '';
  7183. document.getElementById('prule-modal-src').value = '';
  7184. document.getElementById('prule-modal-dst').value = '';
  7185. const sel = document.getElementById('prule-modal-table');
  7186. sel.innerHTML = '';
  7187. (state.routingTables || []).forEach(t => {
  7188. const opt = document.createElement('option');
  7189. opt.value = t.name;
  7190. opt.innerText = t.name;
  7191. sel.appendChild(opt);
  7192. });
  7193. document.getElementById('prule-modal').classList.remove('hidden');
  7194. }
  7195. function closePolicyRuleModal() {
  7196. document.getElementById('prule-modal').classList.add('hidden');
  7197. }
  7198. async function submitSavePolicyRule(e) {
  7199. e.preventDefault();
  7200. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7201. const mark = document.getElementById('prule-modal-mark').value.trim();
  7202. const src = document.getElementById('prule-modal-src').value.trim();
  7203. const dst = document.getElementById('prule-modal-dst').value.trim();
  7204. const table = document.getElementById('prule-modal-table').value;
  7205. const action = document.getElementById('prule-modal-action').value;
  7206. try {
  7207. const res = await fetch(`${API_BASE}/routing/rules`, {
  7208. method: 'POST',
  7209. headers: { 'Content-Type': 'application/json' },
  7210. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7211. });
  7212. if (res.ok) {
  7213. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7214. closePolicyRuleModal();
  7215. loadRoutes();
  7216. } else {
  7217. const err = await res.json();
  7218. showToast('Error', err.message, 'error');
  7219. }
  7220. } catch (err) {
  7221. showToast('Error', err.message, 'error');
  7222. }
  7223. }
  7224. async function deletePolicyRule(id) {
  7225. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7226. try {
  7227. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7228. if (res.ok) {
  7229. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7230. loadRoutes();
  7231. } else {
  7232. throw new Error(await responseError(res));
  7233. }
  7234. } catch (err) {
  7235. showToast('Error', err.message, 'error');
  7236. }
  7237. }
  7238. // ----------------- Routing Tables -----------------
  7239. function renderRoutingTables() {
  7240. const tbody = document.getElementById('tables-table-body');
  7241. if (!tbody) return;
  7242. const tables = state.routingTables || [];
  7243. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7244. if (tbody.dataset.sig === sig) return;
  7245. tbody.dataset.sig = sig;
  7246. tbody.innerHTML = '';
  7247. (state.routingTables || []).forEach(t => {
  7248. const tr = document.createElement('tr');
  7249. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7250. tr.innerHTML = `
  7251. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7252. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7253. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7254. `;
  7255. tbody.appendChild(tr);
  7256. });
  7257. }
  7258. function openAddTableModal() {
  7259. document.getElementById('table-modal-name').value = '';
  7260. document.getElementById('table-modal-id').value = '';
  7261. document.getElementById('table-modal-comment').value = '';
  7262. document.getElementById('table-modal').classList.remove('hidden');
  7263. }
  7264. function closeTableModal() {
  7265. document.getElementById('table-modal').classList.add('hidden');
  7266. }
  7267. async function submitSaveTable(e) {
  7268. e.preventDefault();
  7269. const name = document.getElementById('table-modal-name').value.trim();
  7270. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7271. const comment = document.getElementById('table-modal-comment').value.trim();
  7272. try {
  7273. const res = await fetch(`${API_BASE}/routing/tables`, {
  7274. method: 'POST',
  7275. headers: { 'Content-Type': 'application/json' },
  7276. body: JSON.stringify({ name, table_id: id, comment })
  7277. });
  7278. if (res.ok) {
  7279. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7280. closeTableModal();
  7281. loadRoutes();
  7282. } else {
  7283. const err = await res.json();
  7284. showToast('Error', err.message, 'error');
  7285. }
  7286. } catch (err) {
  7287. showToast('Error', err.message, 'error');
  7288. }
  7289. }
  7290. async function loadDebianConfig() {
  7291. const view = document.getElementById('debian-config-view');
  7292. view.innerText = 'Generating live configuration...';
  7293. try {
  7294. const res = await fetch(`${API_BASE}/debian/config`);
  7295. const data = await res.json();
  7296. view.innerText = data.content || '# Empty config';
  7297. } catch (err) {
  7298. view.innerText = 'Failed to generate Debian network config.';
  7299. }
  7300. }
  7301. async function saveDebianConfig() {
  7302. try {
  7303. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7304. const data = await res.json();
  7305. if (res.ok) {
  7306. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7307. loadDebianConfig();
  7308. }
  7309. } catch (err) {
  7310. showToast('Error', err.message, 'error');
  7311. }
  7312. }
  7313. function showToast(title, message, type = 'info') {
  7314. const container = document.getElementById('toast-container');
  7315. const toast = document.createElement('div');
  7316. const borderColors = {
  7317. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7318. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7319. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7320. };
  7321. 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}`;
  7322. toast.innerHTML = `
  7323. <div class="flex-1">
  7324. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7325. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7326. </div>
  7327. `;
  7328. container.appendChild(toast);
  7329. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7330. setTimeout(() => {
  7331. toast.classList.add('opacity-0', 'translate-y-2');
  7332. setTimeout(() => toast.remove(), 300);
  7333. }, 4000);
  7334. }
  7335. function formatTraffic(bytesPerSec) {
  7336. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7337. const kb = bytesPerSec / 1024;
  7338. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7339. const mb = kb / 1024;
  7340. return `${mb.toFixed(2)} MB/s`;
  7341. }
  7342. function toggleSidebar() {
  7343. const sb = document.getElementById('sidebar');
  7344. sb.classList.toggle('-translate-x-full');
  7345. }
  7346. // ======================== EoIP (Ethernet over IP) ========================
  7347. async function loadEoIP(populate = true) {
  7348. try {
  7349. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7350. const data = await res.json();
  7351. state.eoipTunnels = Array.isArray(data) ? data : [];
  7352. const badge = document.getElementById('eoip-count-badge');
  7353. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7354. const sideBadge = document.getElementById('badge-eoip-count');
  7355. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7356. renderEoIPTunnels();
  7357. } catch (err) {
  7358. console.error('Failed to load EoIP:', err);
  7359. }
  7360. }
  7361. function renderEoIPTunnels() {
  7362. const tbody = document.getElementById('eoip-table-body');
  7363. const empty = document.getElementById('eoip-empty');
  7364. if (!tbody) return;
  7365. tbody.innerHTML = '';
  7366. const tunnels = state.eoipTunnels || [];
  7367. if (tunnels.length === 0) {
  7368. empty?.classList.remove('hidden');
  7369. return;
  7370. }
  7371. empty?.classList.add('hidden');
  7372. tunnels.forEach(t => {
  7373. const tr = document.createElement('tr');
  7374. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7375. tr.innerHTML = `
  7376. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7377. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7378. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7379. <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>
  7380. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7381. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7382. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7383. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7384. <td class="py-2.5 px-3 font-mono text-[11px]">
  7385. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7386. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7387. </td>
  7388. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7389. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7390. <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>
  7391. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7392. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7393. </td>
  7394. `;
  7395. tbody.appendChild(tr);
  7396. });
  7397. }
  7398. function openAddEoIPModal() {
  7399. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7400. document.getElementById('eoip-modal-id').value = '';
  7401. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7402. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7403. document.getElementById('eoip-modal-remote').value = '';
  7404. document.getElementById('eoip-modal-ip').value = '';
  7405. document.getElementById('eoip-modal-local').value = '';
  7406. document.getElementById('eoip-modal-mac').value = '';
  7407. document.getElementById('eoip-modal-mtu').value = '1500';
  7408. document.getElementById('eoip-modal-comment').value = '';
  7409. document.getElementById('eoip-modal-clampmss').checked = true;
  7410. document.getElementById('eoip-modal-disabled').checked = false;
  7411. document.getElementById('eoip-modal').classList.remove('hidden');
  7412. }
  7413. function openEditEoIPModal(id) {
  7414. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7415. if (!t) return;
  7416. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7417. document.getElementById('eoip-modal-id').value = t.id;
  7418. document.getElementById('eoip-modal-name').value = t.name;
  7419. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7420. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7421. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7422. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7423. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7424. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7425. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7426. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7427. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7428. document.getElementById('eoip-modal').classList.remove('hidden');
  7429. }
  7430. function closeEoIPModal() {
  7431. document.getElementById('eoip-modal').classList.add('hidden');
  7432. }
  7433. async function submitSaveEoIP(e) {
  7434. e.preventDefault();
  7435. const id = document.getElementById('eoip-modal-id').value;
  7436. const name = document.getElementById('eoip-modal-name').value.trim();
  7437. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7438. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7439. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7440. const local = document.getElementById('eoip-modal-local').value.trim();
  7441. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7442. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7443. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7444. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7445. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7446. try {
  7447. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7448. method: 'POST',
  7449. headers: { 'Content-Type': 'application/json' },
  7450. body: JSON.stringify({
  7451. id,
  7452. name,
  7453. tunnel_id: tunnelId,
  7454. remote_address: remote,
  7455. ip_address: ipAddress,
  7456. local_address: local,
  7457. mac_address: mac,
  7458. mtu,
  7459. clamp_mss: clampMss,
  7460. comment,
  7461. disabled
  7462. })
  7463. });
  7464. if (res.ok) {
  7465. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7466. closeEoIPModal();
  7467. loadEoIP(false);
  7468. fetchData(false);
  7469. } else {
  7470. const err = await res.json();
  7471. showToast('Error', err.message, 'error');
  7472. }
  7473. } catch (err) {
  7474. showToast('Error', err.message, 'error');
  7475. }
  7476. }
  7477. async function toggleEoIPState(id, disabled) {
  7478. try {
  7479. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7480. method: 'POST',
  7481. headers: { 'Content-Type': 'application/json' },
  7482. body: JSON.stringify({ disabled })
  7483. });
  7484. if (res.ok) {
  7485. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7486. loadEoIP(false);
  7487. fetchData(false);
  7488. }
  7489. } catch (err) {
  7490. showToast('Error', err.message, 'error');
  7491. }
  7492. }
  7493. async function deleteEoIP(id) {
  7494. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7495. try {
  7496. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7497. if (res.ok) {
  7498. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7499. loadEoIP(false);
  7500. fetchData(false);
  7501. }
  7502. } catch (err) {
  7503. showToast('Error', err.message, 'error');
  7504. }
  7505. }
  7506. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7507. async function loadVXLAN(populate = true) {
  7508. try {
  7509. const [tunnelsRes, vtepsRes] = await Promise.all([
  7510. fetch(`${API_BASE}/vpn/vxlan`),
  7511. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7512. ]);
  7513. if (tunnelsRes.ok) {
  7514. state.vxlanTunnels = await tunnelsRes.json() || [];
  7515. }
  7516. if (vtepsRes.ok) {
  7517. state.vxlanVteps = await vtepsRes.json() || [];
  7518. }
  7519. renderVXLANTable();
  7520. renderVXLANVtepsTable();
  7521. const countBadge = document.getElementById('vxlan-count-badge');
  7522. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7523. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7524. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7525. const navBadge = document.getElementById('badge-vxlan-count');
  7526. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7527. } catch (err) {
  7528. console.error('Error loading VXLAN:', err);
  7529. }
  7530. }
  7531. function renderVXLANTable() {
  7532. const tbody = document.getElementById('vxlan-table-body');
  7533. const empty = document.getElementById('vxlan-empty');
  7534. if (!tbody || !empty) return;
  7535. tbody.innerHTML = '';
  7536. const tunnels = state.vxlanTunnels || [];
  7537. if (tunnels.length === 0) {
  7538. empty.classList.remove('hidden');
  7539. return;
  7540. }
  7541. empty.classList.add('hidden');
  7542. tunnels.forEach(t => {
  7543. const tr = document.createElement('tr');
  7544. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7545. let flag = '';
  7546. if (t.disabled) {
  7547. 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>';
  7548. } else if (t.running) {
  7549. 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>';
  7550. } else {
  7551. 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>';
  7552. }
  7553. const vtepCount = (t.vteps || []).length;
  7554. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7555. tr.innerHTML = `
  7556. <td class="py-2.5 px-3 text-center">${flag}</td>
  7557. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7558. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7559. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7560. <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>
  7561. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7562. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7563. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7564. <td class="py-2.5 px-3 font-mono">
  7565. <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>
  7566. </td>
  7567. <td class="py-2.5 px-3 font-mono text-[11px]">
  7568. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7569. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7570. </td>
  7571. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7572. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7573. <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>
  7574. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7575. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7576. </td>
  7577. `;
  7578. tbody.appendChild(tr);
  7579. });
  7580. }
  7581. function renderVXLANVtepsTable() {
  7582. const tbody = document.getElementById('vxlan-vteps-table-body');
  7583. const empty = document.getElementById('vxlan-vteps-empty');
  7584. if (!tbody || !empty) return;
  7585. tbody.innerHTML = '';
  7586. const vteps = state.vxlanVteps || [];
  7587. if (vteps.length === 0) {
  7588. empty.classList.remove('hidden');
  7589. return;
  7590. }
  7591. empty.classList.add('hidden');
  7592. vteps.forEach(v => {
  7593. const tr = document.createElement('tr');
  7594. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7595. tr.innerHTML = `
  7596. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7597. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7598. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7599. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7600. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7601. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7602. </td>
  7603. `;
  7604. tbody.appendChild(tr);
  7605. });
  7606. }
  7607. function openAddVXLANModal() {
  7608. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7609. document.getElementById('vxlan-modal-id').value = '';
  7610. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7611. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7612. document.getElementById('vxlan-modal-port').value = '4789';
  7613. document.getElementById('vxlan-modal-ip').value = '';
  7614. document.getElementById('vxlan-modal-parent').value = '';
  7615. document.getElementById('vxlan-modal-local').value = '';
  7616. document.getElementById('vxlan-modal-remote').value = '';
  7617. document.getElementById('vxlan-modal-group').value = '';
  7618. document.getElementById('vxlan-modal-mac').value = '';
  7619. document.getElementById('vxlan-modal-mtu').value = '1500';
  7620. document.getElementById('vxlan-modal-comment').value = '';
  7621. document.getElementById('vxlan-modal-learning').checked = true;
  7622. document.getElementById('vxlan-modal-disabled').checked = false;
  7623. document.getElementById('vxlan-modal').classList.remove('hidden');
  7624. }
  7625. function openEditVXLANModal(id) {
  7626. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7627. if (!t) return;
  7628. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7629. document.getElementById('vxlan-modal-id').value = t.id;
  7630. document.getElementById('vxlan-modal-name').value = t.name;
  7631. document.getElementById('vxlan-modal-vni').value = t.vni;
  7632. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7633. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7634. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7635. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7636. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7637. document.getElementById('vxlan-modal-group').value = t.group || '';
  7638. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7639. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7640. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7641. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7642. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7643. document.getElementById('vxlan-modal').classList.remove('hidden');
  7644. }
  7645. function closeVXLANModal() {
  7646. document.getElementById('vxlan-modal').classList.add('hidden');
  7647. }
  7648. async function submitSaveVXLAN(e) {
  7649. e.preventDefault();
  7650. const id = document.getElementById('vxlan-modal-id').value;
  7651. const name = document.getElementById('vxlan-modal-name').value.trim();
  7652. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7653. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7654. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7655. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7656. const local = document.getElementById('vxlan-modal-local').value.trim();
  7657. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7658. const group = document.getElementById('vxlan-modal-group').value.trim();
  7659. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7660. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7661. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7662. const learning = document.getElementById('vxlan-modal-learning').checked;
  7663. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7664. try {
  7665. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7666. method: 'POST',
  7667. headers: { 'Content-Type': 'application/json' },
  7668. body: JSON.stringify({
  7669. id,
  7670. name,
  7671. vni,
  7672. port,
  7673. ip_address: ipAddress,
  7674. parent_interface: parentInterface,
  7675. local_address: local,
  7676. remote_address: remote,
  7677. group,
  7678. mac_address: mac,
  7679. mtu,
  7680. learning,
  7681. comment,
  7682. disabled
  7683. })
  7684. });
  7685. if (res.ok) {
  7686. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7687. closeVXLANModal();
  7688. loadVXLAN(false);
  7689. fetchData(false);
  7690. } else {
  7691. const err = await res.json();
  7692. showToast('Error', err.message, 'error');
  7693. }
  7694. } catch (err) {
  7695. showToast('Error', err.message, 'error');
  7696. }
  7697. }
  7698. async function toggleVXLANState(id, disabled) {
  7699. try {
  7700. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7701. method: 'POST',
  7702. headers: { 'Content-Type': 'application/json' },
  7703. body: JSON.stringify({ disabled })
  7704. });
  7705. if (res.ok) {
  7706. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7707. loadVXLAN(false);
  7708. fetchData(false);
  7709. }
  7710. } catch (err) {
  7711. showToast('Error', err.message, 'error');
  7712. }
  7713. }
  7714. async function deleteVXLAN(id) {
  7715. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7716. try {
  7717. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7718. if (res.ok) {
  7719. showToast('Deleted', 'VXLAN interface removed', 'success');
  7720. loadVXLAN(false);
  7721. fetchData(false);
  7722. }
  7723. } catch (err) {
  7724. showToast('Error', err.message, 'error');
  7725. }
  7726. }
  7727. function openAddVXLANVtepModal(defaultIface = '') {
  7728. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7729. if (sel) {
  7730. sel.innerHTML = '';
  7731. const tunnels = state.vxlanTunnels || [];
  7732. tunnels.forEach(t => {
  7733. const opt = document.createElement('option');
  7734. opt.value = t.name;
  7735. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7736. if (defaultIface && t.name === defaultIface) {
  7737. opt.selected = true;
  7738. }
  7739. sel.appendChild(opt);
  7740. });
  7741. }
  7742. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7743. document.getElementById('vxlan-vtep-modal-port').value = '';
  7744. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7745. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7746. }
  7747. function closeVXLANVtepModal() {
  7748. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7749. }
  7750. async function submitSaveVXLANVtep(e) {
  7751. e.preventDefault();
  7752. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7753. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7754. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7755. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7756. try {
  7757. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7758. method: 'POST',
  7759. headers: { 'Content-Type': 'application/json' },
  7760. body: JSON.stringify({
  7761. interface: iface,
  7762. remote_ip: remote,
  7763. port,
  7764. comment
  7765. })
  7766. });
  7767. if (res.ok) {
  7768. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7769. closeVXLANVtepModal();
  7770. loadVXLAN(false);
  7771. fetchData(false);
  7772. } else {
  7773. const err = await res.json();
  7774. showToast('Error', err.message, 'error');
  7775. }
  7776. } catch (err) {
  7777. showToast('Error', err.message, 'error');
  7778. }
  7779. }
  7780. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7781. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7782. try {
  7783. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7784. method: 'DELETE'
  7785. });
  7786. if (res.ok) {
  7787. showToast('Deleted', 'Remote VTEP removed', 'success');
  7788. loadVXLAN(false);
  7789. fetchData(false);
  7790. }
  7791. } catch (err) {
  7792. showToast('Error', err.message, 'error');
  7793. }
  7794. }
  7795. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7796. const aeroRateSamples = new Map();
  7797. const aeroLiveRates = new Map();
  7798. async function loadAeroTUN(populate = true) {
  7799. try {
  7800. const [tunnelsRes, statsRes] = await Promise.all([
  7801. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7802. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7803. ]);
  7804. if (tunnelsRes.ok) {
  7805. const data = await tunnelsRes.json();
  7806. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7807. const now = Date.now();
  7808. for (const t of state.aerotunTunnels) {
  7809. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7810. 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) {
  7811. 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});
  7812. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7813. 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});
  7814. }
  7815. }
  7816. if (statsRes.ok) {
  7817. state.aerotunStats = await statsRes.json();
  7818. }
  7819. const countBadge = document.getElementById('aerotun-count-badge');
  7820. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7821. const sideBadge = document.getElementById('badge-aerotun-count');
  7822. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7823. renderAeroTUN();
  7824. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7825. } catch (err) {
  7826. console.error('Failed to load AeroTUN:', err);
  7827. }
  7828. }
  7829. function renderAeroTUN() {
  7830. const tbody = document.getElementById('aerotun-table-body');
  7831. const empty = document.getElementById('aerotun-empty');
  7832. // Update summary cards
  7833. const stats = state.aerotunStats || {};
  7834. const tunnels = state.aerotunTunnels || [];
  7835. const statActive = document.getElementById('aerotun-stat-active');
  7836. if (statActive) {
  7837. const activeCount = tunnels.filter(t => t.connected).length;
  7838. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7839. }
  7840. const statSaved = document.getElementById('aerotun-stat-saved');
  7841. if (statSaved) {
  7842. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7843. }
  7844. const statRatio = document.getElementById('aerotun-stat-ratio');
  7845. if (statRatio) {
  7846. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7847. }
  7848. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7849. if (statTraffic) {
  7850. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7851. }
  7852. if (!tbody) return;
  7853. tbody.innerHTML = '';
  7854. if (tunnels.length === 0) {
  7855. empty?.classList.remove('hidden');
  7856. return;
  7857. }
  7858. empty?.classList.add('hidden');
  7859. tunnels.forEach(t => {
  7860. const tr = document.createElement('tr');
  7861. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7862. const modeBadge = t.mode === 'server'
  7863. ? `<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>`
  7864. : `<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>`;
  7865. const endpointInfo = t.mode === 'server'
  7866. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7867. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7868. const compBadge = t.compression
  7869. ? `<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>`
  7870. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7871. const activePeer = t.connected && t.active_peer_endpoint
  7872. ? `<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>`
  7873. : `<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>`;
  7874. const rawRx = formatBytes(t.rx_bytes || 0);
  7875. const rawTx = formatBytes(t.tx_bytes || 0);
  7876. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7877. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7878. const rate = aeroLiveRates.get(t.id);
  7879. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7880. tr.innerHTML = `
  7881. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7882. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7883. <span>${escapeHtml(t.name)}</span>
  7884. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7885. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7886. </td>
  7887. <td class="py-2.5 px-3">${modeBadge}</td>
  7888. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7889. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7890. <td class="py-2.5 px-3">${compBadge}</td>
  7891. <td class="py-2.5 px-3">${activePeer}</td>
  7892. <td class="py-2.5 px-3 font-mono text-[11px]">
  7893. <span class="text-emerald-400">↓ ${rawRx}</span>
  7894. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7895. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7896. </td>
  7897. <td class="py-2.5 px-3 font-mono text-[11px]">
  7898. <span class="text-slate-400">↓ ${wireRx}</span>
  7899. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7900. </td>
  7901. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7902. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7903. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7904. ${t.running
  7905. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7906. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7907. }
  7908. <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>
  7909. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7910. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7911. </td>
  7912. `;
  7913. tbody.appendChild(tr);
  7914. });
  7915. }
  7916. async function openAeroTUNHealth(encodedID) {
  7917. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7918. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7919. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7920. document.getElementById('aerotun-compare-host').value=underlay;
  7921. document.getElementById('aerotun-compare-result').textContent='';
  7922. document.getElementById('aerotun-health-result').textContent = '';
  7923. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7924. await refreshAeroTUNHealth();
  7925. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7926. }
  7927. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7928. async function refreshAeroTUNHealth() {
  7929. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7930. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7931. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7932. try {
  7933. 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;
  7934. 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);
  7935. const d=t.drop_breakdown;
  7936. 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}`:''}`;
  7937. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7938. if(!events.length){node.textContent='No events recorded yet.';return}
  7939. 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)}
  7940. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7941. }
  7942. async function runAeroTUNHealthCheck() {
  7943. 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…';
  7944. 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()}
  7945. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7946. finally {button.disabled=false}
  7947. }
  7948. let aeroCompareRunning=false, aeroCompareCancel=false;
  7949. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7950. async function runAeroTUNComparison() {
  7951. if(aeroCompareRunning)return;
  7952. 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();
  7953. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7954. 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}
  7955. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7956. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7957. 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()};
  7958. const results=[];
  7959. try {
  7960. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7961. if(aeroCompareCancel)break;
  7962. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7963. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7964. 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;
  7965. 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}}
  7966. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7967. 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.`);
  7968. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7969. }
  7970. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7971. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7972. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7973. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7974. }
  7975. let aeroModalGeneration = 0;
  7976. let aeroIdentityDraft = '';
  7977. let aeroSaving = false;
  7978. let aeroPSKRequest = 0;
  7979. function discardAeroIdentityDraft(id) {
  7980. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7981. }
  7982. async function generateAeroTUNIdentity() {
  7983. const generation = aeroModalGeneration;
  7984. const retry = document.getElementById('aerotun-retry-identity');
  7985. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7986. retry.classList.add('hidden');
  7987. document.getElementById('aerotun-modal-public').value = '';
  7988. try {
  7989. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7990. if (!res.ok) throw new Error(await responseError(res));
  7991. const draft = await res.json();
  7992. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7993. aeroIdentityDraft = draft.draft_id;
  7994. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7995. updateAeroTUNSetupHint();
  7996. } catch (err) {
  7997. if (generation !== aeroModalGeneration) return;
  7998. retry.classList.remove('hidden');
  7999. updateAeroTUNSetupHint();
  8000. showToast('Identity Generation Failed', err.message, 'error');
  8001. }
  8002. }
  8003. function onAeroTUNModeChange() {
  8004. const mode = document.getElementById('aerotun-modal-mode').value;
  8005. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  8006. const portInput = document.getElementById('aerotun-modal-port');
  8007. if (mode === 'server') {
  8008. if (!portInput.value) portInput.value = '51830';
  8009. endpointInput.placeholder = 'Optional / learned roaming peer';
  8010. } else {
  8011. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  8012. if (!portInput.value) portInput.value = '';
  8013. }
  8014. }
  8015. function onAeroTUNPeerChange() {
  8016. const peer = document.getElementById('aerotun-modal-peer');
  8017. const allowed = document.getElementById('aerotun-modal-allowed');
  8018. const previous = peer.dataset.allowedDefault || '';
  8019. const host = peer.value.trim().split('/')[0];
  8020. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  8021. if (allowed.value.trim() === previous) allowed.value = next;
  8022. peer.dataset.allowedDefault = next;
  8023. }
  8024. async function generateAeroTUNKey(automatic = false) {
  8025. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  8026. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  8027. try {
  8028. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  8029. if (!res.ok) throw new Error(await responseError(res));
  8030. const data = await res.json();
  8031. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  8032. input.value = data.key;
  8033. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  8034. } catch (err) {
  8035. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  8036. }
  8037. }
  8038. function updateAeroTUNSetupHint() {
  8039. const version = document.getElementById('aerotun-modal-protocol').value;
  8040. const key = document.getElementById('aerotun-modal-public').value;
  8041. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  8042. const hint = document.getElementById('aerotun-setup-hint');
  8043. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  8044. if (!hint) return;
  8045. 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.';
  8046. }
  8047. async function copyAeroTUNPublicKey() {
  8048. const input = document.getElementById('aerotun-modal-public');
  8049. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  8050. try {
  8051. await navigator.clipboard.writeText(input.value);
  8052. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  8053. } catch {
  8054. input.focus(); input.select();
  8055. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  8056. }
  8057. }
  8058. async function copyAeroTUNPSK() {
  8059. const input = document.getElementById('aerotun-modal-psk');
  8060. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  8061. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  8062. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  8063. }
  8064. function openAddAeroTUNModal() {
  8065. if (aeroSaving) return;
  8066. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8067. const tunnels = state.aerotunTunnels || [];
  8068. const usedNames = new Set(tunnels.map(t => t.name));
  8069. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  8070. 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++;
  8071. if (index >= 256) index = 0;
  8072. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  8073. document.getElementById('aerotun-modal-id').value = '';
  8074. document.getElementById('aerotun-modal-protocol').value='3';
  8075. document.getElementById('aerotun-modal-public').value='';
  8076. document.getElementById('aerotun-modal-peerkey').value='';
  8077. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  8078. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  8079. document.getElementById('aerotun-modal-mode').value = 'server';
  8080. document.getElementById('aerotun-modal-port').value = 51830 + index;
  8081. document.getElementById('aerotun-modal-endpoint').value = '';
  8082. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  8083. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  8084. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  8085. document.getElementById('aerotun-modal-psk').value = '';
  8086. document.getElementById('aerotun-modal-mtu').value = '1420';
  8087. document.getElementById('aerotun-modal-comment').value = '';
  8088. document.getElementById('aerotun-modal-compression').checked = false;
  8089. document.getElementById('aerotun-modal-defroute').checked = false;
  8090. document.getElementById('aerotun-modal-disabled').checked = true;
  8091. document.getElementById('aerotun-modal-psk').type = 'password';
  8092. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8093. onAeroTUNModeChange();
  8094. updateAeroTUNSetupHint();
  8095. document.getElementById('aerotun-modal').classList.remove('hidden');
  8096. generateAeroTUNKey(true);
  8097. generateAeroTUNIdentity();
  8098. }
  8099. function openEditAeroTUNModal(id) {
  8100. if (aeroSaving) return;
  8101. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8102. if (!t) return;
  8103. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8104. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8105. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8106. document.getElementById('aerotun-modal-id').value = t.id;
  8107. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8108. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8109. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8110. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8111. document.getElementById('aerotun-modal-name').value = t.name;
  8112. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8113. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8114. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8115. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8116. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8117. const peerHost = (t.peer_address || '').split('/')[0];
  8118. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8119. document.getElementById('aerotun-modal-psk').value = '';
  8120. document.getElementById('aerotun-modal-psk').type = 'password';
  8121. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8122. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8123. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8124. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8125. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8126. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8127. onAeroTUNModeChange();
  8128. updateAeroTUNSetupHint();
  8129. document.getElementById('aerotun-modal').classList.remove('hidden');
  8130. }
  8131. function closeAeroTUNModal() {
  8132. if (aeroSaving) return;
  8133. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8134. document.getElementById('aerotun-modal-psk').value = '';
  8135. document.getElementById('aerotun-modal').classList.add('hidden');
  8136. }
  8137. async function submitSaveAeroTUN(e) {
  8138. e.preventDefault();
  8139. if (aeroSaving) return;
  8140. const id = document.getElementById('aerotun-modal-id').value;
  8141. const name = document.getElementById('aerotun-modal-name').value.trim();
  8142. const mode = document.getElementById('aerotun-modal-mode').value;
  8143. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8144. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8145. const local = document.getElementById('aerotun-modal-local').value.trim();
  8146. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8147. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8148. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8149. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8150. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8151. const compression = document.getElementById('aerotun-modal-compression').checked;
  8152. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8153. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8154. if (mode === 'client' && !endpoint) {
  8155. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8156. return;
  8157. }
  8158. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8159. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8160. return;
  8161. }
  8162. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8163. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8164. return;
  8165. }
  8166. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8167. if (version === 3 && !id && !aeroIdentityDraft) {
  8168. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8169. return;
  8170. }
  8171. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8172. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8173. document.getElementById('aerotun-modal-allowed').focus();
  8174. return;
  8175. }
  8176. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8177. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8178. return;
  8179. }
  8180. if (!psk && !id) {
  8181. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8182. return;
  8183. }
  8184. aeroSaving = true;
  8185. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8186. if (submit) submit.disabled = true;
  8187. try {
  8188. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8189. method: 'POST',
  8190. headers: { 'Content-Type': 'application/json' },
  8191. body: JSON.stringify({
  8192. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8193. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8194. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8195. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8196. id,
  8197. name,
  8198. mode,
  8199. listen_port: port,
  8200. remote_endpoint: endpoint,
  8201. local_address: local,
  8202. peer_address: peer,
  8203. psk,
  8204. mtu,
  8205. compression,
  8206. default_route: defaultRoute,
  8207. comment,
  8208. disabled
  8209. })
  8210. });
  8211. if (res.ok) {
  8212. await res.json();
  8213. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8214. aeroIdentityDraft = '';
  8215. aeroSaving = false;
  8216. closeAeroTUNModal();
  8217. await loadAeroTUN(false);
  8218. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8219. fetchData(false);
  8220. } else {
  8221. const err = await responseError(res);
  8222. if (err.includes('configuration saved but tunnel failed to start')) {
  8223. aeroIdentityDraft = '';
  8224. aeroSaving = false;
  8225. closeAeroTUNModal();
  8226. await loadAeroTUN(false);
  8227. showToast('Saved, but not started', err, 'error');
  8228. } else showToast('Error Saving Tunnel', err, 'error');
  8229. }
  8230. } catch (err) {
  8231. showToast('Network Error', err.message, 'error');
  8232. } finally {
  8233. aeroSaving = false;
  8234. if (submit) submit.disabled = false;
  8235. }
  8236. }
  8237. async function startAeroTUNTunnel(id) {
  8238. try {
  8239. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8240. if (res.ok) {
  8241. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8242. loadAeroTUN(false);
  8243. fetchData(false);
  8244. } else {
  8245. const err = await res.text();
  8246. showToast('Failed to Start', err, 'error');
  8247. }
  8248. } catch (err) {
  8249. showToast('Error', err.message, 'error');
  8250. }
  8251. }
  8252. async function stopAeroTUNTunnel(id) {
  8253. try {
  8254. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8255. if (res.ok) {
  8256. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8257. loadAeroTUN(false);
  8258. fetchData(false);
  8259. } else {
  8260. const err = await res.text();
  8261. showToast('Failed to Stop', err, 'error');
  8262. }
  8263. } catch (err) {
  8264. showToast('Error', err.message, 'error');
  8265. }
  8266. }
  8267. async function toggleAeroTUNState(id, disabled) {
  8268. try {
  8269. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8270. method: 'POST',
  8271. headers: { 'Content-Type': 'application/json' },
  8272. body: JSON.stringify({ disabled })
  8273. });
  8274. if (res.ok) {
  8275. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8276. loadAeroTUN(false);
  8277. fetchData(false);
  8278. }
  8279. } catch (err) {
  8280. showToast('Error', err.message, 'error');
  8281. }
  8282. }
  8283. async function deleteAeroTUN(id) {
  8284. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8285. try {
  8286. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8287. if (res.ok) {
  8288. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8289. loadAeroTUN(false);
  8290. fetchData(false);
  8291. }
  8292. } catch (err) {
  8293. showToast('Error', err.message, 'error');
  8294. }
  8295. }
  8296. // ======================== PPP Central Hub & Servers ========================
  8297. function switchPPPSubTab(tab) {
  8298. state.pppSubTab = tab;
  8299. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8300. tabs.forEach(t => {
  8301. const panel = document.getElementById(`ppp-subtab-${t}`);
  8302. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8303. if (panel) {
  8304. if (t === tab) panel.classList.remove('hidden');
  8305. else panel.classList.add('hidden');
  8306. }
  8307. if (btn) {
  8308. if (t === tab) {
  8309. 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';
  8310. } else {
  8311. 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';
  8312. }
  8313. }
  8314. });
  8315. const addBtn = document.getElementById('ppp-primary-add-btn');
  8316. if (addBtn) {
  8317. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8318. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8319. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8320. else addBtn.innerHTML = '<span>Save Config</span>';
  8321. }
  8322. if (tab === 'active') loadPPPSessions();
  8323. }
  8324. function openCurrentPPPModal() {
  8325. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8326. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8327. else if (state.pppSubTab === 'active') loadPPPSessions();
  8328. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8329. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8330. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8331. }
  8332. async function loadPPP(populateDropdowns = true) {
  8333. await Promise.all([
  8334. loadPPPSecrets(),
  8335. loadPPPProfiles(),
  8336. loadPPPServers(),
  8337. loadPPPSessions()
  8338. ]);
  8339. }
  8340. async function loadPPPSecrets() {
  8341. try {
  8342. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8343. const data = await res.json();
  8344. state.pppSecrets = Array.isArray(data) ? data : [];
  8345. const b = document.getElementById('ppp-badge-secrets');
  8346. if (b) b.innerText = state.pppSecrets.length;
  8347. const b2 = document.getElementById('secrets-count-badge');
  8348. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8349. renderPPPSecrets();
  8350. } catch (err) {
  8351. console.error('Failed to load PPP secrets:', err);
  8352. }
  8353. }
  8354. function renderPPPSecrets() {
  8355. const tbody = document.getElementById('secrets-table-body');
  8356. const empty = document.getElementById('secrets-empty');
  8357. if (!tbody) return;
  8358. tbody.innerHTML = '';
  8359. const secrets = state.pppSecrets || [];
  8360. if (secrets.length === 0) {
  8361. empty?.classList.remove('hidden');
  8362. return;
  8363. }
  8364. empty?.classList.add('hidden');
  8365. secrets.forEach(s => {
  8366. const tr = document.createElement('tr');
  8367. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8368. tr.innerHTML = `
  8369. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8370. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8371. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8372. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8373. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8374. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8375. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8376. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8377. <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>
  8378. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8379. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8380. </td>
  8381. `;
  8382. tbody.appendChild(tr);
  8383. });
  8384. }
  8385. async function loadPPPProfiles() {
  8386. try {
  8387. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8388. const data = await res.json();
  8389. state.pppProfiles = Array.isArray(data) ? data : [];
  8390. const b = document.getElementById('ppp-badge-profiles');
  8391. if (b) b.innerText = state.pppProfiles.length;
  8392. const b2 = document.getElementById('profiles-count-badge');
  8393. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8394. // Populate profile selects across modals
  8395. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8396. selects.forEach(sid => {
  8397. const el = document.getElementById(sid);
  8398. if (!el) return;
  8399. const cur = el.value;
  8400. el.innerHTML = '';
  8401. state.pppProfiles.forEach(p => {
  8402. const opt = document.createElement('option');
  8403. opt.value = p.name;
  8404. opt.innerText = `${p.name} (${p.remote_address})`;
  8405. if (p.name === cur) opt.selected = true;
  8406. el.appendChild(opt);
  8407. });
  8408. });
  8409. renderPPPProfiles();
  8410. } catch (err) {
  8411. console.error('Failed to load PPP profiles:', err);
  8412. }
  8413. }
  8414. function renderPPPProfiles() {
  8415. const tbody = document.getElementById('profiles-table-body');
  8416. if (!tbody) return;
  8417. tbody.innerHTML = '';
  8418. (state.pppProfiles || []).forEach(p => {
  8419. const isDefault = p.name.startsWith('default');
  8420. const tr = document.createElement('tr');
  8421. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8422. tr.innerHTML = `
  8423. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8424. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8425. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8426. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8427. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8428. <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>
  8429. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8430. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8431. ${!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>`}
  8432. </td>
  8433. `;
  8434. tbody.appendChild(tr);
  8435. });
  8436. }
  8437. async function loadPPPServers() {
  8438. try {
  8439. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8440. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8441. fetch(`${API_BASE}/vpn/servers/pptp`),
  8442. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8443. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8444. ]);
  8445. if (pppoeRes.ok) {
  8446. state.pppoeServer = await pppoeRes.json();
  8447. const s = state.pppoeServer;
  8448. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8449. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8450. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8451. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8452. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8453. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8454. const pill = document.getElementById('pppoe-server-status-pill');
  8455. if (pill) {
  8456. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8457. 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';
  8458. }
  8459. setDotBadge('ppp-badge-pppoe-state', s.running);
  8460. }
  8461. if (pptpRes.ok) {
  8462. state.pptpServer = await pptpRes.json();
  8463. const s = state.pptpServer;
  8464. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8465. document.getElementById('pptp-server-port').value = s.port || 1723;
  8466. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8467. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8468. const pill = document.getElementById('pptp-server-status-pill');
  8469. if (pill) {
  8470. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8471. 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';
  8472. }
  8473. setDotBadge('ppp-badge-pptp-state', s.running);
  8474. }
  8475. if (l2tpRes.ok) {
  8476. state.l2tpServer = await l2tpRes.json();
  8477. const s = state.l2tpServer;
  8478. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8479. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8480. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8481. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8482. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8483. const pill = document.getElementById('l2tp-server-status-pill');
  8484. if (pill) {
  8485. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8486. 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';
  8487. }
  8488. setDotBadge('ppp-badge-l2tp-state', s.running);
  8489. }
  8490. if (ipsecRes.ok) {
  8491. state.ipsecServer = await ipsecRes.json();
  8492. const s = state.ipsecServer;
  8493. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8494. if (modalEn) modalEn.checked = !!s.enabled;
  8495. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8496. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8497. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8498. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8499. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8500. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8501. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8502. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8503. const pill = document.getElementById('modal-ipsec-server-status');
  8504. if (pill) {
  8505. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8506. 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';
  8507. }
  8508. }
  8509. } catch (err) {
  8510. console.error('Failed to load VPN servers:', err);
  8511. }
  8512. }
  8513. async function loadPPPSessions() {
  8514. try {
  8515. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8516. const data = await res.json();
  8517. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8518. const b = document.getElementById('ppp-badge-active');
  8519. if (b) b.innerText = state.pppActiveSessions.length;
  8520. const sideB = document.getElementById('badge-ppp-sessions');
  8521. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8522. renderPPPSessions();
  8523. } catch (err) {
  8524. console.error('Failed to load active PPP sessions:', err);
  8525. }
  8526. }
  8527. function renderPPPSessions() {
  8528. const tbody = document.getElementById('active-ppp-table-body');
  8529. const empty = document.getElementById('active-ppp-empty');
  8530. if (!tbody) return;
  8531. tbody.innerHTML = '';
  8532. const list = state.pppActiveSessions || [];
  8533. if (list.length === 0) {
  8534. empty?.classList.remove('hidden');
  8535. return;
  8536. }
  8537. empty?.classList.add('hidden');
  8538. list.forEach(s => {
  8539. const tr = document.createElement('tr');
  8540. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8541. tr.innerHTML = `
  8542. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8543. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8544. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8545. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8546. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8547. <td class="py-2.5 px-3 text-[11px]">
  8548. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8549. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8550. </td>
  8551. <td class="py-2.5 px-3 text-right font-sans">
  8552. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8553. </td>
  8554. `;
  8555. tbody.appendChild(tr);
  8556. });
  8557. }
  8558. async function disconnectPPPSession(iface) {
  8559. if (!confirm(`Disconnect session ${iface}?`)) return;
  8560. try {
  8561. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8562. if (res.ok) {
  8563. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8564. loadPPPSessions();
  8565. }
  8566. } catch (err) {
  8567. showToast('Error', err.message, 'error');
  8568. }
  8569. }
  8570. // PPP Secret Modal handlers
  8571. function openAddPPPSecretModal() {
  8572. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8573. document.getElementById('secret-modal-id').value = '';
  8574. document.getElementById('secret-modal-name').value = '';
  8575. document.getElementById('secret-modal-password').value = '';
  8576. document.getElementById('secret-modal-service').value = 'any';
  8577. document.getElementById('secret-modal-profile').value = 'default';
  8578. document.getElementById('secret-modal-local').value = '';
  8579. document.getElementById('secret-modal-remote').value = '';
  8580. document.getElementById('secret-modal-comment').value = '';
  8581. document.getElementById('secret-modal-disabled').checked = false;
  8582. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8583. }
  8584. function openEditPPPSecretModal(id) {
  8585. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8586. if (!s) return;
  8587. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8588. document.getElementById('secret-modal-id').value = s.id;
  8589. document.getElementById('secret-modal-name').value = s.name;
  8590. document.getElementById('secret-modal-password').value = s.password;
  8591. document.getElementById('secret-modal-service').value = s.service || 'any';
  8592. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8593. document.getElementById('secret-modal-local').value = s.local_address || '';
  8594. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8595. document.getElementById('secret-modal-comment').value = s.comment || '';
  8596. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8597. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8598. }
  8599. function closePPPSecretModal() {
  8600. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8601. }
  8602. async function submitSavePPPSecret(e) {
  8603. e.preventDefault();
  8604. const id = document.getElementById('secret-modal-id').value;
  8605. const name = document.getElementById('secret-modal-name').value.trim();
  8606. const password = document.getElementById('secret-modal-password').value.trim();
  8607. const service = document.getElementById('secret-modal-service').value;
  8608. const profile = document.getElementById('secret-modal-profile').value;
  8609. const local = document.getElementById('secret-modal-local').value.trim();
  8610. const remote = document.getElementById('secret-modal-remote').value.trim();
  8611. const comment = document.getElementById('secret-modal-comment').value.trim();
  8612. const disabled = document.getElementById('secret-modal-disabled').checked;
  8613. try {
  8614. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8615. method: 'POST',
  8616. headers: { 'Content-Type': 'application/json' },
  8617. body: JSON.stringify({
  8618. id,
  8619. name,
  8620. password,
  8621. service,
  8622. profile,
  8623. local_address: local,
  8624. remote_address: remote,
  8625. comment,
  8626. disabled
  8627. })
  8628. });
  8629. if (res.ok) {
  8630. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8631. closePPPSecretModal();
  8632. loadPPPSecrets();
  8633. } else {
  8634. const err = await res.json();
  8635. showToast('Error', err.message, 'error');
  8636. }
  8637. } catch (err) {
  8638. showToast('Error', err.message, 'error');
  8639. }
  8640. }
  8641. async function togglePPPSecretState(id, disabled) {
  8642. try {
  8643. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8644. method: 'POST',
  8645. headers: { 'Content-Type': 'application/json' },
  8646. body: JSON.stringify({ disabled })
  8647. });
  8648. if (res.ok) {
  8649. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8650. loadPPPSecrets();
  8651. }
  8652. } catch (err) {
  8653. showToast('Error', err.message, 'error');
  8654. }
  8655. }
  8656. async function deletePPPSecret(id) {
  8657. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8658. try {
  8659. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8660. if (res.ok) {
  8661. showToast('Deleted', 'Secret account removed', 'success');
  8662. loadPPPSecrets();
  8663. }
  8664. } catch (err) {
  8665. showToast('Error', err.message, 'error');
  8666. }
  8667. }
  8668. // PPP Profile Modal handlers
  8669. function openAddPPPProfileModal() {
  8670. document.getElementById('profile-modal-name').value = '';
  8671. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8672. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8673. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8674. document.getElementById('profile-modal-encryption').value = 'required';
  8675. document.getElementById('profile-modal-onlyone').checked = true;
  8676. document.getElementById('profile-modal-comment').value = '';
  8677. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8678. }
  8679. function closePPPProfileModal() {
  8680. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8681. }
  8682. async function submitSavePPPProfile(e) {
  8683. e.preventDefault();
  8684. const name = document.getElementById('profile-modal-name').value.trim();
  8685. const local = document.getElementById('profile-modal-local').value.trim();
  8686. const remote = document.getElementById('profile-modal-remote').value.trim();
  8687. const dns = document.getElementById('profile-modal-dns').value.trim();
  8688. const enc = document.getElementById('profile-modal-encryption').value;
  8689. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8690. const comment = document.getElementById('profile-modal-comment').value.trim();
  8691. try {
  8692. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8693. method: 'POST',
  8694. headers: { 'Content-Type': 'application/json' },
  8695. body: JSON.stringify({
  8696. id: name,
  8697. name,
  8698. local_address: local,
  8699. remote_address: remote,
  8700. dns_servers: dns,
  8701. use_encryption: enc,
  8702. only_one: onlyone,
  8703. comment
  8704. })
  8705. });
  8706. if (res.ok) {
  8707. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8708. closePPPProfileModal();
  8709. loadPPPProfiles();
  8710. } else {
  8711. const err = await res.json();
  8712. showToast('Error', err.message, 'error');
  8713. }
  8714. } catch (err) {
  8715. showToast('Error', err.message, 'error');
  8716. }
  8717. }
  8718. async function deletePPPProfile(name) {
  8719. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8720. try {
  8721. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8722. if (res.ok) {
  8723. showToast('Deleted', 'Profile removed', 'success');
  8724. loadPPPProfiles();
  8725. } else {
  8726. const err = await res.json();
  8727. showToast('Error', err.message, 'error');
  8728. }
  8729. } catch (err) {
  8730. showToast('Error', err.message, 'error');
  8731. }
  8732. }
  8733. // Server Config submissions
  8734. async function savePPPoEServerConfig(e) {
  8735. e.preventDefault();
  8736. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8737. const name = document.getElementById('pppoe-server-name').value.trim();
  8738. const iface = document.getElementById('pppoe-server-iface').value;
  8739. const profile = document.getElementById('pppoe-server-profile').value;
  8740. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8741. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8742. try {
  8743. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8744. method: 'POST',
  8745. headers: { 'Content-Type': 'application/json' },
  8746. body: JSON.stringify({
  8747. enabled,
  8748. service_name: name,
  8749. interface: iface,
  8750. default_profile: profile,
  8751. max_mtu: mtu,
  8752. max_mru: mtu,
  8753. one_session_per_host: onesession
  8754. })
  8755. });
  8756. if (res.ok) {
  8757. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8758. loadPPPServers();
  8759. fetchData(false);
  8760. } else {
  8761. const err = await res.json();
  8762. showToast('Error', err.message, 'error');
  8763. }
  8764. } catch (err) {
  8765. showToast('Error', err.message, 'error');
  8766. }
  8767. }
  8768. async function savePPTPServerConfig(e) {
  8769. e.preventDefault();
  8770. const enabled = document.getElementById('pptp-server-enabled').checked;
  8771. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8772. const profile = document.getElementById('pptp-server-profile').value;
  8773. const mppe = document.getElementById('pptp-server-mppe').checked;
  8774. try {
  8775. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8776. method: 'POST',
  8777. headers: { 'Content-Type': 'application/json' },
  8778. body: JSON.stringify({
  8779. enabled,
  8780. port,
  8781. default_profile: profile,
  8782. require_mppe: mppe
  8783. })
  8784. });
  8785. if (res.ok) {
  8786. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8787. loadPPPServers();
  8788. fetchData(false);
  8789. } else {
  8790. const err = await res.json();
  8791. showToast('Error', err.message, 'error');
  8792. }
  8793. } catch (err) {
  8794. showToast('Error', err.message, 'error');
  8795. }
  8796. }
  8797. async function saveL2TPServerConfig(e) {
  8798. e.preventDefault();
  8799. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8800. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8801. const profile = document.getElementById('l2tp-server-profile').value;
  8802. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8803. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8804. try {
  8805. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8806. method: 'POST',
  8807. headers: { 'Content-Type': 'application/json' },
  8808. body: JSON.stringify({
  8809. enabled,
  8810. port,
  8811. default_profile: profile,
  8812. use_ipsec: useipsec,
  8813. ipsec_secret: psk
  8814. })
  8815. });
  8816. if (res.ok) {
  8817. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8818. loadPPPServers();
  8819. fetchData(false);
  8820. } else {
  8821. const err = await res.json();
  8822. showToast('Error', err.message, 'error');
  8823. }
  8824. } catch (err) {
  8825. showToast('Error', err.message, 'error');
  8826. }
  8827. }
  8828. // IPSec Server Modal
  8829. function openIPSecServerModal() {
  8830. loadPPPServers();
  8831. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8832. }
  8833. function closeIPSecServerModal() {
  8834. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8835. }
  8836. async function submitSaveIPSecServer(e) {
  8837. e.preventDefault();
  8838. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8839. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8840. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8841. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8842. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8843. try {
  8844. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8845. method: 'POST',
  8846. headers: { 'Content-Type': 'application/json' },
  8847. body: JSON.stringify({
  8848. enabled,
  8849. preshared_key: psk,
  8850. pool_address: pool,
  8851. dns_servers: dns,
  8852. local_subnet: subnet
  8853. })
  8854. });
  8855. if (res.ok) {
  8856. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8857. closeIPSecServerModal();
  8858. loadPPPServers();
  8859. fetchData(false);
  8860. } else {
  8861. const err = await res.json();
  8862. showToast('Error', err.message, 'error');
  8863. }
  8864. } catch (err) {
  8865. showToast('Error', err.message, 'error');
  8866. }
  8867. }
  8868. // WireGuard Client Config Viewer
  8869. let currentWGClientConf = '';
  8870. async function openWGClientConfModal(iface, clientIP) {
  8871. try {
  8872. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8873. method: 'POST',
  8874. headers: { 'Content-Type': 'application/json' },
  8875. body: JSON.stringify({
  8876. interface: iface,
  8877. address: clientIP || '10.10.0.2/32',
  8878. dns: '1.1.1.1, 8.8.8.8'
  8879. })
  8880. });
  8881. if (res.ok) {
  8882. const data = await res.json();
  8883. currentWGClientConf = data.config;
  8884. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8885. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8886. } else {
  8887. const err = await res.json();
  8888. showToast('Error', err.message, 'error');
  8889. }
  8890. } catch (err) {
  8891. showToast('Error', err.message, 'error');
  8892. }
  8893. }
  8894. function closeWGClientConfModal() {
  8895. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8896. }
  8897. function copyWGClientConf() {
  8898. if (!currentWGClientConf) return;
  8899. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8900. }
  8901. function downloadWGClientConf() {
  8902. if (!currentWGClientConf) return;
  8903. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8904. const a = document.createElement('a');
  8905. a.href = URL.createObjectURL(blob);
  8906. a.download = 'wireguard-client.conf';
  8907. document.body.appendChild(a);
  8908. a.click();
  8909. document.body.removeChild(a);
  8910. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8911. }
  8912. // =========================================================================
  8913. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8914. // =========================================================================
  8915. state.activeDynSubTab = 'bgp-peers';
  8916. state.activeBgpSubTab = 'bgp-peers';
  8917. state.activeOspfTab = 'instances';
  8918. state.bgpInstance = null;
  8919. state.bgpPeers = [];
  8920. state.bgpNets = [];
  8921. state.bgpRoutes = [];
  8922. state.ospfInstance = null;
  8923. state.ospfInstances = [];
  8924. state.ospfAreas = [];
  8925. state.ospfAreaRanges = [];
  8926. state.ospfTemplates = [];
  8927. state.ospfLiveInterfaces = [];
  8928. state.ospfStaticNbrs = [];
  8929. state.ospfNeighbors = [];
  8930. state.ospfLSA = [];
  8931. state.ospfRoutes = [];
  8932. state.selectedOspfRow = {
  8933. instances: null,
  8934. areas: null,
  8935. 'area-ranges': null,
  8936. templates: null,
  8937. interfaces: null,
  8938. 'static-nbrs': null,
  8939. neighbors: null,
  8940. lsa: null,
  8941. };
  8942. state.ospfSort = {
  8943. instances: { col: 'name', asc: true },
  8944. areas: { col: 'name', asc: true },
  8945. ranges: { col: 'area', asc: true },
  8946. templates: { col: 'interfaces', asc: true },
  8947. live_ifaces: { col: 'interface', asc: true },
  8948. snbrs: { col: 'address', asc: true },
  8949. neighbors: { col: 'address', asc: true },
  8950. lsa: { col: 'instance', asc: true },
  8951. };
  8952. function switchBgpSubTab(subTab) {
  8953. state.activeBgpSubTab = subTab;
  8954. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8955. tabs.forEach(t => {
  8956. const el = document.getElementById(`dyn-subtab-${t}`);
  8957. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8958. if (el) el.classList.toggle('hidden', t !== subTab);
  8959. if (btn) {
  8960. if (t === subTab) {
  8961. 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';
  8962. } else {
  8963. 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';
  8964. }
  8965. }
  8966. });
  8967. }
  8968. function switchOspfTab(tabName) {
  8969. state.activeOspfTab = tabName;
  8970. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8971. tabs.forEach(t => {
  8972. const pane = document.getElementById(`ospf-pane-${t}`);
  8973. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8974. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8975. if (btn) {
  8976. if (t === tabName) {
  8977. 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';
  8978. } else {
  8979. 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';
  8980. }
  8981. }
  8982. });
  8983. }
  8984. function switchOspfSubTab(tab) {
  8985. // Legacy alias
  8986. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8987. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8988. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8989. else switchOspfTab('instances');
  8990. }
  8991. function switchDynSubTab(subTab) {
  8992. if (subTab.startsWith('bgp')) {
  8993. if (state.activeTab !== 'bgp') navigate('bgp');
  8994. switchBgpSubTab(subTab);
  8995. } else if (subTab.startsWith('ospf')) {
  8996. if (state.activeTab !== 'ospf') navigate('ospf');
  8997. switchOspfTab('instances');
  8998. }
  8999. }
  9000. async function loadDynamicRouting(showToastMsg = false) {
  9001. try {
  9002. const routingTab = state.activeTab === 'dynamic-routing' ? 'bgp' : state.activeTab;
  9003. const routingViews = new Set(['bgp', 'ospf', 'rip', 'bfd', 'babel', 'radv', 'eigrp', 'routing-filters']);
  9004. const fetchSafeJson = async (url) => {
  9005. const match = url.match(/\/routing\/(bgp|ospf|rip|bfd|babel|radv|eigrp)\//);
  9006. if (routingViews.has(routingTab) && match && match[1] !== routingTab) return null;
  9007. try {
  9008. const r = await fetch(url);
  9009. return r.ok ? await r.json() : null;
  9010. } catch (e) {
  9011. return null;
  9012. }
  9013. };
  9014. const [
  9015. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  9016. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  9017. commLists, asLists,
  9018. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  9019. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  9020. babelInsts, babelIfaces, babelLiveIfaces, babelNbrs, babelRoutes,
  9021. radvInsts, radvIfaces,
  9022. eigrpInsts, eigrpIfaces, eigrpNets, eigrpNbrs, eigrpTopology
  9023. ] = await Promise.all([
  9024. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  9025. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  9026. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  9027. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  9028. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  9029. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  9030. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  9031. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  9032. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  9033. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  9034. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  9035. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  9036. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  9037. fetchSafeJson(`${API_BASE}/routing/filters`),
  9038. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  9039. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`),
  9040. fetchSafeJson(`${API_BASE}/routing/rip/instances`),
  9041. fetchSafeJson(`${API_BASE}/routing/rip/interfaces`),
  9042. fetchSafeJson(`${API_BASE}/routing/rip/neighbors-live`),
  9043. fetchSafeJson(`${API_BASE}/routing/rip/routes`),
  9044. fetchSafeJson(`${API_BASE}/routing/bfd/instance`),
  9045. fetchSafeJson(`${API_BASE}/routing/bfd/interfaces`),
  9046. fetchSafeJson(`${API_BASE}/routing/bfd/peers`),
  9047. fetchSafeJson(`${API_BASE}/routing/bfd/sessions`),
  9048. fetchSafeJson(`${API_BASE}/routing/babel/instances`),
  9049. fetchSafeJson(`${API_BASE}/routing/babel/interfaces`),
  9050. fetchSafeJson(`${API_BASE}/routing/babel/interfaces-live`),
  9051. fetchSafeJson(`${API_BASE}/routing/babel/neighbors`),
  9052. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  9053. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  9054. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`),
  9055. fetchSafeJson(`${API_BASE}/routing/eigrp/instances`),
  9056. fetchSafeJson(`${API_BASE}/routing/eigrp/interfaces`),
  9057. fetchSafeJson(`${API_BASE}/routing/eigrp/networks`),
  9058. fetchSafeJson(`${API_BASE}/routing/eigrp/neighbors`),
  9059. fetchSafeJson(`${API_BASE}/routing/eigrp/topology`)
  9060. ]);
  9061. if (sum) state.dynSummary = sum;
  9062. if (bgpInst) state.bgpInstance = bgpInst;
  9063. if (bgpPeers) state.bgpPeers = bgpPeers;
  9064. if (bgpNets) state.bgpNets = bgpNets;
  9065. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  9066. if (ospfInsts) state.ospfInstances = ospfInsts;
  9067. if (ospfAreas) state.ospfAreas = ospfAreas;
  9068. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  9069. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  9070. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  9071. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  9072. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  9073. if (ospfLsa) state.ospfLSA = ospfLsa;
  9074. if (filters) state.routingFilters = filters;
  9075. if (commLists) state.routingCommunityLists = commLists;
  9076. if (asLists) state.routingASLists = asLists;
  9077. if (ripInsts) state.ripInstances = ripInsts;
  9078. if (ripIfaces) state.ripInterfaces = ripIfaces;
  9079. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  9080. if (ripRoutes) state.ripRoutes = ripRoutes;
  9081. if (bfdInst) state.bfdInstance = bfdInst;
  9082. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  9083. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  9084. if (bfdSessions) state.bfdSessions = bfdSessions;
  9085. if (babelInsts) state.babelInstances = babelInsts;
  9086. if (babelIfaces) state.babelInterfaces = babelIfaces;
  9087. if (babelLiveIfaces) state.babelInterfacesLive = babelLiveIfaces;
  9088. if (babelNbrs) state.babelNeighbors = babelNbrs;
  9089. if (babelRoutes) state.babelRoutes = babelRoutes;
  9090. if (radvInsts) state.radvInstances = radvInsts;
  9091. if (radvIfaces) state.radvInterfaces = radvIfaces;
  9092. if (eigrpInsts) state.eigrpInstances = eigrpInsts;
  9093. if (eigrpIfaces) state.eigrpInterfaces = eigrpIfaces;
  9094. if (eigrpNets) state.eigrpNetworks = eigrpNets;
  9095. if (eigrpNbrs) state.eigrpNeighbors = eigrpNbrs;
  9096. if (eigrpTopology) state.eigrpTopology = eigrpTopology;
  9097. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  9098. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  9099. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  9100. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  9101. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  9102. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  9103. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  9104. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  9105. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  9106. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9107. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9108. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9109. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9110. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9111. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9112. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9113. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9114. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9115. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9116. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9117. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9118. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9119. try { renderBabelLiveInterfaces(); } catch(e) { console.error('renderBabelLiveInterfaces error:', e); }
  9120. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9121. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9122. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9123. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9124. try { renderEigrpInstances(); } catch(e) { console.error('renderEigrpInstances error:', e); }
  9125. try { renderEigrpNetworks(); } catch(e) { console.error('renderEigrpNetworks error:', e); }
  9126. try { renderEigrpInterfaces(); } catch(e) { console.error('renderEigrpInterfaces error:', e); }
  9127. try { renderEigrpNeighbors(); } catch(e) { console.error('renderEigrpNeighbors error:', e); }
  9128. try { renderEigrpTopology(); } catch(e) { console.error('renderEigrpTopology error:', e); }
  9129. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9130. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9131. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9132. } catch (err) {
  9133. console.error('Failed to load dynamic routing:', err);
  9134. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9135. }
  9136. }
  9137. async function loadOspfAll() {
  9138. await loadDynamicRouting(true);
  9139. }
  9140. function renderBgpStatusPill() {
  9141. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9142. pills.forEach(pill => {
  9143. const inst = state.bgpInstance;
  9144. if (!inst || !inst.enabled) {
  9145. 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';
  9146. pill.innerText = 'BGP DISABLED';
  9147. } else if (inst.running) {
  9148. 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';
  9149. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9150. } else {
  9151. 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';
  9152. pill.innerText = 'BGP STARTING...';
  9153. }
  9154. });
  9155. }
  9156. function renderBgpPeers() {
  9157. const tbody = document.getElementById('bgp-peers-table-body');
  9158. if (!tbody) return;
  9159. const empty = document.getElementById('bgp-peers-empty');
  9160. const countBadge = document.getElementById('bgp-peers-count-badge');
  9161. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9162. const peers = state.bgpPeers || [];
  9163. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9164. if (navBadge) navBadge.innerText = peers.length;
  9165. if (peers.length === 0) {
  9166. tbody.innerHTML = '';
  9167. if (empty) empty.classList.remove('hidden');
  9168. return;
  9169. }
  9170. if (empty) empty.classList.add('hidden');
  9171. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9172. if (tbody.dataset.sig === sig) return;
  9173. tbody.dataset.sig = sig;
  9174. tbody.innerHTML = peers.map(p => {
  9175. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9176. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9177. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9178. let stateBadge = '';
  9179. if (p.disabled) {
  9180. 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>';
  9181. } else if (p.state === 'Established') {
  9182. 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>';
  9183. } else if (p.state === 'Connect' || p.state === 'Active') {
  9184. 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>`;
  9185. } else {
  9186. 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>`;
  9187. }
  9188. return `
  9189. <tr class="hover:bg-slate-800/40 transition">
  9190. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9191. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9192. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9193. <td class="py-2.5 px-3">
  9194. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9195. ${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>`}
  9196. </td>
  9197. <td class="py-2.5 px-3">${stateBadge}</td>
  9198. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9199. <td class="py-2.5 px-3 text-slate-300">
  9200. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9201. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9202. </td>
  9203. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9204. ${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> ` : ''}
  9205. ${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>` : ''}
  9206. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9207. </td>
  9208. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9209. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9210. <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'}">
  9211. ${p.disabled ? 'Enable' : 'Disable'}
  9212. </button>
  9213. <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">
  9214. Edit
  9215. </button>
  9216. <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">
  9217. Delete
  9218. </button>
  9219. </td>
  9220. </tr>
  9221. `;
  9222. }).join('');
  9223. }
  9224. function renderBgpNetworks() {
  9225. const tbody = document.getElementById('bgp-nets-table-body');
  9226. if (!tbody) return;
  9227. const empty = document.getElementById('bgp-nets-empty');
  9228. const countBadge = document.getElementById('bgp-nets-count-badge');
  9229. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9230. const nets = state.bgpNets || [];
  9231. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9232. if (navBadge) navBadge.innerText = nets.length;
  9233. if (nets.length === 0) {
  9234. tbody.innerHTML = '';
  9235. if (empty) empty.classList.remove('hidden');
  9236. return;
  9237. }
  9238. if (empty) empty.classList.add('hidden');
  9239. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9240. if (tbody.dataset.sig === sig) return;
  9241. tbody.dataset.sig = sig;
  9242. tbody.innerHTML = nets.map(n => `
  9243. <tr class="hover:bg-slate-800/40 transition">
  9244. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9245. <td class="py-2.5 px-3">
  9246. ${n.disabled
  9247. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9248. : '<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>'}
  9249. </td>
  9250. <td class="py-2.5 px-3">
  9251. ${n.disabled
  9252. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9253. : '<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>'}
  9254. </td>
  9255. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9256. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9257. <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">
  9258. Delete
  9259. </button>
  9260. </td>
  9261. </tr>
  9262. `).join('');
  9263. }
  9264. function renderBgpRoutes() {
  9265. const tbody = document.getElementById('bgp-routes-table-body');
  9266. if (!tbody) return;
  9267. const empty = document.getElementById('bgp-routes-empty');
  9268. const countBadge = document.getElementById('bgp-routes-count-badge');
  9269. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9270. const routes = state.bgpRoutes || [];
  9271. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9272. if (navBadge) navBadge.innerText = routes.length;
  9273. if (routes.length === 0) {
  9274. tbody.innerHTML = '';
  9275. if (empty) empty.classList.remove('hidden');
  9276. return;
  9277. }
  9278. if (empty) empty.classList.add('hidden');
  9279. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9280. if (tbody.dataset.sig === sig) return;
  9281. tbody.dataset.sig = sig;
  9282. tbody.innerHTML = routes.map(r => `
  9283. <tr class="hover:bg-slate-800/40 transition">
  9284. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9285. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9286. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9287. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9288. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9289. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9290. </tr>
  9291. `).join('');
  9292. }
  9293. // =========================================================================
  9294. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9295. // =========================================================================
  9296. function sortOspfTable(tab, col) {
  9297. if (!state.ospfSort) state.ospfSort = {};
  9298. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9299. if (state.ospfSort[tab].col === col) {
  9300. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9301. } else {
  9302. state.ospfSort[tab].col = col;
  9303. state.ospfSort[tab].asc = true;
  9304. }
  9305. const asc = state.ospfSort[tab].asc;
  9306. let list = [];
  9307. if (tab === 'instances') list = state.ospfInstances || [];
  9308. else if (tab === 'areas') list = state.ospfAreas || [];
  9309. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9310. else if (tab === 'templates') list = state.ospfTemplates || [];
  9311. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9312. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9313. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9314. else if (tab === 'lsa') list = state.ospfLSA || [];
  9315. list.sort((a, b) => {
  9316. let valA = a[col] ?? '';
  9317. let valB = b[col] ?? '';
  9318. if (typeof valA === 'number' && typeof valB === 'number') {
  9319. return asc ? valA - valB : valB - valA;
  9320. }
  9321. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9322. });
  9323. if (tab === 'instances') renderOspfInstances();
  9324. else if (tab === 'areas') renderOspfAreas();
  9325. else if (tab === 'ranges') renderOspfAreaRanges();
  9326. else if (tab === 'templates') renderOspfTemplates();
  9327. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9328. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9329. else if (tab === 'neighbors') renderOspfNeighbors();
  9330. else if (tab === 'lsa') renderOspfLSA();
  9331. }
  9332. function selectOspfRow(tab, id) {
  9333. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9334. state.selectedOspfRow[tab] = id;
  9335. if (tab === 'instances') {
  9336. renderOspfInstances();
  9337. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9338. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9339. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9340. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9341. if (btnEn) btnEn.disabled = false;
  9342. if (btnDis) btnDis.disabled = false;
  9343. if (btnRem) btnRem.disabled = false;
  9344. if (btnCom) btnCom.disabled = false;
  9345. } else if (tab === 'areas') {
  9346. renderOspfAreas();
  9347. const btnEn = document.getElementById('btn-ospf-area-enable');
  9348. const btnDis = document.getElementById('btn-ospf-area-disable');
  9349. const btnRem = document.getElementById('btn-ospf-area-remove');
  9350. const btnCom = document.getElementById('btn-ospf-area-comment');
  9351. if (btnEn) btnEn.disabled = false;
  9352. if (btnDis) btnDis.disabled = false;
  9353. if (btnRem) btnRem.disabled = false;
  9354. if (btnCom) btnCom.disabled = false;
  9355. } else if (tab === 'ranges') {
  9356. renderOspfAreaRanges();
  9357. const btnEn = document.getElementById('btn-ospf-range-enable');
  9358. const btnDis = document.getElementById('btn-ospf-range-disable');
  9359. const btnRem = document.getElementById('btn-ospf-range-remove');
  9360. const btnCom = document.getElementById('btn-ospf-range-comment');
  9361. if (btnEn) btnEn.disabled = false;
  9362. if (btnDis) btnDis.disabled = false;
  9363. if (btnRem) btnRem.disabled = false;
  9364. if (btnCom) btnCom.disabled = false;
  9365. } else if (tab === 'templates') {
  9366. renderOspfTemplates();
  9367. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9368. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9369. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9370. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9371. if (btnEn) btnEn.disabled = false;
  9372. if (btnDis) btnDis.disabled = false;
  9373. if (btnRem) btnRem.disabled = false;
  9374. if (btnCom) btnCom.disabled = false;
  9375. } else if (tab === 'snbrs') {
  9376. renderOspfStaticNbrs();
  9377. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9378. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9379. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9380. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9381. if (btnEn) btnEn.disabled = false;
  9382. if (btnDis) btnDis.disabled = false;
  9383. if (btnRem) btnRem.disabled = false;
  9384. if (btnCom) btnCom.disabled = false;
  9385. }
  9386. }
  9387. // TAB 1: INSTANCES
  9388. function renderOspfInstances() {
  9389. const tbody = document.getElementById('ospf-instances-table-body');
  9390. if (!tbody) return;
  9391. const countEl = document.getElementById('ospf-instances-footer-count');
  9392. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9393. let list = state.ospfInstances || [];
  9394. if (filter) {
  9395. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9396. }
  9397. if (countEl) countEl.innerText = list.length;
  9398. const selId = state.selectedOspfRow?.instances;
  9399. tbody.innerHTML = list.map((inst, idx) => {
  9400. const isSel = inst.id === selId;
  9401. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9402. const flagD = inst.disabled
  9403. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  9404. : (inst.running
  9405. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  9406. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  9407. const redist = [];
  9408. if (inst.redistribute_connected) redist.push('conn');
  9409. if (inst.redistribute_static) redist.push('static');
  9410. if (inst.redistribute_bgp) redist.push('bgp');
  9411. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9412. redist.push('default');
  9413. }
  9414. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9415. const origBadge = origDef === 'always'
  9416. ? '<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>'
  9417. : (origDef === 'if-installed'
  9418. ? '<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>'
  9419. : '<span class="text-slate-500 text-[10px]">never</span>');
  9420. const filterBadges = [];
  9421. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  9422. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  9423. return `
  9424. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9425. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9426. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  9427. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9428. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9429. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9430. ${filterBadges.join(' ')}
  9431. </td>
  9432. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9433. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9434. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9435. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9436. <td class="py-1.5 px-3">${origBadge}</td>
  9437. </tr>
  9438. `;
  9439. }).join('');
  9440. }
  9441. // TAB 2: AREAS
  9442. function renderOspfAreas() {
  9443. const tbody = document.getElementById('ospf-areas-table-body');
  9444. if (!tbody) return;
  9445. const countEl = document.getElementById('ospf-areas-footer-count');
  9446. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9447. let list = state.ospfAreas || [];
  9448. if (filter) {
  9449. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9450. }
  9451. if (countEl) countEl.innerText = list.length;
  9452. const selId = state.selectedOspfRow?.areas;
  9453. tbody.innerHTML = list.map((a, idx) => {
  9454. const isSel = a.id === selId;
  9455. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9456. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9457. return `
  9458. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9459. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9460. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9461. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9462. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9463. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9464. </td>
  9465. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9466. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9467. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9468. </tr>
  9469. `;
  9470. }).join('');
  9471. }
  9472. // TAB 3: AREA RANGES
  9473. function renderOspfAreaRanges() {
  9474. const tbody = document.getElementById('ospf-ranges-table-body');
  9475. if (!tbody) return;
  9476. const countEl = document.getElementById('ospf-ranges-footer-count');
  9477. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9478. let list = state.ospfAreaRanges || [];
  9479. if (filter) {
  9480. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9481. }
  9482. if (countEl) countEl.innerText = list.length;
  9483. const selId = state.selectedOspfRow?.['area-ranges'];
  9484. tbody.innerHTML = list.map((r, idx) => {
  9485. const isSel = r.id === selId;
  9486. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9487. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9488. return `
  9489. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9490. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9491. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9492. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9493. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9494. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9495. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9496. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9497. </tr>
  9498. `;
  9499. }).join('');
  9500. }
  9501. // TAB 4: INTERFACE TEMPLATES
  9502. function renderOspfTemplates() {
  9503. const tbody = document.getElementById('ospf-templates-table-body');
  9504. if (!tbody) return;
  9505. const countEl = document.getElementById('ospf-templates-footer-count');
  9506. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9507. let list = state.ospfTemplates || [];
  9508. if (filter) {
  9509. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9510. }
  9511. if (countEl) countEl.innerText = list.length;
  9512. const selId = state.selectedOspfRow?.templates;
  9513. tbody.innerHTML = list.map((t, idx) => {
  9514. const isSel = t.id === selId;
  9515. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9516. const ifaces = t.interfaces || t.interface || 'all';
  9517. const nets = t.networks || t.network || '';
  9518. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9519. return `
  9520. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9521. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9522. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9523. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9524. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9525. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9526. </td>
  9527. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9528. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9529. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9530. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9531. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9532. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9533. </tr>
  9534. `;
  9535. }).join('');
  9536. }
  9537. // TAB 5: LIVE INTERFACES
  9538. function renderOspfLiveInterfaces() {
  9539. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9540. if (!tbody) return;
  9541. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9542. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9543. let list = state.ospfLiveInterfaces || [];
  9544. if (filter) {
  9545. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9546. }
  9547. if (countEl) countEl.innerText = list.length;
  9548. tbody.innerHTML = list.map(i => `
  9549. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9550. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9551. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9552. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9553. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9554. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9555. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9556. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9557. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9558. </tr>
  9559. `).join('');
  9560. }
  9561. // TAB 6: STATIC NEIGHBORS
  9562. function renderOspfStaticNbrs() {
  9563. const tbody = document.getElementById('ospf-snbrs-table-body');
  9564. if (!tbody) return;
  9565. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9566. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9567. let list = state.ospfStaticNbrs || [];
  9568. if (filter) {
  9569. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9570. }
  9571. if (countEl) countEl.innerText = list.length;
  9572. const selId = state.selectedOspfRow?.['static-nbrs'];
  9573. tbody.innerHTML = list.map((n, idx) => {
  9574. const isSel = n.id === selId;
  9575. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9576. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9577. return `
  9578. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9579. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9580. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9581. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9582. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9583. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9584. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9585. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9586. </tr>
  9587. `;
  9588. }).join('');
  9589. }
  9590. // TAB 7: LIVE NEIGHBORS
  9591. function renderOspfNeighbors() {
  9592. const tbody = document.getElementById('ospf-neighbors-table-body');
  9593. if (!tbody) return;
  9594. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9595. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9596. let list = state.ospfNeighbors || [];
  9597. if (filter) {
  9598. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9599. }
  9600. if (countEl) countEl.innerText = list.length;
  9601. tbody.innerHTML = list.map(n => `
  9602. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9603. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9604. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9605. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9606. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9607. </td>
  9608. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9609. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9610. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9611. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9612. </tr>
  9613. `).join('');
  9614. }
  9615. // TAB 8: LINK-STATE DATABASE (LSA)
  9616. function renderOspfLSA() {
  9617. const tbody = document.getElementById('ospf-lsa-table-body');
  9618. if (!tbody) return;
  9619. const countEl = document.getElementById('ospf-lsa-footer-count');
  9620. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9621. let list = state.ospfLSA || [];
  9622. if (filter) {
  9623. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9624. }
  9625. if (countEl) countEl.innerText = list.length;
  9626. tbody.innerHTML = list.map(l => `
  9627. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9628. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9629. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9630. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9631. </td>
  9632. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9633. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9634. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9635. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9636. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9637. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9638. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9639. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9640. </tr>
  9641. `).join('');
  9642. }
  9643. function renderOspfStatusPill() {
  9644. // Maintained for backward compatibility
  9645. const pill = document.getElementById('ospf-live-status-pill');
  9646. if (!pill) return;
  9647. 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';
  9648. pill.innerText = 'OSPF ACTIVE';
  9649. }
  9650. function renderOspfInterfaces() {
  9651. renderOspfTemplates();
  9652. }
  9653. function renderOspfRoutes() {
  9654. // Routes retained in background
  9655. }
  9656. // BGP Modals & Actions
  9657. function openBgpInstanceModal() {
  9658. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9659. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9660. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9661. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9662. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9663. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9664. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9665. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9666. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9667. document.getElementById('modal-bgp-in-filter').value = inst.in_filter || '';
  9668. document.getElementById('modal-bgp-out-filter').value = inst.out_filter || '';
  9669. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9670. }
  9671. function closeBgpInstanceModal() {
  9672. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9673. }
  9674. async function submitBgpInstance(e) {
  9675. e.preventDefault();
  9676. const payload = {
  9677. enabled: document.getElementById('modal-bgp-enabled').checked,
  9678. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9679. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9680. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9681. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9682. in_filter: (document.getElementById('modal-bgp-in-filter')?.value || '').trim(),
  9683. out_filter: (document.getElementById('modal-bgp-out-filter')?.value || '').trim(),
  9684. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9685. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9686. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9687. };
  9688. try {
  9689. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9690. method: 'POST',
  9691. headers: { 'Content-Type': 'application/json' },
  9692. body: JSON.stringify(payload)
  9693. });
  9694. if (res.ok) {
  9695. closeBgpInstanceModal();
  9696. showToast('Success', 'BGP instance configuration updated', 'success');
  9697. loadDynamicRouting();
  9698. } else {
  9699. const err = await res.json();
  9700. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9701. }
  9702. } catch (err) {
  9703. showToast('Error', err.message, 'error');
  9704. }
  9705. }
  9706. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9707. function switchBgpPeerModalTab(tab) {
  9708. // Normalize legacy tab names
  9709. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9710. if (tab === 'attributes') tab = 'networks';
  9711. const tabs = ['general', 'filters', 'networks'];
  9712. tabs.forEach(t => {
  9713. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9714. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9715. if (t === tab) {
  9716. if (pane) pane.classList.remove('hidden');
  9717. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9718. } else {
  9719. if (pane) pane.classList.add('hidden');
  9720. 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';
  9721. }
  9722. });
  9723. }
  9724. function addOutputNetworkRow(val = '') {
  9725. const container = document.getElementById('modal-bgp-output-networks-container');
  9726. if (!container) return;
  9727. const row = document.createElement('div');
  9728. row.className = 'flex items-center gap-2 output-net-row';
  9729. row.innerHTML = `
  9730. <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">
  9731. <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>
  9732. `;
  9733. container.appendChild(row);
  9734. }
  9735. function parseBgpTime(val) {
  9736. if (!val) return 0;
  9737. val = String(val).trim();
  9738. if (val.includes(':')) {
  9739. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9740. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9741. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9742. }
  9743. return parseInt(val, 10) || 0;
  9744. }
  9745. function formatBgpTime(secs) {
  9746. if (!secs || secs <= 0) return '30';
  9747. return String(secs);
  9748. }
  9749. function populateBgpRoutingTables() {
  9750. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9751. if (!sel) return;
  9752. const cur = sel.value || 'main';
  9753. sel.innerHTML = '<option value="main">main</option>';
  9754. (state.routingTables || []).forEach(t => {
  9755. if (t.name !== 'main') {
  9756. const opt = document.createElement('option');
  9757. opt.value = t.name;
  9758. opt.innerText = t.name;
  9759. sel.appendChild(opt);
  9760. }
  9761. });
  9762. sel.value = cur;
  9763. }
  9764. function populateBgpLocalAddrDatalist() {
  9765. const dlBgp = document.getElementById('bgp-peer-local-addr-datalist');
  9766. if (!dlBgp) return;
  9767. const addrs = [];
  9768. (state.interfaces || []).forEach(iface => {
  9769. if (iface.ip) addrs.push(iface.ip.split('/')[0]);
  9770. (iface.addresses || []).forEach(a => addrs.push(a.split('/')[0]));
  9771. });
  9772. dlBgp.innerHTML = Array.from(new Set(addrs.filter(Boolean))).map(ip => `<option value="${escapeHtml(ip)}">`).join('');
  9773. }
  9774. function openAddBgpPeerModal() {
  9775. document.getElementById('bgp-peer-form').reset();
  9776. document.getElementById('modal-bgp-peer-id').value = '';
  9777. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9778. populateBgpLocalAddrDatalist();
  9779. // General Tab
  9780. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9781. document.getElementById('modal-bgp-peer-name').value = '';
  9782. document.getElementById('modal-bgp-peer-comment').value = '';
  9783. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9784. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9785. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9786. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9787. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9788. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9789. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9790. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9791. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9792. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9793. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9794. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9795. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9796. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9797. // Filters Tab
  9798. populateFilterChainsDatalist();
  9799. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9800. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9801. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9802. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9803. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9804. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9805. // Advertised Networks Tab
  9806. const container = document.getElementById('modal-bgp-output-networks-container');
  9807. if (container) {
  9808. container.innerHTML = '';
  9809. addOutputNetworkRow('');
  9810. }
  9811. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9812. if (removeBtn) removeBtn.classList.add('hidden');
  9813. switchBgpPeerModalTab('general');
  9814. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9815. }
  9816. function populateFilterChainsDatalist() {
  9817. const dl = document.getElementById('filter-chains-list');
  9818. if (!dl) return;
  9819. const chains = new Set();
  9820. (state.routingFilters || []).forEach(f => {
  9821. if (f.chain) chains.add(f.chain);
  9822. });
  9823. if (chains.size === 0) {
  9824. chains.add('awmn');
  9825. chains.add('Internal');
  9826. chains.add('bgp-in');
  9827. chains.add('bgp-out');
  9828. }
  9829. dl.innerHTML = '';
  9830. chains.forEach(c => {
  9831. const opt = document.createElement('option');
  9832. opt.value = c;
  9833. dl.appendChild(opt);
  9834. });
  9835. }
  9836. function openEditBgpPeerModal(id) {
  9837. const p = (state.bgpPeers || []).find(item => item.id === id);
  9838. if (!p) return;
  9839. populateFilterChainsDatalist();
  9840. populateBgpLocalAddrDatalist();
  9841. document.getElementById('modal-bgp-peer-id').value = p.id;
  9842. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9843. // General Tab
  9844. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9845. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9846. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9847. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9848. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9849. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9850. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9851. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9852. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9853. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9854. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9855. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9856. // Passive mode
  9857. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9858. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9859. // Next-hop self
  9860. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9861. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9862. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9863. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9864. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9865. // Filters Tab
  9866. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9867. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9868. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9869. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9870. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9871. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9872. // Advertised Networks Tab
  9873. const container = document.getElementById('modal-bgp-output-networks-container');
  9874. if (container) {
  9875. container.innerHTML = '';
  9876. if (p.output_networks && p.output_networks.length > 0) {
  9877. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9878. } else {
  9879. addOutputNetworkRow('');
  9880. }
  9881. }
  9882. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9883. if (removeBtn) removeBtn.classList.remove('hidden');
  9884. switchBgpPeerModalTab('general');
  9885. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9886. }
  9887. function copyCurrentBgpPeer() {
  9888. document.getElementById('modal-bgp-peer-id').value = '';
  9889. const nameEl = document.getElementById('modal-bgp-peer-name');
  9890. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9891. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9892. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9893. if (removeBtn) removeBtn.classList.add('hidden');
  9894. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9895. }
  9896. function removeCurrentBgpPeer() {
  9897. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9898. if (!id) return;
  9899. deleteBgpPeer(id);
  9900. closeBgpPeerModal();
  9901. }
  9902. function closeBgpPeerModal() {
  9903. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9904. }
  9905. function getBgpPeerFormData() {
  9906. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9907. const outputNetworks = [];
  9908. netInputs.forEach(inp => {
  9909. const v = inp.value.trim();
  9910. if (v) outputNetworks.push(v);
  9911. });
  9912. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9913. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9914. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9915. const useBfd = document.getElementById('modal-bgp-peer-use-bfd')?.checked || false;
  9916. return {
  9917. id: document.getElementById('modal-bgp-peer-id').value,
  9918. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9919. enabled: enabled,
  9920. disabled: !enabled,
  9921. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9922. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9923. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9924. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9925. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9926. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9927. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9928. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9929. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9930. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9931. use_bfd: useBfd,
  9932. passive: isPassive,
  9933. connect: !isPassive,
  9934. listen: true,
  9935. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9936. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9937. nexthop_self: isNexthopSelf,
  9938. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9939. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9940. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9941. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9942. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9943. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9944. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9945. output_networks: outputNetworks
  9946. };
  9947. }
  9948. async function submitBgpPeer(e) {
  9949. if (e) e.preventDefault();
  9950. const payload = getBgpPeerFormData();
  9951. try {
  9952. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9953. method: 'POST',
  9954. headers: { 'Content-Type': 'application/json' },
  9955. body: JSON.stringify(payload)
  9956. });
  9957. if (res.ok) {
  9958. closeBgpPeerModal();
  9959. showToast('Success', 'BGP Connection saved', 'success');
  9960. loadDynamicRouting();
  9961. } else {
  9962. const err = await res.json();
  9963. showToast('Error', err.error || 'Failed to save peer', 'error');
  9964. }
  9965. } catch (err) {
  9966. showToast('Error', err.message, 'error');
  9967. }
  9968. }
  9969. async function applyBgpPeerModal(e) {
  9970. if (e) e.preventDefault();
  9971. const payload = getBgpPeerFormData();
  9972. try {
  9973. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9974. method: 'POST',
  9975. headers: { 'Content-Type': 'application/json' },
  9976. body: JSON.stringify(payload)
  9977. });
  9978. if (res.ok) {
  9979. const data = await res.json();
  9980. if (data.peer && data.peer.id) {
  9981. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9982. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9983. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9984. }
  9985. showToast('Applied', 'BGP Connection applied', 'success');
  9986. loadDynamicRouting();
  9987. } else {
  9988. const err = await res.json();
  9989. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9990. }
  9991. } catch (err) {
  9992. showToast('Error', err.message, 'error');
  9993. }
  9994. }
  9995. async function deleteBgpPeer(id) {
  9996. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9997. try {
  9998. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9999. if (res.ok) {
  10000. showToast('Deleted', 'BGP peer removed', 'success');
  10001. loadDynamicRouting();
  10002. }
  10003. } catch (err) {
  10004. showToast('Error', err.message, 'error');
  10005. }
  10006. }
  10007. async function toggleBgpPeerState(id, disabled) {
  10008. try {
  10009. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  10010. method: 'POST',
  10011. headers: { 'Content-Type': 'application/json' },
  10012. body: JSON.stringify({ disabled })
  10013. });
  10014. if (res.ok) {
  10015. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  10016. loadDynamicRouting();
  10017. }
  10018. } catch (err) {
  10019. showToast('Error', err.message, 'error');
  10020. }
  10021. }
  10022. function openAddBgpNetworkModal() {
  10023. document.getElementById('bgp-network-form').reset();
  10024. document.getElementById('modal-bgp-net-id').value = '';
  10025. document.getElementById('bgp-network-modal').classList.remove('hidden');
  10026. }
  10027. function closeBgpNetworkModal() {
  10028. document.getElementById('bgp-network-modal').classList.add('hidden');
  10029. }
  10030. async function submitBgpNetwork(e) {
  10031. e.preventDefault();
  10032. const payload = {
  10033. id: document.getElementById('modal-bgp-net-id').value,
  10034. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  10035. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  10036. disabled: document.getElementById('modal-bgp-net-disabled').checked
  10037. };
  10038. try {
  10039. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  10040. method: 'POST',
  10041. headers: { 'Content-Type': 'application/json' },
  10042. body: JSON.stringify(payload)
  10043. });
  10044. if (res.ok) {
  10045. closeBgpNetworkModal();
  10046. showToast('Success', 'BGP network advertisement saved', 'success');
  10047. loadDynamicRouting();
  10048. } else {
  10049. const err = await res.json();
  10050. showToast('Error', err.error || 'Failed to save network', 'error');
  10051. }
  10052. } catch (err) {
  10053. showToast('Error', err.message, 'error');
  10054. }
  10055. }
  10056. async function deleteBgpNetwork(id) {
  10057. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  10058. try {
  10059. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10060. if (res.ok) {
  10061. showToast('Deleted', 'Network advertisement removed', 'success');
  10062. loadDynamicRouting();
  10063. }
  10064. } catch (err) {
  10065. showToast('Error', err.message, 'error');
  10066. }
  10067. }
  10068. // =========================================================================
  10069. // DEBTIK v7 OSPF MODALS & ACTIONS
  10070. // =========================================================================
  10071. // --- 1. OSPF INSTANCE ---
  10072. function openOspfInstanceModal(id = null) {
  10073. const isEdit = !!id;
  10074. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  10075. id: '',
  10076. name: 'Default',
  10077. version: 2,
  10078. vrf: 'main',
  10079. router_id: '192.168.131.56',
  10080. routing_table: 'main',
  10081. enabled: true,
  10082. redistribute_connected: false,
  10083. redistribute_static: true,
  10084. redistribute_bgp: false,
  10085. comment: ''
  10086. };
  10087. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  10088. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  10089. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  10090. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  10091. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  10092. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  10093. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  10094. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  10095. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  10096. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  10097. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  10098. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  10099. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  10100. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  10101. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  10102. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  10103. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  10104. document.getElementById('modal-ospf-inst-in-filter').value = inst.in_filter || '';
  10105. document.getElementById('modal-ospf-inst-out-filter').value = inst.out_filter || '';
  10106. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  10107. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10108. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  10109. }
  10110. function toggleOspfDefaultModeUI() {
  10111. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  10112. const select = document.getElementById('modal-ospf-inst-originate-default');
  10113. if (!select) return;
  10114. if (isChecked) {
  10115. if (select.value === 'never') select.value = 'if-installed';
  10116. } else {
  10117. select.value = 'never';
  10118. }
  10119. }
  10120. function onOspfOriginateDefaultChange() {
  10121. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  10122. const chk = document.getElementById('modal-ospf-inst-redist-default');
  10123. if (chk) chk.checked = val !== 'never';
  10124. }
  10125. function openEditOspfInstanceModal(id) {
  10126. openOspfInstanceModal(id);
  10127. }
  10128. function closeOspfInstanceModal() {
  10129. document.getElementById('ospf-instance-modal').classList.add('hidden');
  10130. }
  10131. async function submitOspfInstance(e) {
  10132. if (e) e.preventDefault();
  10133. const payload = {
  10134. id: document.getElementById('modal-ospf-inst-id').value,
  10135. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  10136. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  10137. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  10138. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  10139. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10140. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10141. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10142. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10143. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10144. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10145. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10146. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10147. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10148. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0,
  10149. in_filter: (document.getElementById('modal-ospf-inst-in-filter')?.value || '').trim(),
  10150. out_filter: (document.getElementById('modal-ospf-inst-out-filter')?.value || '').trim()
  10151. };
  10152. try {
  10153. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10154. method: 'POST',
  10155. headers: { 'Content-Type': 'application/json' },
  10156. body: JSON.stringify(payload)
  10157. });
  10158. if (res.ok) {
  10159. closeOspfInstanceModal();
  10160. showToast('Saved', 'OSPF instance updated', 'success');
  10161. loadDynamicRouting();
  10162. } else {
  10163. const err = await res.json();
  10164. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10165. }
  10166. } catch (err) {
  10167. showToast('Error', err.message, 'error');
  10168. }
  10169. }
  10170. function applyOspfInstanceForm() {
  10171. submitOspfInstance(null);
  10172. }
  10173. function copyOspfInstance() {
  10174. document.getElementById('modal-ospf-inst-id').value = '';
  10175. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10176. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10177. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10178. }
  10179. async function deleteCurrentOspfInstance() {
  10180. const id = document.getElementById('modal-ospf-inst-id').value;
  10181. if (!id) return;
  10182. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10183. try {
  10184. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10185. if (res.ok) {
  10186. closeOspfInstanceModal();
  10187. showToast('Removed', 'OSPF instance deleted', 'success');
  10188. loadDynamicRouting();
  10189. } else {
  10190. throw new Error(await responseError(res));
  10191. }
  10192. } catch (err) {
  10193. showToast('Error', err.message, 'error');
  10194. }
  10195. }
  10196. async function enableSelectedOspfInstance() {
  10197. const id = state.selectedOspfRow?.instances;
  10198. if (!id) return;
  10199. if (!await routingMutation(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10200. method: 'POST',
  10201. headers: { 'Content-Type': 'application/json' },
  10202. body: JSON.stringify({ disabled: false })
  10203. })) return;
  10204. loadDynamicRouting();
  10205. }
  10206. async function disableSelectedOspfInstance() {
  10207. const id = state.selectedOspfRow?.instances;
  10208. if (!id) return;
  10209. if (!await routingMutation(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10210. method: 'POST',
  10211. headers: { 'Content-Type': 'application/json' },
  10212. body: JSON.stringify({ disabled: true })
  10213. })) return;
  10214. loadDynamicRouting();
  10215. }
  10216. async function removeSelectedOspfInstance() {
  10217. const id = state.selectedOspfRow?.instances;
  10218. if (!id) return;
  10219. if (!confirm('Delete selected OSPF instance?')) return;
  10220. if (!await routingMutation(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10221. loadDynamicRouting();
  10222. }
  10223. async function promptCommentOspfInstance() {
  10224. const id = state.selectedOspfRow?.instances;
  10225. if (!id) return;
  10226. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10227. if (!inst) return;
  10228. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10229. if (comment === null) return;
  10230. const updated = {...inst, comment};
  10231. if (!await routingMutation(`${API_BASE}/routing/ospf/instances`, {
  10232. method: 'POST',
  10233. headers: { 'Content-Type': 'application/json' },
  10234. body: JSON.stringify(updated)
  10235. })) return;
  10236. loadDynamicRouting();
  10237. }
  10238. // --- 2. OSPF AREA ---
  10239. function populateOspfAreaDropdowns() {
  10240. const instSelect = document.getElementById('modal-ospf-area-instance');
  10241. if (instSelect) {
  10242. const cur = instSelect.value;
  10243. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10244. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10245. if (cur) instSelect.value = cur;
  10246. }
  10247. }
  10248. function openOspfAreaModal(id = null) {
  10249. const isEdit = !!id;
  10250. populateOspfAreaDropdowns();
  10251. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10252. id: '',
  10253. name: 'Default',
  10254. instance: 'Default',
  10255. area_id: '0.0.0.0',
  10256. area_type: 'default',
  10257. default_cost: 1,
  10258. no_summaries: false,
  10259. disabled: false,
  10260. comment: ''
  10261. };
  10262. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10263. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10264. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10265. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10266. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10267. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10268. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10269. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10270. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10271. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10272. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10273. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10274. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10275. }
  10276. function openEditOspfAreaModal(id) {
  10277. openOspfAreaModal(id);
  10278. }
  10279. function closeOspfAreaModal() {
  10280. document.getElementById('ospf-area-modal').classList.add('hidden');
  10281. }
  10282. async function submitOspfArea(e) {
  10283. if (e) e.preventDefault();
  10284. const payload = {
  10285. id: document.getElementById('modal-ospf-area-id').value,
  10286. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10287. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10288. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10289. area_type: document.getElementById('modal-ospf-area-type').value,
  10290. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10291. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10292. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10293. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10294. };
  10295. try {
  10296. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10297. method: 'POST',
  10298. headers: { 'Content-Type': 'application/json' },
  10299. body: JSON.stringify(payload)
  10300. });
  10301. if (res.ok) {
  10302. closeOspfAreaModal();
  10303. showToast('Saved', 'OSPF area saved', 'success');
  10304. loadDynamicRouting();
  10305. } else {
  10306. const err = await res.json();
  10307. showToast('Error', err.error || 'Failed to save area', 'error');
  10308. }
  10309. } catch (err) {
  10310. showToast('Error', err.message, 'error');
  10311. }
  10312. }
  10313. function applyOspfAreaForm() {
  10314. submitOspfArea(null);
  10315. }
  10316. function copyOspfArea() {
  10317. document.getElementById('modal-ospf-area-id').value = '';
  10318. document.getElementById('modal-ospf-area-name').value += '-copy';
  10319. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10320. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10321. }
  10322. async function deleteCurrentOspfArea() {
  10323. const id = document.getElementById('modal-ospf-area-id').value;
  10324. if (!id) return;
  10325. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10326. try {
  10327. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10328. if (res.ok) {
  10329. closeOspfAreaModal();
  10330. showToast('Removed', 'OSPF area deleted', 'success');
  10331. loadDynamicRouting();
  10332. } else {
  10333. throw new Error(await responseError(res));
  10334. }
  10335. } catch (err) {
  10336. showToast('Error', err.message, 'error');
  10337. }
  10338. }
  10339. async function enableSelectedOspfArea() {
  10340. const id = state.selectedOspfRow?.areas;
  10341. if (!id) return;
  10342. if (!await routingMutation(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10343. method: 'POST',
  10344. headers: { 'Content-Type': 'application/json' },
  10345. body: JSON.stringify({ disabled: false })
  10346. })) return;
  10347. loadDynamicRouting();
  10348. }
  10349. async function disableSelectedOspfArea() {
  10350. const id = state.selectedOspfRow?.areas;
  10351. if (!id) return;
  10352. if (!await routingMutation(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10353. method: 'POST',
  10354. headers: { 'Content-Type': 'application/json' },
  10355. body: JSON.stringify({ disabled: true })
  10356. })) return;
  10357. loadDynamicRouting();
  10358. }
  10359. async function removeSelectedOspfArea() {
  10360. const id = state.selectedOspfRow?.areas;
  10361. if (!id) return;
  10362. if (!confirm('Delete selected OSPF area?')) return;
  10363. if (!await routingMutation(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10364. loadDynamicRouting();
  10365. }
  10366. async function promptCommentOspfArea() {
  10367. const id = state.selectedOspfRow?.areas;
  10368. if (!id) return;
  10369. const area = (state.ospfAreas || []).find(a => a.id === id);
  10370. if (!area) return;
  10371. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10372. if (comment === null) return;
  10373. const updated = {...area, comment};
  10374. if (!await routingMutation(`${API_BASE}/routing/ospf/areas`, {
  10375. method: 'POST',
  10376. headers: { 'Content-Type': 'application/json' },
  10377. body: JSON.stringify(updated)
  10378. })) return;
  10379. loadDynamicRouting();
  10380. }
  10381. // --- 3. OSPF AREA RANGE ---
  10382. function populateAreaRangeDropdowns() {
  10383. const select = document.getElementById('modal-ospf-range-area');
  10384. if (select) {
  10385. const cur = select.value;
  10386. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10387. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10388. if (cur) select.value = cur;
  10389. }
  10390. }
  10391. function openOspfAreaRangeModal(id = null) {
  10392. const isEdit = !!id;
  10393. populateAreaRangeDropdowns();
  10394. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10395. id: '',
  10396. area: 'Default',
  10397. prefix: '',
  10398. cost: 1,
  10399. advertise: true,
  10400. disabled: false,
  10401. comment: ''
  10402. };
  10403. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10404. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10405. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10406. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10407. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10408. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10409. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10410. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10411. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10412. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10413. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10414. }
  10415. function openEditOspfAreaRangeModal(id) {
  10416. openOspfAreaRangeModal(id);
  10417. }
  10418. function closeOspfAreaRangeModal() {
  10419. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10420. }
  10421. async function submitOspfAreaRange(e) {
  10422. if (e) e.preventDefault();
  10423. const payload = {
  10424. id: document.getElementById('modal-ospf-range-id').value,
  10425. area: document.getElementById('modal-ospf-range-area').value,
  10426. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10427. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10428. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10429. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10430. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10431. };
  10432. try {
  10433. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10434. method: 'POST',
  10435. headers: { 'Content-Type': 'application/json' },
  10436. body: JSON.stringify(payload)
  10437. });
  10438. if (res.ok) {
  10439. closeOspfAreaRangeModal();
  10440. showToast('Saved', 'Area range saved', 'success');
  10441. loadDynamicRouting();
  10442. } else {
  10443. const err = await res.json();
  10444. showToast('Error', err.error || 'Failed to save area range', 'error');
  10445. }
  10446. } catch (err) {
  10447. showToast('Error', err.message, 'error');
  10448. }
  10449. }
  10450. function applyOspfAreaRangeForm() {
  10451. submitOspfAreaRange(null);
  10452. }
  10453. async function deleteCurrentOspfAreaRange() {
  10454. const id = document.getElementById('modal-ospf-range-id').value;
  10455. if (!id) return;
  10456. if (!confirm('Delete this area range?')) return;
  10457. try {
  10458. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10459. closeOspfAreaRangeModal();
  10460. showToast('Removed', 'Area range removed', 'success');
  10461. loadDynamicRouting();
  10462. } catch (err) {
  10463. showToast('Error', err.message, 'error');
  10464. }
  10465. }
  10466. async function enableSelectedOspfAreaRange() {
  10467. const id = state.selectedOspfRow?.['area-ranges'];
  10468. if (!id) return;
  10469. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10470. if (!r) return;
  10471. const updated = {...r, disabled: false};
  10472. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10473. loadDynamicRouting();
  10474. }
  10475. async function disableSelectedOspfAreaRange() {
  10476. const id = state.selectedOspfRow?.['area-ranges'];
  10477. if (!id) return;
  10478. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10479. if (!r) return;
  10480. const updated = {...r, disabled: true};
  10481. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10482. loadDynamicRouting();
  10483. }
  10484. async function removeSelectedOspfAreaRange() {
  10485. const id = state.selectedOspfRow?.['area-ranges'];
  10486. if (!id) return;
  10487. if (!confirm('Delete selected area range?')) return;
  10488. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10489. loadDynamicRouting();
  10490. }
  10491. async function promptCommentOspfAreaRange() {
  10492. const id = state.selectedOspfRow?.['area-ranges'];
  10493. if (!id) return;
  10494. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10495. if (!r) return;
  10496. const comment = prompt('Enter comment for area range:', r.comment || '');
  10497. if (comment === null) return;
  10498. const updated = {...r, comment};
  10499. if (!await routingMutation(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10500. loadDynamicRouting();
  10501. }
  10502. // --- 4. OSPF INTERFACE TEMPLATE ---
  10503. function switchOspfTemplateTab(tab) {
  10504. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10505. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10506. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10507. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10508. if (tab === 'general') {
  10509. if (tabGen) tabGen.classList.remove('hidden');
  10510. if (tabAuth) tabAuth.classList.add('hidden');
  10511. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10512. 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';
  10513. } else {
  10514. if (tabGen) tabGen.classList.add('hidden');
  10515. if (tabAuth) tabAuth.classList.remove('hidden');
  10516. 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';
  10517. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10518. }
  10519. }
  10520. function populateTemplateAreaDropdowns() {
  10521. const select = document.getElementById('modal-ospf-tmpl-area');
  10522. if (select) {
  10523. const cur = select.value;
  10524. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10525. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10526. if (cur) select.value = cur;
  10527. }
  10528. }
  10529. function openOspfTemplateModal(id = null) {
  10530. const isEdit = !!id;
  10531. populateTemplateAreaDropdowns();
  10532. switchOspfTemplateTab('general');
  10533. const dl = document.getElementById('ospf-tmpl-iface-datalist');
  10534. if (dl) {
  10535. dl.innerHTML = '<option value="*"><option value="all">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  10536. }
  10537. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10538. id: '',
  10539. interfaces: '',
  10540. area: 'Default',
  10541. networks: '',
  10542. network_type: 'broadcast',
  10543. cost: 1,
  10544. priority: 128,
  10545. passive: false,
  10546. hello_interval: 10,
  10547. dead_interval: 40,
  10548. auth: 'none',
  10549. auth_key: '',
  10550. disabled: false,
  10551. comment: ''
  10552. };
  10553. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10554. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10555. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10556. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10557. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10558. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10559. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10560. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10561. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10562. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10563. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10564. if (document.getElementById('modal-ospf-tmpl-bfd')) document.getElementById('modal-ospf-tmpl-bfd').checked = !!tmpl.use_bfd;
  10565. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10566. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10567. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10568. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10569. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10570. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10571. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10572. }
  10573. function openEditOspfTemplateModal(id) {
  10574. openOspfTemplateModal(id);
  10575. }
  10576. function closeOspfTemplateModal() {
  10577. document.getElementById('ospf-template-modal').classList.add('hidden');
  10578. }
  10579. async function submitOspfTemplate(e) {
  10580. if (e) e.preventDefault();
  10581. const payload = {
  10582. id: document.getElementById('modal-ospf-tmpl-id').value,
  10583. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10584. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10585. area: document.getElementById('modal-ospf-tmpl-area').value,
  10586. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10587. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10588. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10589. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10590. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10591. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10592. use_bfd: document.getElementById('modal-ospf-tmpl-bfd')?.checked || false,
  10593. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10594. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10595. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10596. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10597. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10598. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10599. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10600. };
  10601. try {
  10602. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10603. method: 'POST',
  10604. headers: { 'Content-Type': 'application/json' },
  10605. body: JSON.stringify(payload)
  10606. });
  10607. if (res.ok) {
  10608. closeOspfTemplateModal();
  10609. showToast('Saved', 'Interface template saved', 'success');
  10610. loadDynamicRouting();
  10611. } else {
  10612. const err = await res.json();
  10613. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10614. }
  10615. } catch (err) {
  10616. showToast('Error', err.message, 'error');
  10617. }
  10618. }
  10619. function applyOspfTemplateForm() {
  10620. submitOspfTemplate(null);
  10621. }
  10622. function copyOspfTemplate() {
  10623. document.getElementById('modal-ospf-tmpl-id').value = '';
  10624. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10625. showToast('Copied', 'Duplicated as new template', 'info');
  10626. }
  10627. async function deleteCurrentOspfTemplate() {
  10628. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10629. if (!id) return;
  10630. if (!confirm('Delete this interface template?')) return;
  10631. try {
  10632. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10633. closeOspfTemplateModal();
  10634. showToast('Removed', 'Interface template deleted', 'success');
  10635. loadDynamicRouting();
  10636. } catch (err) {
  10637. showToast('Error', err.message, 'error');
  10638. }
  10639. }
  10640. async function enableSelectedOspfTemplate() {
  10641. const id = state.selectedOspfRow?.templates;
  10642. if (!id) return;
  10643. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10644. method: 'POST',
  10645. headers: { 'Content-Type': 'application/json' },
  10646. body: JSON.stringify({ disabled: false })
  10647. })) return;
  10648. loadDynamicRouting();
  10649. }
  10650. async function disableSelectedOspfTemplate() {
  10651. const id = state.selectedOspfRow?.templates;
  10652. if (!id) return;
  10653. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10654. method: 'POST',
  10655. headers: { 'Content-Type': 'application/json' },
  10656. body: JSON.stringify({ disabled: true })
  10657. })) return;
  10658. loadDynamicRouting();
  10659. }
  10660. async function removeSelectedOspfTemplate() {
  10661. const id = state.selectedOspfRow?.templates;
  10662. if (!id) return;
  10663. if (!confirm('Delete selected interface template?')) return;
  10664. if (!await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10665. loadDynamicRouting();
  10666. }
  10667. async function promptCommentOspfTemplate() {
  10668. const id = state.selectedOspfRow?.templates;
  10669. if (!id) return;
  10670. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10671. if (!tmpl) return;
  10672. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10673. if (comment === null) return;
  10674. const updated = {...tmpl, comment};
  10675. if (!await routingMutation(`${API_BASE}/routing/ospf/templates`, {
  10676. method: 'POST',
  10677. headers: { 'Content-Type': 'application/json' },
  10678. body: JSON.stringify(updated)
  10679. })) return;
  10680. loadDynamicRouting();
  10681. }
  10682. // --- 5. OSPF STATIC NEIGHBOR ---
  10683. function populateStaticNbrAreaDropdowns() {
  10684. const select = document.getElementById('modal-ospf-snbr-area');
  10685. if (select) {
  10686. const cur = select.value;
  10687. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10688. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10689. if (cur) select.value = cur;
  10690. }
  10691. }
  10692. function openOspfStaticNbrModal(id = null) {
  10693. const isEdit = !!id;
  10694. populateStaticNbrAreaDropdowns();
  10695. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10696. id: '',
  10697. address: '',
  10698. area: 'Default',
  10699. poll_interval: 120,
  10700. cost: 1,
  10701. disabled: false,
  10702. comment: ''
  10703. };
  10704. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10705. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10706. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10707. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10708. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10709. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10710. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10711. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10712. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10713. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10714. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10715. }
  10716. function openEditOspfStaticNbrModal(id) {
  10717. openOspfStaticNbrModal(id);
  10718. }
  10719. function closeOspfStaticNbrModal() {
  10720. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10721. }
  10722. async function submitOspfStaticNbr(e) {
  10723. if (e) e.preventDefault();
  10724. const payload = {
  10725. id: document.getElementById('modal-ospf-snbr-id').value,
  10726. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10727. area: document.getElementById('modal-ospf-snbr-area').value,
  10728. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10729. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10730. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10731. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10732. };
  10733. try {
  10734. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10735. method: 'POST',
  10736. headers: { 'Content-Type': 'application/json' },
  10737. body: JSON.stringify(payload)
  10738. });
  10739. if (res.ok) {
  10740. closeOspfStaticNbrModal();
  10741. showToast('Saved', 'Static neighbor saved', 'success');
  10742. loadDynamicRouting();
  10743. } else {
  10744. const err = await res.json();
  10745. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10746. }
  10747. } catch (err) {
  10748. showToast('Error', err.message, 'error');
  10749. }
  10750. }
  10751. function applyOspfStaticNbrForm() {
  10752. submitOspfStaticNbr(null);
  10753. }
  10754. async function deleteCurrentOspfStaticNbr() {
  10755. const id = document.getElementById('modal-ospf-snbr-id').value;
  10756. if (!id) return;
  10757. if (!confirm('Delete this static neighbor?')) return;
  10758. try {
  10759. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10760. closeOspfStaticNbrModal();
  10761. showToast('Removed', 'Static neighbor removed', 'success');
  10762. loadDynamicRouting();
  10763. } catch (err) {
  10764. showToast('Error', err.message, 'error');
  10765. }
  10766. }
  10767. async function enableSelectedOspfStaticNbr() {
  10768. const id = state.selectedOspfRow?.['static-nbrs'];
  10769. if (!id) return;
  10770. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  10771. loadDynamicRouting();
  10772. }
  10773. async function disableSelectedOspfStaticNbr() {
  10774. const id = state.selectedOspfRow?.['static-nbrs'];
  10775. if (!id) return;
  10776. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  10777. loadDynamicRouting();
  10778. }
  10779. async function removeSelectedOspfStaticNbr() {
  10780. const id = state.selectedOspfRow?.['static-nbrs'];
  10781. if (!id) return;
  10782. if (!confirm('Delete selected static neighbor?')) return;
  10783. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' })) return;
  10784. loadDynamicRouting();
  10785. }
  10786. async function promptCommentOspfStaticNbr() {
  10787. const id = state.selectedOspfRow?.['static-nbrs'];
  10788. if (!id) return;
  10789. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10790. if (!n) return;
  10791. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10792. if (comment === null) return;
  10793. const updated = {...n, comment};
  10794. if (!await routingMutation(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updated) })) return;
  10795. loadDynamicRouting();
  10796. }
  10797. // Backward-compat aliases
  10798. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10799. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10800. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10801. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10802. async function deleteOspfInterface(id) {
  10803. if (await routingMutation(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' })) await loadDynamicRouting();
  10804. }
  10805. function toggleOspfInterfaceState(id, disabled) {
  10806. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10807. method: 'POST',
  10808. headers: { 'Content-Type': 'application/json' },
  10809. body: JSON.stringify({ disabled })
  10810. }).then(() => loadDynamicRouting());
  10811. }
  10812. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10813. function deleteOspfArea(id) {
  10814. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10815. }
  10816. // ============================================================================
  10817. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10818. // ============================================================================
  10819. function switchBridgeSubTab(tab) {
  10820. state.bridgeSubTab = tab;
  10821. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10822. tabs.forEach(t => {
  10823. const panel = document.getElementById(`bridge-subtab-${t}`);
  10824. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10825. if (panel) {
  10826. if (t === tab) panel.classList.remove('hidden');
  10827. else panel.classList.add('hidden');
  10828. }
  10829. if (btn) {
  10830. if (t === tab) {
  10831. 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';
  10832. } else {
  10833. 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';
  10834. }
  10835. }
  10836. });
  10837. const addBtn = document.getElementById('bridge-top-action-btn');
  10838. if (addBtn) {
  10839. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10840. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10841. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10842. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10843. }
  10844. if (tab === 'hosts') loadBridgeHosts();
  10845. setTimeout(initTableSorting, 50);
  10846. }
  10847. function openCurrentBridgeModal() {
  10848. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10849. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10850. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10851. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10852. }
  10853. async function loadBridge() {
  10854. try {
  10855. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10856. fetch(`${API_BASE}/bridge/bridges`),
  10857. fetch(`${API_BASE}/bridge/ports`),
  10858. fetch(`${API_BASE}/bridge/vlans`),
  10859. fetch(`${API_BASE}/bridge/summary`),
  10860. fetch(`${API_BASE}/vpn/eoip`),
  10861. fetch(`${API_BASE}/vpn/vxlan`),
  10862. fetch(`${API_BASE}/vlans`)
  10863. ]);
  10864. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10865. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10866. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10867. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10868. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10869. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10870. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10871. // Badges & Stats
  10872. const bBridges = document.getElementById('bridge-badge-bridges');
  10873. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10874. const bPorts = document.getElementById('bridge-badge-ports');
  10875. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10876. const bVlans = document.getElementById('bridge-badge-vlans');
  10877. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10878. const bHosts = document.getElementById('bridge-badge-hosts');
  10879. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10880. const sBr = document.getElementById('bridge-stat-bridges');
  10881. if (sBr) sBr.innerText = (state.bridges || []).length;
  10882. const sPorts = document.getElementById('bridge-stat-ports');
  10883. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10884. const sHosts = document.getElementById('bridge-stat-hosts');
  10885. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10886. renderBridges();
  10887. renderBridgePorts();
  10888. renderBridgeVLANs();
  10889. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10890. } catch (err) {
  10891. console.error('Failed to load bridge subsystem:', err);
  10892. }
  10893. }
  10894. // ----------------- Bridges -----------------
  10895. function renderBridges() {
  10896. const tbody = document.getElementById('bridge-table-body');
  10897. const empty = document.getElementById('bridge-empty-bridges');
  10898. const countBadge = document.getElementById('bridge-count-badge');
  10899. if (!tbody) return;
  10900. tbody.innerHTML = '';
  10901. const bridges = state.bridges || [];
  10902. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10903. if (bridges.length === 0) {
  10904. empty?.classList.remove('hidden');
  10905. return;
  10906. }
  10907. empty?.classList.add('hidden');
  10908. bridges.forEach((b, idx) => {
  10909. const tr = document.createElement('tr');
  10910. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10911. // Format IP addresses pill list
  10912. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10913. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10914. ipsHtml = b.ip_addresses.map(ip => `
  10915. <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">
  10916. <span>${ip}</span>
  10917. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10918. </span>
  10919. `).join(' ');
  10920. }
  10921. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10922. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10923. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10924. tr.innerHTML = `
  10925. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10926. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10927. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10928. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10929. </td>
  10930. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10931. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10932. <td class="py-2.5 px-3">
  10933. <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>
  10934. </td>
  10935. <td class="py-2.5 px-3 text-center">
  10936. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10937. </td>
  10938. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10939. <td class="py-2.5 px-3">
  10940. <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>
  10941. </td>
  10942. <td class="py-2.5 px-3">
  10943. <div class="flex items-center gap-1.5 flex-wrap">
  10944. ${ipsHtml}
  10945. <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>
  10946. </div>
  10947. </td>
  10948. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10949. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10950. </td>
  10951. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10952. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10953. <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>
  10954. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10955. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10956. </td>
  10957. `;
  10958. tbody.appendChild(tr);
  10959. });
  10960. }
  10961. function openAddBridgeModal() {
  10962. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10963. document.getElementById('bridge-modal-id').value = '';
  10964. document.getElementById('bridge-modal-name').value = 'bridge1';
  10965. document.getElementById('bridge-modal-name').disabled = false;
  10966. document.getElementById('bridge-modal-mtu').value = '1500';
  10967. document.getElementById('bridge-modal-mac').value = '';
  10968. document.getElementById('bridge-modal-stp').value = 'stp';
  10969. document.getElementById('bridge-modal-priority').value = '32768';
  10970. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10971. document.getElementById('bridge-modal-pvid').value = '1';
  10972. document.getElementById('bridge-modal-fastforward').checked = true;
  10973. document.getElementById('bridge-modal-comment').value = '';
  10974. document.getElementById('bridge-modal-disabled').checked = false;
  10975. toggleBridgeModalVlanFiltering();
  10976. document.getElementById('bridge-modal').classList.remove('hidden');
  10977. }
  10978. function openEditBridgeModal(id) {
  10979. const b = (state.bridges || []).find(x => x.id === id);
  10980. if (!b) return;
  10981. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10982. document.getElementById('bridge-modal-id').value = b.id;
  10983. document.getElementById('bridge-modal-name').value = b.name;
  10984. document.getElementById('bridge-modal-name').disabled = true;
  10985. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10986. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10987. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10988. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10989. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10990. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10991. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10992. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10993. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10994. toggleBridgeModalVlanFiltering();
  10995. document.getElementById('bridge-modal').classList.remove('hidden');
  10996. }
  10997. function closeBridgeModal() {
  10998. document.getElementById('bridge-modal').classList.add('hidden');
  10999. }
  11000. function toggleBridgeModalVlanFiltering() {
  11001. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  11002. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  11003. if (pvidBox) {
  11004. if (chk) pvidBox.classList.remove('opacity-40');
  11005. else pvidBox.classList.add('opacity-40');
  11006. }
  11007. }
  11008. async function submitSaveBridge(e) {
  11009. e.preventDefault();
  11010. const id = document.getElementById('bridge-modal-id').value;
  11011. const name = document.getElementById('bridge-modal-name').value.trim();
  11012. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  11013. const mac = document.getElementById('bridge-modal-mac').value.trim();
  11014. const stp = document.getElementById('bridge-modal-stp').value;
  11015. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  11016. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  11017. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  11018. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  11019. const comment = document.getElementById('bridge-modal-comment').value.trim();
  11020. const disabled = document.getElementById('bridge-modal-disabled').checked;
  11021. try {
  11022. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  11023. method: 'POST',
  11024. headers: { 'Content-Type': 'application/json' },
  11025. body: JSON.stringify({
  11026. id,
  11027. name,
  11028. mtu,
  11029. mac_address: mac,
  11030. stp,
  11031. priority,
  11032. vlan_filtering: vlanFiltering,
  11033. pvid,
  11034. fast_forward: fastForward,
  11035. comment,
  11036. disabled
  11037. })
  11038. });
  11039. if (res.ok) {
  11040. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  11041. closeBridgeModal();
  11042. loadBridge();
  11043. fetchData(false);
  11044. } else {
  11045. const err = await res.json();
  11046. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  11047. }
  11048. } catch (err) {
  11049. showToast('Error', err.message, 'error');
  11050. }
  11051. }
  11052. async function toggleBridgeState(id, disabled) {
  11053. try {
  11054. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  11055. method: 'POST',
  11056. headers: { 'Content-Type': 'application/json' },
  11057. body: JSON.stringify({ disabled })
  11058. });
  11059. if (res.ok) {
  11060. loadBridge();
  11061. fetchData(false);
  11062. }
  11063. } catch (err) {
  11064. showToast('Error', err.message, 'error');
  11065. }
  11066. }
  11067. async function deleteBridge(id) {
  11068. const b = (state.bridges || []).find(x => x.id === id);
  11069. const name = b ? b.name : id;
  11070. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  11071. try {
  11072. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11073. if (res.ok) {
  11074. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  11075. loadBridge();
  11076. fetchData(false);
  11077. } else {
  11078. const err = await res.json();
  11079. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  11080. }
  11081. } catch (err) {
  11082. showToast('Error', err.message, 'error');
  11083. }
  11084. }
  11085. // ----------------- Bridge IP Assignments -----------------
  11086. function openAddBridgeIPModal(id, name) {
  11087. document.getElementById('bridge-ip-modal-id').value = id;
  11088. document.getElementById('bridge-ip-modal-sub').innerText = name;
  11089. document.getElementById('bridge-ip-modal-cidr').value = '';
  11090. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  11091. }
  11092. function closeBridgeIPModal() {
  11093. document.getElementById('bridge-ip-modal').classList.add('hidden');
  11094. }
  11095. async function submitAddBridgeIP(e) {
  11096. e.preventDefault();
  11097. const id = document.getElementById('bridge-ip-modal-id').value;
  11098. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  11099. try {
  11100. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11101. method: 'POST',
  11102. headers: { 'Content-Type': 'application/json' },
  11103. body: JSON.stringify({ ip })
  11104. });
  11105. if (res.ok) {
  11106. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  11107. closeBridgeIPModal();
  11108. loadBridge();
  11109. fetchData(false);
  11110. } else {
  11111. const err = await res.json();
  11112. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  11113. }
  11114. } catch (err) {
  11115. showToast('Error', err.message, 'error');
  11116. }
  11117. }
  11118. async function deleteBridgeIP(id, ip) {
  11119. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  11120. try {
  11121. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  11122. method: 'DELETE',
  11123. headers: { 'Content-Type': 'application/json' },
  11124. body: JSON.stringify({ ip })
  11125. });
  11126. if (res.ok) {
  11127. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  11128. loadBridge();
  11129. fetchData(false);
  11130. }
  11131. } catch (err) {
  11132. showToast('Error', err.message, 'error');
  11133. }
  11134. }
  11135. // ----------------- Bridge Ports -----------------
  11136. function renderBridgePorts() {
  11137. const tbody = document.getElementById('bridge-ports-table-body');
  11138. const empty = document.getElementById('bridge-empty-ports');
  11139. const countBadge = document.getElementById('bridge-ports-count-badge');
  11140. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  11141. if (!tbody) return;
  11142. tbody.innerHTML = '';
  11143. // Update filter select
  11144. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  11145. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  11146. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  11147. if (ports.length === 0) {
  11148. empty?.classList.remove('hidden');
  11149. return;
  11150. }
  11151. empty?.classList.add('hidden');
  11152. ports.forEach((p, idx) => {
  11153. const tr = document.createElement('tr');
  11154. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11155. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11156. tr.innerHTML = `
  11157. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11158. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11159. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11160. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11161. </td>
  11162. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11163. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11164. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11165. <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>
  11166. <td class="py-2.5 px-3">
  11167. ${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>'}
  11168. </td>
  11169. <td class="py-2.5 px-3">
  11170. <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>
  11171. </td>
  11172. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11173. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11174. <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>
  11175. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11176. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11177. </td>
  11178. `;
  11179. tbody.appendChild(tr);
  11180. });
  11181. }
  11182. function openAddBridgePortModal() {
  11183. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11184. document.getElementById('bridge-port-modal-id').value = '';
  11185. populateBridgeSelect('bridge-port-modal-bridge');
  11186. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11187. document.getElementById('bridge-port-modal-pvid').value = '1';
  11188. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11189. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11190. document.getElementById('bridge-port-modal-horizon').value = '0';
  11191. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11192. document.getElementById('bridge-port-modal-priority').value = '128';
  11193. document.getElementById('bridge-port-modal-learn').checked = true;
  11194. document.getElementById('bridge-port-modal-comment').value = '';
  11195. document.getElementById('bridge-port-modal-disabled').checked = false;
  11196. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11197. }
  11198. function openEditBridgePortModal(id) {
  11199. const p = (state.bridgePorts || []).find(x => x.id === id);
  11200. if (!p) return;
  11201. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11202. document.getElementById('bridge-port-modal-id').value = p.id;
  11203. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11204. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11205. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11206. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11207. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11208. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11209. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11210. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11211. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11212. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11213. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11214. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11215. }
  11216. function closeBridgePortModal() {
  11217. document.getElementById('bridge-port-modal').classList.add('hidden');
  11218. }
  11219. async function submitSaveBridgePort(e) {
  11220. e.preventDefault();
  11221. const id = document.getElementById('bridge-port-modal-id').value;
  11222. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11223. const iface = document.getElementById('bridge-port-modal-interface').value;
  11224. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11225. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11226. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11227. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11228. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11229. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11230. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11231. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11232. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11233. try {
  11234. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11235. method: 'POST',
  11236. headers: { 'Content-Type': 'application/json' },
  11237. body: JSON.stringify({
  11238. id,
  11239. bridge,
  11240. interface: iface,
  11241. pvid,
  11242. frame_types: frameTypes,
  11243. ingress_filtering: ingressFiltering,
  11244. horizon,
  11245. path_cost: pathCost,
  11246. priority,
  11247. learn,
  11248. comment,
  11249. disabled
  11250. })
  11251. });
  11252. if (res.ok) {
  11253. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11254. closeBridgePortModal();
  11255. loadBridge();
  11256. fetchData(false);
  11257. } else {
  11258. const err = await res.json();
  11259. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11260. }
  11261. } catch (err) {
  11262. showToast('Error', err.message, 'error');
  11263. }
  11264. }
  11265. async function toggleBridgePortState(id, disabled) {
  11266. try {
  11267. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11268. method: 'POST',
  11269. headers: { 'Content-Type': 'application/json' },
  11270. body: JSON.stringify({ disabled })
  11271. });
  11272. if (res.ok) {
  11273. loadBridge();
  11274. fetchData(false);
  11275. }
  11276. } catch (err) {
  11277. showToast('Error', err.message, 'error');
  11278. }
  11279. }
  11280. async function deleteBridgePort(id) {
  11281. const p = (state.bridgePorts || []).find(x => x.id === id);
  11282. const iface = p ? p.interface : id;
  11283. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11284. try {
  11285. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11286. if (res.ok) {
  11287. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11288. loadBridge();
  11289. fetchData(false);
  11290. }
  11291. } catch (err) {
  11292. showToast('Error', err.message, 'error');
  11293. }
  11294. }
  11295. // ----------------- Bridge VLANs -----------------
  11296. function renderBridgeVLANs() {
  11297. const tbody = document.getElementById('bridge-vlans-table-body');
  11298. const empty = document.getElementById('bridge-empty-vlans');
  11299. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11300. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11301. if (!tbody) return;
  11302. tbody.innerHTML = '';
  11303. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11304. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11305. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11306. if (vlans.length === 0) {
  11307. empty?.classList.remove('hidden');
  11308. return;
  11309. }
  11310. empty?.classList.add('hidden');
  11311. vlans.forEach((v, idx) => {
  11312. const tr = document.createElement('tr');
  11313. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11314. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11315. ? 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(' ')
  11316. : '<span class="text-slate-600">none</span>';
  11317. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11318. ? 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(' ')
  11319. : '<span class="text-slate-600">none</span>';
  11320. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11321. tr.innerHTML = `
  11322. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11323. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11324. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11325. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11326. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11327. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11328. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11329. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11330. <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>
  11331. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11332. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11333. </td>
  11334. `;
  11335. tbody.appendChild(tr);
  11336. });
  11337. }
  11338. function openAddBridgeVLANModal() {
  11339. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11340. document.getElementById('bridge-vlan-modal-id').value = '';
  11341. populateBridgeSelect('bridge-vlan-modal-bridge');
  11342. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11343. document.getElementById('bridge-vlan-modal-comment').value = '';
  11344. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11345. updateBridgeVlanPortCheckboxes();
  11346. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11347. }
  11348. function openEditBridgeVLANModal(id) {
  11349. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11350. if (!v) return;
  11351. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11352. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11353. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11354. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11355. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11356. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11357. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11358. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11359. }
  11360. function closeBridgeVlanModal() {
  11361. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11362. }
  11363. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11364. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11365. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11366. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11367. if (!taggedBox || !untaggedBox) return;
  11368. // Ports belonging to the selected bridge
  11369. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11370. if (memberPorts.length === 0) {
  11371. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11372. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11373. return;
  11374. }
  11375. taggedBox.innerHTML = memberPorts.map(p => `
  11376. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11377. <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">
  11378. <span>${p.interface}</span>
  11379. </label>
  11380. `).join('');
  11381. untaggedBox.innerHTML = memberPorts.map(p => `
  11382. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11383. <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">
  11384. <span>${p.interface}</span>
  11385. </label>
  11386. `).join('');
  11387. }
  11388. async function submitSaveBridgeVLAN(e) {
  11389. e.preventDefault();
  11390. const id = document.getElementById('bridge-vlan-modal-id').value;
  11391. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11392. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11393. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11394. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11395. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11396. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11397. try {
  11398. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11399. method: 'POST',
  11400. headers: { 'Content-Type': 'application/json' },
  11401. body: JSON.stringify({
  11402. id,
  11403. bridge,
  11404. vlan_ids: vlanIDs,
  11405. tagged,
  11406. untagged,
  11407. comment,
  11408. disabled
  11409. })
  11410. });
  11411. if (res.ok) {
  11412. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11413. closeBridgeVlanModal();
  11414. loadBridge();
  11415. } else {
  11416. const err = await res.json();
  11417. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11418. }
  11419. } catch (err) {
  11420. showToast('Error', err.message, 'error');
  11421. }
  11422. }
  11423. async function toggleBridgeVLANState(id, disabled) {
  11424. try {
  11425. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11426. method: 'POST',
  11427. headers: { 'Content-Type': 'application/json' },
  11428. body: JSON.stringify({ disabled })
  11429. });
  11430. if (res.ok) loadBridge();
  11431. } catch (err) {
  11432. showToast('Error', err.message, 'error');
  11433. }
  11434. }
  11435. async function deleteBridgeVLAN(id) {
  11436. if (!confirm('Delete this bridge VLAN entry?')) return;
  11437. try {
  11438. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11439. if (res.ok) {
  11440. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11441. loadBridge();
  11442. }
  11443. } catch (err) {
  11444. showToast('Error', err.message, 'error');
  11445. }
  11446. }
  11447. // ----------------- Hosts / MAC Table -----------------
  11448. async function loadBridgeHosts() {
  11449. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11450. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11451. try {
  11452. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11453. const res = await fetch(url);
  11454. if (res.ok) {
  11455. state.bridgeHosts = await res.json();
  11456. renderBridgeHosts();
  11457. }
  11458. } catch (err) {
  11459. console.error('Failed to load bridge hosts:', err);
  11460. }
  11461. }
  11462. function renderBridgeHosts() {
  11463. const tbody = document.getElementById('bridge-hosts-table-body');
  11464. const empty = document.getElementById('bridge-empty-hosts');
  11465. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11466. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11467. if (!tbody) return;
  11468. tbody.innerHTML = '';
  11469. const hosts = (state.bridgeHosts || []).filter(h => {
  11470. if (!search) return true;
  11471. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11472. });
  11473. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11474. if (hosts.length === 0) {
  11475. empty?.classList.remove('hidden');
  11476. return;
  11477. }
  11478. empty?.classList.add('hidden');
  11479. hosts.forEach(h => {
  11480. const tr = document.createElement('tr');
  11481. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11482. let flagBadges = '';
  11483. 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>';
  11484. 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>';
  11485. 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>';
  11486. tr.innerHTML = `
  11487. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11488. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11489. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11490. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11491. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11492. <td class="py-2.5 px-3">${flagBadges}</td>
  11493. `;
  11494. tbody.appendChild(tr);
  11495. });
  11496. }
  11497. async function flushBridgeHosts() {
  11498. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11499. if (!selBridge) {
  11500. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11501. return;
  11502. }
  11503. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11504. try {
  11505. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11506. method: 'POST',
  11507. headers: { 'Content-Type': 'application/json' },
  11508. body: JSON.stringify({ bridge: selBridge })
  11509. });
  11510. if (res.ok) {
  11511. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11512. loadBridgeHosts();
  11513. }
  11514. } catch (err) {
  11515. showToast('Error', err.message, 'error');
  11516. }
  11517. }
  11518. // ----------------- Helpers -----------------
  11519. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11520. const sel = document.getElementById(selectId);
  11521. if (!sel) return;
  11522. const prevVal = currentVal || sel.value;
  11523. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11524. (state.bridges || []).forEach(b => {
  11525. const opt = document.createElement('option');
  11526. opt.value = b.name;
  11527. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11528. if (b.name === prevVal) opt.selected = true;
  11529. sel.appendChild(opt);
  11530. });
  11531. }
  11532. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11533. const sel = document.getElementById(selectId);
  11534. if (!sel) return;
  11535. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11536. // 1. Physical Interfaces
  11537. const grpPhys = document.createElement('optgroup');
  11538. grpPhys.label = 'Physical Interfaces';
  11539. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11540. const opt = document.createElement('option');
  11541. opt.value = i.name;
  11542. opt.innerText = `${i.name} (${i.role || i.type})`;
  11543. if (i.name === currentVal) opt.selected = true;
  11544. grpPhys.appendChild(opt);
  11545. });
  11546. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11547. // 2. VLAN Sub-interfaces
  11548. const grpVlans = document.createElement('optgroup');
  11549. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11550. (state.vlans || []).forEach(v => {
  11551. const opt = document.createElement('option');
  11552. opt.value = v.name;
  11553. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11554. if (v.name === currentVal) opt.selected = true;
  11555. grpVlans.appendChild(opt);
  11556. });
  11557. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11558. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11559. const grpEoip = document.createElement('optgroup');
  11560. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11561. (state.eoipTunnels || []).forEach(t => {
  11562. const opt = document.createElement('option');
  11563. opt.value = t.name;
  11564. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11565. if (t.name === currentVal) opt.selected = true;
  11566. grpEoip.appendChild(opt);
  11567. });
  11568. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11569. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11570. const grpVxlan = document.createElement('optgroup');
  11571. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11572. (state.vxlanTunnels || []).forEach(t => {
  11573. const opt = document.createElement('option');
  11574. opt.value = t.name;
  11575. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11576. if (t.name === currentVal) opt.selected = true;
  11577. grpVxlan.appendChild(opt);
  11578. });
  11579. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11580. }
  11581. // -------------------------------------------------------------
  11582. // DebTik Routing Filters Management (/routing filter)
  11583. // -------------------------------------------------------------
  11584. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11585. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11586. if (!state.rfSort) state.rfSort = {};
  11587. function switchRoutingFilterTab(tab) {
  11588. state.activeRoutingFilterTab = tab;
  11589. const tabs = ['rules', 'community-lists', 'as-lists'];
  11590. tabs.forEach(t => {
  11591. const btn = document.getElementById(`tab-rf-${t}`);
  11592. const content = document.getElementById(`tab-content-rf-${t}`);
  11593. if (btn) {
  11594. if (t === tab) {
  11595. 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';
  11596. } else {
  11597. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11598. }
  11599. }
  11600. if (content) {
  11601. if (t === tab) content.classList.remove('hidden');
  11602. else content.classList.add('hidden');
  11603. }
  11604. });
  11605. const chainContainer = document.getElementById('rf-chain-filter-container');
  11606. if (chainContainer) {
  11607. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11608. else chainContainer.classList.add('hidden');
  11609. }
  11610. renderRoutingFilters();
  11611. }
  11612. function selectFilterRow(tab, id) {
  11613. if (state.selectedFilterRow[tab] === id) {
  11614. delete state.selectedFilterRow[tab];
  11615. } else {
  11616. state.selectedFilterRow[tab] = id;
  11617. }
  11618. if (tab === 'rules') renderRoutingFilterRules();
  11619. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11620. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11621. }
  11622. function openRoutingFilterNewModal() {
  11623. const tab = state.activeRoutingFilterTab || 'rules';
  11624. if (tab === 'rules') openAddRoutingFilterModal();
  11625. else if (tab === 'community-lists') openAddCommunityListModal();
  11626. else if (tab === 'as-lists') openAddASListModal();
  11627. }
  11628. function toggleSelectedRoutingFilter(disabled) {
  11629. const tab = state.activeRoutingFilterTab || 'rules';
  11630. const id = state.selectedFilterRow[tab];
  11631. if (!id) {
  11632. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11633. return;
  11634. }
  11635. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11636. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11637. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11638. }
  11639. function removeSelectedRoutingFilter() {
  11640. const tab = state.activeRoutingFilterTab || 'rules';
  11641. const id = state.selectedFilterRow[tab];
  11642. if (!id) {
  11643. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11644. return;
  11645. }
  11646. if (tab === 'rules') deleteRoutingFilter(id);
  11647. else if (tab === 'community-lists') deleteCommunityList(id);
  11648. else if (tab === 'as-lists') deleteASList(id);
  11649. }
  11650. function searchRoutingFilters(q) {
  11651. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11652. renderRoutingFilters();
  11653. }
  11654. function sortFilterTable(tab, col) {
  11655. if (!state.rfSort) state.rfSort = {};
  11656. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11657. if (state.rfSort[tab].col === col) {
  11658. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11659. } else {
  11660. state.rfSort[tab].col = col;
  11661. state.rfSort[tab].asc = true;
  11662. }
  11663. const asc = state.rfSort[tab].asc;
  11664. let list = [];
  11665. if (tab === 'rules') list = state.routingFilters || [];
  11666. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11667. else if (tab === 'as-lists') list = state.routingASLists || [];
  11668. list.sort((a, b) => {
  11669. let valA = a[col] ?? '';
  11670. let valB = b[col] ?? '';
  11671. if (col === 'flags') {
  11672. valA = a.disabled ? 'X' : 'A';
  11673. valB = b.disabled ? 'X' : 'A';
  11674. }
  11675. if (typeof valA === 'number' && typeof valB === 'number') {
  11676. return asc ? valA - valB : valB - valA;
  11677. }
  11678. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11679. });
  11680. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11681. allCols.forEach(c => {
  11682. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11683. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11684. });
  11685. if (tab === 'rules') renderRoutingFilterRules();
  11686. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11687. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11688. }
  11689. function renderRoutingFilters() {
  11690. const navBadge = document.getElementById('badge-filters-count');
  11691. const allRules = state.routingFilters || [];
  11692. if (navBadge) navBadge.innerText = allRules.length;
  11693. // Populate chain filter select options and datalist
  11694. const chainSelect = document.getElementById('routing-filter-chain-select');
  11695. const chainDatalist = document.getElementById('dl-routing-chains');
  11696. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11697. if (chainSelect) {
  11698. const currentVal = state.filterChainSelected || 'all';
  11699. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11700. uniqueChains.map(ch => {
  11701. const count = allRules.filter(r => r.chain === ch).length;
  11702. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11703. }).join('');
  11704. chainSelect.value = currentVal;
  11705. }
  11706. if (chainDatalist) {
  11707. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11708. }
  11709. renderRoutingFilterRules();
  11710. renderRoutingFilterCommunityLists();
  11711. renderRoutingFilterASLists();
  11712. }
  11713. function filterRoutingFiltersByChain(chain) {
  11714. state.filterChainSelected = chain;
  11715. renderRoutingFilters();
  11716. }
  11717. // -------------------------------------------------------------
  11718. // TAB 1: RULES (/routing filter rule)
  11719. // -------------------------------------------------------------
  11720. function renderRoutingFilterRules() {
  11721. const tbody = document.getElementById('routing-filter-rules-tbody');
  11722. if (!tbody) return;
  11723. const empty = document.getElementById('rf-rules-empty');
  11724. const statusCount = document.getElementById('rf-status-count');
  11725. let list = (state.routingFilters || []).slice();
  11726. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11727. list = list.filter(r => r.chain === state.filterChainSelected);
  11728. }
  11729. const q = state.rfSearchQuery;
  11730. if (q) {
  11731. list = list.filter(r =>
  11732. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11733. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11734. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11735. (r.comment && r.comment.toLowerCase().includes(q))
  11736. );
  11737. }
  11738. if (!state.rfSort?.['rules']) {
  11739. list.sort((a, b) => {
  11740. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11741. return (a.rule_order || 0) - (b.rule_order || 0);
  11742. });
  11743. }
  11744. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11745. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11746. }
  11747. if (list.length === 0) {
  11748. tbody.innerHTML = '';
  11749. if (empty) empty.classList.remove('hidden');
  11750. return;
  11751. }
  11752. if (empty) empty.classList.add('hidden');
  11753. tbody.innerHTML = list.map(r => {
  11754. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11755. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11756. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11757. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11758. let ruleDisplay = '';
  11759. if (r.rule && r.rule.trim() !== '') {
  11760. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11761. } else {
  11762. let conds = [];
  11763. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11764. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11765. let act = r.action || 'accept';
  11766. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11767. }
  11768. return `
  11769. <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'}">
  11770. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11771. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11772. <td class="py-2 px-3">
  11773. <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>
  11774. </td>
  11775. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11776. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11777. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11778. <button onclick="event.stopPropagation(); moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  11779. <button onclick="event.stopPropagation(); moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  11780. <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'}">
  11781. ${r.disabled ? 'Enable' : 'Disable'}
  11782. </button>
  11783. <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">
  11784. Edit
  11785. </button>
  11786. <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">
  11787. ✕
  11788. </button>
  11789. </td>
  11790. </tr>
  11791. `;
  11792. }).join('');
  11793. }
  11794. // -------------------------------------------------------------
  11795. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11796. // -------------------------------------------------------------
  11797. function renderRoutingFilterCommunityLists() {
  11798. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11799. if (!tbody) return;
  11800. const empty = document.getElementById('rf-comm-lists-empty');
  11801. const statusCount = document.getElementById('rf-status-count');
  11802. let list = (state.routingCommunityLists || []).slice();
  11803. const q = state.rfSearchQuery;
  11804. if (q) {
  11805. list = list.filter(cl =>
  11806. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11807. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11808. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11809. );
  11810. }
  11811. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11812. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11813. }
  11814. if (list.length === 0) {
  11815. tbody.innerHTML = '';
  11816. if (empty) empty.classList.remove('hidden');
  11817. return;
  11818. }
  11819. if (empty) empty.classList.add('hidden');
  11820. tbody.innerHTML = list.map(cl => {
  11821. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11822. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11823. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11824. const commBadges = (cl.communities || []).map(c =>
  11825. `<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>`
  11826. ).join(' ');
  11827. return `
  11828. <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'}">
  11829. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11830. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11831. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11832. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11833. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11834. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11835. <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'}">
  11836. ${cl.disabled ? 'Enable' : 'Disable'}
  11837. </button>
  11838. <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">
  11839. Edit
  11840. </button>
  11841. <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">
  11842. ✕
  11843. </button>
  11844. </td>
  11845. </tr>
  11846. `;
  11847. }).join('');
  11848. }
  11849. // -------------------------------------------------------------
  11850. // TAB 4: AS LISTS (/routing filter num-list)
  11851. // -------------------------------------------------------------
  11852. function renderRoutingFilterASLists() {
  11853. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11854. if (!tbody) return;
  11855. const empty = document.getElementById('rf-as-lists-empty');
  11856. const statusCount = document.getElementById('rf-status-count');
  11857. let list = (state.routingASLists || []).slice();
  11858. const q = state.rfSearchQuery;
  11859. if (q) {
  11860. list = list.filter(al =>
  11861. (al.name && al.name.toLowerCase().includes(q)) ||
  11862. (al.range && al.range.toLowerCase().includes(q)) ||
  11863. (al.comment && al.comment.toLowerCase().includes(q))
  11864. );
  11865. }
  11866. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11867. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11868. }
  11869. if (list.length === 0) {
  11870. tbody.innerHTML = '';
  11871. if (empty) empty.classList.remove('hidden');
  11872. return;
  11873. }
  11874. if (empty) empty.classList.add('hidden');
  11875. tbody.innerHTML = list.map(al => {
  11876. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11877. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11878. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11879. return `
  11880. <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'}">
  11881. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11882. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11883. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11884. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11885. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11886. <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'}">
  11887. ${al.disabled ? 'Enable' : 'Disable'}
  11888. </button>
  11889. <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">
  11890. Edit
  11891. </button>
  11892. <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">
  11893. ✕
  11894. </button>
  11895. </td>
  11896. </tr>
  11897. `;
  11898. }).join('');
  11899. }
  11900. // -------------------------------------------------------------
  11901. // SNIPPETS & WIZARD HELPERS
  11902. // -------------------------------------------------------------
  11903. function insertRuleSnippet(type) {
  11904. const textarea = document.getElementById('modal-rf-rule');
  11905. if (!textarea) return;
  11906. let snippet = '';
  11907. switch (type) {
  11908. case 'accept-default':
  11909. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11910. break;
  11911. case 'drop-rfc1918':
  11912. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11913. break;
  11914. case 'len-24':
  11915. snippet = 'if (dst-len > 24) { reject; }';
  11916. break;
  11917. case 'local-pref-150':
  11918. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11919. break;
  11920. case 'as-prepend-2':
  11921. snippet = 'set bgp-path-prepend 2; accept;';
  11922. break;
  11923. case 'set-comm':
  11924. snippet = 'set bgp-communities.add 65000:100; accept;';
  11925. break;
  11926. case 'match-comm':
  11927. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11928. break;
  11929. case 'reject-all':
  11930. snippet = 'reject;';
  11931. break;
  11932. }
  11933. if (!snippet) return;
  11934. if (!textarea.value.trim()) {
  11935. textarea.value = snippet;
  11936. } else {
  11937. textarea.value = textarea.value.trim() + '\n' + snippet;
  11938. }
  11939. }
  11940. function generateScriptFromWizard() {
  11941. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11942. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11943. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11944. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11945. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11946. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11947. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11948. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11949. const conds = [];
  11950. if (pfx) {
  11951. if (pfxLen) {
  11952. if (pfxLen.includes('-')) {
  11953. const parts = pfxLen.split('-');
  11954. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11955. } else {
  11956. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11957. }
  11958. } else {
  11959. conds.push(`dst in ${pfx}`);
  11960. }
  11961. }
  11962. if (proto && proto !== 'any') {
  11963. conds.push(`protocol ${proto}`);
  11964. }
  11965. if (asp) {
  11966. conds.push(`bgp-as-path "${asp}"`);
  11967. }
  11968. if (comm) {
  11969. conds.push(`bgp-communities includes ${comm}`);
  11970. }
  11971. const actions = [];
  11972. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11973. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11974. if (act && act !== 'passthrough') {
  11975. actions.push(`${act};`);
  11976. }
  11977. let code = '';
  11978. if (conds.length > 0) {
  11979. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11980. } else {
  11981. code = actions.join(' ');
  11982. }
  11983. const textarea = document.getElementById('modal-rf-rule');
  11984. if (textarea) textarea.value = code;
  11985. }
  11986. // -------------------------------------------------------------
  11987. // MODAL CRUD: RULES (/routing filter rule)
  11988. // -------------------------------------------------------------
  11989. function openAddRoutingFilterModal(defaultChain = '') {
  11990. const form = document.getElementById('routing-filter-form');
  11991. if (form) form.reset();
  11992. const idEl = document.getElementById('modal-rf-id');
  11993. if (idEl) idEl.value = '';
  11994. const titleEl = document.getElementById('modal-rf-title');
  11995. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11996. const chainEl = document.getElementById('modal-rf-chain');
  11997. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11998. const orderEl = document.getElementById('modal-rf-order');
  11999. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  12000. const ruleEl = document.getElementById('modal-rf-rule');
  12001. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  12002. const disEl = document.getElementById('modal-rf-disabled');
  12003. if (disEl) disEl.checked = false;
  12004. const modal = document.getElementById('modal-routing-filter');
  12005. if (modal) modal.classList.remove('hidden');
  12006. }
  12007. function openEditRoutingFilterModal(id) {
  12008. const r = (state.routingFilters || []).find(item => item.id === id);
  12009. if (!r) return;
  12010. const idEl = document.getElementById('modal-rf-id');
  12011. if (idEl) idEl.value = r.id;
  12012. const titleEl = document.getElementById('modal-rf-title');
  12013. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  12014. const chainEl = document.getElementById('modal-rf-chain');
  12015. if (chainEl) chainEl.value = r.chain || '';
  12016. const orderEl = document.getElementById('modal-rf-order');
  12017. if (orderEl) orderEl.value = r.rule_order || 10;
  12018. const ruleEl = document.getElementById('modal-rf-rule');
  12019. if (ruleEl) {
  12020. if (r.rule) {
  12021. ruleEl.value = r.rule;
  12022. } else {
  12023. let conds = [];
  12024. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  12025. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  12026. let act = r.action || 'accept';
  12027. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  12028. }
  12029. }
  12030. const comEl = document.getElementById('modal-rf-comment');
  12031. if (comEl) comEl.value = r.comment || '';
  12032. const disEl = document.getElementById('modal-rf-disabled');
  12033. if (disEl) disEl.checked = !!r.disabled;
  12034. const modal = document.getElementById('modal-routing-filter');
  12035. if (modal) modal.classList.remove('hidden');
  12036. }
  12037. function closeRoutingFilterModal() {
  12038. const modal = document.getElementById('modal-routing-filter');
  12039. if (modal) modal.classList.add('hidden');
  12040. }
  12041. async function submitRoutingFilter(e) {
  12042. if (e) e.preventDefault();
  12043. const payload = {
  12044. id: document.getElementById('modal-rf-id').value,
  12045. chain: document.getElementById('modal-rf-chain').value.trim(),
  12046. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  12047. rule: document.getElementById('modal-rf-rule').value.trim(),
  12048. comment: document.getElementById('modal-rf-comment').value.trim(),
  12049. disabled: document.getElementById('modal-rf-disabled').checked
  12050. };
  12051. try {
  12052. const res = await fetch(`${API_BASE}/routing/filters`, {
  12053. method: 'POST',
  12054. headers: { 'Content-Type': 'application/json' },
  12055. body: JSON.stringify(payload)
  12056. });
  12057. if (res.ok) {
  12058. closeRoutingFilterModal();
  12059. showToast('Success', 'Routing filter rule saved', 'success');
  12060. loadDynamicRouting();
  12061. } else {
  12062. const err = await res.json();
  12063. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  12064. }
  12065. } catch (err) {
  12066. showToast('Error', err.message, 'error');
  12067. }
  12068. }
  12069. async function applyRoutingFilterForm() {
  12070. const payload = {
  12071. id: document.getElementById('modal-rf-id').value,
  12072. chain: document.getElementById('modal-rf-chain').value.trim(),
  12073. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  12074. rule: document.getElementById('modal-rf-rule').value.trim(),
  12075. comment: document.getElementById('modal-rf-comment').value.trim(),
  12076. disabled: document.getElementById('modal-rf-disabled').checked
  12077. };
  12078. try {
  12079. const res = await fetch(`${API_BASE}/routing/filters`, {
  12080. method: 'POST',
  12081. headers: { 'Content-Type': 'application/json' },
  12082. body: JSON.stringify(payload)
  12083. });
  12084. if (res.ok) {
  12085. const data = await res.json();
  12086. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  12087. showToast('Applied', 'Routing filter configuration applied', 'success');
  12088. loadDynamicRouting();
  12089. } else {
  12090. const err = await res.json();
  12091. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  12092. }
  12093. } catch (err) {
  12094. showToast('Error', err.message, 'error');
  12095. }
  12096. }
  12097. async function moveRoutingFilterOrder(id, delta) {
  12098. const dir = delta < 0 ? 'up' : 'down';
  12099. try {
  12100. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/move`, {
  12101. method: 'POST',
  12102. headers: { 'Content-Type': 'application/json' },
  12103. body: JSON.stringify({ direction: dir })
  12104. });
  12105. if (!res.ok) {
  12106. const err = await res.json().catch(() => ({}));
  12107. showToast('Error', err.error || 'Failed to move filter rule', 'error');
  12108. return;
  12109. }
  12110. await loadDynamicRouting(false);
  12111. } catch (e) {
  12112. showToast('Error', e.message, 'error');
  12113. }
  12114. }
  12115. async function moveSelectedRoutingFilter(delta) {
  12116. const id = state.selectedFilterRow?.['rules'];
  12117. if (!id) {
  12118. showToast('Notice', 'Please select a routing filter rule first', 'info');
  12119. return;
  12120. }
  12121. await moveRoutingFilterOrder(id, delta);
  12122. }
  12123. async function deleteRoutingFilter(id) {
  12124. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  12125. try {
  12126. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12127. if (res.ok) {
  12128. showToast('Deleted', 'Routing filter rule removed', 'info');
  12129. loadDynamicRouting();
  12130. } else {
  12131. const err = await res.json();
  12132. showToast('Error', err.error || 'Failed to delete rule', 'error');
  12133. }
  12134. } catch (err) {
  12135. showToast('Error', err.message, 'error');
  12136. }
  12137. }
  12138. async function toggleRoutingFilterState(id, disabled) {
  12139. try {
  12140. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  12141. method: 'POST',
  12142. headers: { 'Content-Type': 'application/json' },
  12143. body: JSON.stringify({ disabled })
  12144. });
  12145. if (res.ok) {
  12146. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12147. loadDynamicRouting();
  12148. } else {
  12149. const err = await res.json();
  12150. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  12151. }
  12152. } catch (err) {
  12153. showToast('Error', err.message, 'error');
  12154. }
  12155. }
  12156. // -------------------------------------------------------------
  12157. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12158. // -------------------------------------------------------------
  12159. function openAddCommunityListModal() {
  12160. document.getElementById('modal-rf-cl-id').value = '';
  12161. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12162. document.getElementById('modal-rf-cl-name').value = '';
  12163. document.getElementById('modal-rf-cl-communities').value = '';
  12164. document.getElementById('modal-rf-cl-regexp').value = '';
  12165. document.getElementById('modal-rf-cl-comment').value = '';
  12166. document.getElementById('modal-rf-cl-disabled').checked = false;
  12167. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12168. }
  12169. function openEditCommunityListModal(id) {
  12170. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12171. if (!cl) return;
  12172. document.getElementById('modal-rf-cl-id').value = cl.id;
  12173. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12174. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12175. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12176. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12177. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12178. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12179. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12180. }
  12181. function closeCommunityListModal() {
  12182. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12183. }
  12184. async function submitCommunityList(e) {
  12185. e.preventDefault();
  12186. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12187. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12188. const payload = {
  12189. id: document.getElementById('modal-rf-cl-id').value,
  12190. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12191. communities: comms,
  12192. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12193. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12194. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12195. };
  12196. try {
  12197. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12198. method: 'POST',
  12199. headers: { 'Content-Type': 'application/json' },
  12200. body: JSON.stringify(payload)
  12201. });
  12202. if (res.ok) {
  12203. closeCommunityListModal();
  12204. showToast('Success', 'Community list saved', 'success');
  12205. loadDynamicRouting();
  12206. } else {
  12207. const err = await res.json();
  12208. showToast('Error', err.error || 'Failed to save community list', 'error');
  12209. }
  12210. } catch (err) {
  12211. showToast('Error', err.message, 'error');
  12212. }
  12213. }
  12214. async function deleteCommunityList(id) {
  12215. if (!confirm('Are you sure you want to delete this community list?')) return;
  12216. try {
  12217. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12218. if (res.ok) {
  12219. showToast('Deleted', 'Community list removed', 'info');
  12220. loadDynamicRouting();
  12221. } else {
  12222. const err = await res.json();
  12223. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12224. }
  12225. } catch (err) {
  12226. showToast('Error', err.message, 'error');
  12227. }
  12228. }
  12229. async function toggleCommunityListState(id, disabled) {
  12230. try {
  12231. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12232. method: 'POST',
  12233. headers: { 'Content-Type': 'application/json' },
  12234. body: JSON.stringify({ disabled })
  12235. });
  12236. if (res.ok) {
  12237. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12238. loadDynamicRouting();
  12239. } else {
  12240. const err = await res.json();
  12241. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12242. }
  12243. } catch (err) {
  12244. showToast('Error', err.message, 'error');
  12245. }
  12246. }
  12247. // -------------------------------------------------------------
  12248. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12249. // -------------------------------------------------------------
  12250. function openAddASListModal() {
  12251. document.getElementById('modal-rf-al-id').value = '';
  12252. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12253. document.getElementById('modal-rf-al-name').value = '';
  12254. document.getElementById('modal-rf-al-range').value = '';
  12255. document.getElementById('modal-rf-al-comment').value = '';
  12256. document.getElementById('modal-rf-al-disabled').checked = false;
  12257. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12258. }
  12259. function openEditASListModal(id) {
  12260. const al = (state.routingASLists || []).find(item => item.id === id);
  12261. if (!al) return;
  12262. document.getElementById('modal-rf-al-id').value = al.id;
  12263. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12264. document.getElementById('modal-rf-al-name').value = al.name || '';
  12265. document.getElementById('modal-rf-al-range').value = al.range || '';
  12266. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12267. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12268. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12269. }
  12270. function closeASListModal() {
  12271. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12272. }
  12273. async function submitASList(e) {
  12274. e.preventDefault();
  12275. const payload = {
  12276. id: document.getElementById('modal-rf-al-id').value,
  12277. name: document.getElementById('modal-rf-al-name').value.trim(),
  12278. range: document.getElementById('modal-rf-al-range').value.trim(),
  12279. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12280. disabled: document.getElementById('modal-rf-al-disabled').checked
  12281. };
  12282. try {
  12283. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12284. method: 'POST',
  12285. headers: { 'Content-Type': 'application/json' },
  12286. body: JSON.stringify(payload)
  12287. });
  12288. if (res.ok) {
  12289. closeASListModal();
  12290. showToast('Success', 'AS number list saved', 'success');
  12291. loadDynamicRouting();
  12292. } else {
  12293. const err = await res.json();
  12294. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12295. }
  12296. } catch (err) {
  12297. showToast('Error', err.message, 'error');
  12298. }
  12299. }
  12300. async function deleteASList(id) {
  12301. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12302. try {
  12303. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12304. if (res.ok) {
  12305. showToast('Deleted', 'AS list removed', 'info');
  12306. loadDynamicRouting();
  12307. } else {
  12308. const err = await res.json();
  12309. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12310. }
  12311. } catch (err) {
  12312. showToast('Error', err.message, 'error');
  12313. }
  12314. }
  12315. async function toggleASListState(id, disabled) {
  12316. try {
  12317. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12318. method: 'POST',
  12319. headers: { 'Content-Type': 'application/json' },
  12320. body: JSON.stringify({ disabled })
  12321. });
  12322. if (res.ok) {
  12323. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12324. loadDynamicRouting();
  12325. } else {
  12326. const err = await res.json();
  12327. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12328. }
  12329. } catch (err) {
  12330. showToast('Error', err.message, 'error');
  12331. }
  12332. }
  12333. // ==========================================
  12334. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12335. // ==========================================
  12336. async function loadNetworkOverview() {
  12337. const container = document.getElementById('tools-overview');
  12338. const timestamp = document.getElementById('tools-overview-time');
  12339. if (!container || !timestamp) return;
  12340. timestamp.textContent = 'Refreshing overview...';
  12341. const current = {};
  12342. container._overviewRequest = current;
  12343. const requests = [
  12344. ['Interfaces', '/interfaces'], ['System', '/system/status'], ['Routes', '/routes'],
  12345. ['DNS', '/dns/status'], ['WireGuard peers', '/vpn/wireguard/peers'], ['AeroTUN', '/vpn/aerotun/tunnels']
  12346. ];
  12347. const results = await Promise.all(requests.map(async ([label, path]) => {
  12348. try {
  12349. const response = await fetch(API_BASE + path);
  12350. if (!response.ok) throw new Error(await responseError(response));
  12351. return {label, data: await response.json()};
  12352. } catch (error) { return {label, error: error.message || 'Request failed'}; }
  12353. }));
  12354. // A later refresh supersedes an earlier response.
  12355. if (container._overviewRequest !== current) return;
  12356. container.replaceChildren();
  12357. for (const result of results) {
  12358. const card = document.createElement('div');
  12359. card.className = 'rounded border border-slate-700 bg-slate-950/50 p-3';
  12360. const title = document.createElement('div');
  12361. title.className = 'text-xs font-bold text-slate-200 mb-1';
  12362. title.textContent = result.label;
  12363. const detail = document.createElement('div');
  12364. detail.className = 'text-xs text-slate-400 whitespace-pre-wrap break-words';
  12365. detail.textContent = result.error ? `Unavailable: ${result.error}` : formatNetworkOverview(result.label, result.data);
  12366. card.append(title, detail); container.append(card);
  12367. }
  12368. timestamp.textContent = `Updated ${new Date().toLocaleTimeString()} · each section reports its own errors`;
  12369. }
  12370. function formatNetworkOverview(label, data) {
  12371. if (label === 'System') return `Default gateway: ${data.default_gateway || 'not reported'}`;
  12372. if (label === 'DNS') return `Active resolvers: ${(data.active_servers || []).join(', ') || 'none reported'}\nDNS service: ${data.service_running ? 'running' : 'not running'}`;
  12373. if (!Array.isArray(data)) return 'Unexpected response';
  12374. if (label === 'Routes') return `${data.length} routes reported. Open Routing for details.`;
  12375. if (!data.length) return 'None reported';
  12376. if (label === 'Interfaces') return data.map(i => `${i.name}: ${i.operstate || i.state || 'unknown'} · ${[...(i.ipv4 || []), ...(i.ipv6 || [])].join(', ') || 'no addresses'}`).join('\n');
  12377. if (label === 'WireGuard peers') return data.map(p => `${p.interface || '?'} / ${p.name || p.public_key || '?'}: ${p.disabled ? 'disabled' : 'enabled'} · last handshake ${p.latest_handshake || 'not reported'}`).join('\n');
  12378. if (label === 'AeroTUN') return data.map(t => `${t.name || '?'}: ${t.disabled ? 'disabled' : t.connected ? 'connected' : t.running ? 'running, not connected' : 'stopped'}`).join('\n');
  12379. return 'Unavailable';
  12380. }
  12381. function loadToolsView() {
  12382. loadNetworkOverview();
  12383. populateToolsInterfaces();
  12384. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12385. }
  12386. function populateToolsInterfaces() {
  12387. const pingSel = document.getElementById('tools-ping-iface');
  12388. const traceSel = document.getElementById('tools-tr-iface');
  12389. let opts = '<option value="">Auto (Default Route)</option>';
  12390. if (Array.isArray(state.interfaces)) {
  12391. state.interfaces.forEach(iface => {
  12392. if (iface.name) {
  12393. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12394. }
  12395. });
  12396. }
  12397. if (pingSel) {
  12398. const cur = pingSel.value;
  12399. pingSel.innerHTML = opts;
  12400. if (cur) pingSel.value = cur;
  12401. }
  12402. if (traceSel) {
  12403. const cur = traceSel.value;
  12404. traceSel.innerHTML = opts;
  12405. if (cur) traceSel.value = cur;
  12406. }
  12407. }
  12408. function switchToolsSubTab(subTab) {
  12409. state.activeToolsSubTab = subTab;
  12410. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12411. tabs.forEach(t => {
  12412. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12413. const view = document.getElementById(`tools-view-${t}`);
  12414. if (btn) {
  12415. if (t === subTab) {
  12416. 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';
  12417. } else {
  12418. 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';
  12419. }
  12420. }
  12421. if (view) {
  12422. if (t === subTab) {
  12423. view.classList.remove('hidden');
  12424. } else {
  12425. view.classList.add('hidden');
  12426. }
  12427. }
  12428. });
  12429. }
  12430. function setPortPreset(port) {
  12431. const input = document.getElementById('tools-port-num');
  12432. if (input) input.value = port;
  12433. }
  12434. let pingAbortController = null;
  12435. let tracerouteAbortController = null;
  12436. function clearPingTable() {
  12437. const tbody = document.getElementById('tools-ping-tbody');
  12438. if (tbody) tbody.innerHTML = '';
  12439. const rawEl = document.getElementById('tools-ping-raw');
  12440. if (rawEl) rawEl.innerText = '';
  12441. const sentEl = document.getElementById('tools-ping-stat-sent');
  12442. if (sentEl) sentEl.innerText = '0';
  12443. const recvEl = document.getElementById('tools-ping-stat-recv');
  12444. if (recvEl) recvEl.innerText = '0';
  12445. const lossEl = document.getElementById('tools-ping-stat-loss');
  12446. if (lossEl) lossEl.innerText = '0%';
  12447. const avgEl = document.getElementById('tools-ping-stat-avg');
  12448. if (avgEl) avgEl.innerText = '0 ms';
  12449. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12450. if (minMaxEl) minMaxEl.innerText = '-';
  12451. const badge = document.getElementById('tools-ping-status-badge');
  12452. if (badge) {
  12453. badge.className = '';
  12454. badge.innerText = '';
  12455. }
  12456. }
  12457. function clearTracerouteTable() {
  12458. const tbody = document.getElementById('tools-tr-tbody');
  12459. if (tbody) tbody.innerHTML = '';
  12460. const rawEl = document.getElementById('tools-tr-raw');
  12461. if (rawEl) rawEl.innerText = '';
  12462. const statHops = document.getElementById('tools-tr-hops-count');
  12463. if (statHops) statHops.innerText = '0 Hops';
  12464. }
  12465. function resetPingButton() {
  12466. const btn = document.getElementById('tools-ping-btn');
  12467. const btnText = document.getElementById('tools-ping-btn-text');
  12468. const spinner = document.getElementById('tools-ping-spinner');
  12469. if (btn) {
  12470. btn.disabled = false;
  12471. 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';
  12472. }
  12473. if (btnText) btnText.innerText = 'Start Ping';
  12474. if (spinner) spinner.classList.add('hidden');
  12475. }
  12476. function setPingRunningButton() {
  12477. const btn = document.getElementById('tools-ping-btn');
  12478. const btnText = document.getElementById('tools-ping-btn-text');
  12479. const spinner = document.getElementById('tools-ping-spinner');
  12480. if (btn) {
  12481. btn.disabled = false;
  12482. 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';
  12483. }
  12484. if (btnText) btnText.innerText = 'Stop Ping';
  12485. if (spinner) spinner.classList.remove('hidden');
  12486. }
  12487. function resetTracerouteButton() {
  12488. const btn = document.getElementById('tools-tr-btn');
  12489. const btnText = document.getElementById('tools-tr-btn-text');
  12490. const spinner = document.getElementById('tools-tr-spinner');
  12491. if (btn) {
  12492. btn.disabled = false;
  12493. 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';
  12494. }
  12495. if (btnText) btnText.innerText = 'Start Traceroute';
  12496. if (spinner) spinner.classList.add('hidden');
  12497. }
  12498. function setTracerouteRunningButton() {
  12499. const btn = document.getElementById('tools-tr-btn');
  12500. const btnText = document.getElementById('tools-tr-btn-text');
  12501. const spinner = document.getElementById('tools-tr-spinner');
  12502. if (btn) {
  12503. btn.disabled = false;
  12504. 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';
  12505. }
  12506. if (btnText) btnText.innerText = 'Stop Traceroute';
  12507. if (spinner) spinner.classList.remove('hidden');
  12508. }
  12509. async function executePing(e) {
  12510. if (e) e.preventDefault();
  12511. // If already running, clicking the button stops the stream!
  12512. if (pingAbortController) {
  12513. pingAbortController.abort();
  12514. pingAbortController = null;
  12515. resetPingButton();
  12516. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12517. return;
  12518. }
  12519. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12520. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12521. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12522. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12523. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12524. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12525. if (!target) {
  12526. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12527. return;
  12528. }
  12529. clearPingTable();
  12530. const resCard = document.getElementById('tools-ping-results');
  12531. if (resCard) resCard.classList.remove('hidden');
  12532. pingAbortController = new AbortController();
  12533. setPingRunningButton();
  12534. try {
  12535. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12536. method: 'POST',
  12537. headers: { 'Content-Type': 'application/json' },
  12538. body: JSON.stringify({
  12539. target,
  12540. count,
  12541. size,
  12542. timeout,
  12543. interface: iface,
  12544. dont_frag: dontFrag
  12545. }),
  12546. signal: pingAbortController.signal
  12547. });
  12548. if (!res.ok) {
  12549. const errText = await res.text();
  12550. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12551. resetPingButton();
  12552. pingAbortController = null;
  12553. return;
  12554. }
  12555. const reader = res.body.getReader();
  12556. const decoder = new TextDecoder('utf-8');
  12557. let buffer = '';
  12558. while (true) {
  12559. const { done, value } = await reader.read();
  12560. if (done) break;
  12561. buffer += decoder.decode(value, { stream: true });
  12562. const blocks = buffer.split('\n\n');
  12563. buffer = blocks.pop() || '';
  12564. for (const block of blocks) {
  12565. const trimmed = block.trim();
  12566. if (!trimmed) continue;
  12567. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12568. try {
  12569. const evt = JSON.parse(line);
  12570. handleLivePingEvent(evt);
  12571. } catch (parseErr) {
  12572. console.warn('Ping SSE parse error:', parseErr, line);
  12573. }
  12574. }
  12575. }
  12576. } catch (err) {
  12577. if (err.name === 'AbortError') {
  12578. // User aborted normally
  12579. } else {
  12580. showToast('Ping Error', err.message, 'error');
  12581. }
  12582. } finally {
  12583. pingAbortController = null;
  12584. resetPingButton();
  12585. }
  12586. }
  12587. function handleLivePingEvent(evt) {
  12588. const sentEl = document.getElementById('tools-ping-stat-sent');
  12589. const recvEl = document.getElementById('tools-ping-stat-recv');
  12590. const lossEl = document.getElementById('tools-ping-stat-loss');
  12591. const avgEl = document.getElementById('tools-ping-stat-avg');
  12592. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12593. const badge = document.getElementById('tools-ping-status-badge');
  12594. const tbody = document.getElementById('tools-ping-tbody');
  12595. const rawEl = document.getElementById('tools-ping-raw');
  12596. if (evt.raw && rawEl) {
  12597. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12598. rawEl.scrollTop = rawEl.scrollHeight;
  12599. }
  12600. if (evt.type === 'reply') {
  12601. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12602. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12603. if (lossEl && evt.packet_loss_pct !== undefined) {
  12604. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12605. lossEl.className = evt.packet_loss_pct === 0
  12606. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12607. : (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');
  12608. }
  12609. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12610. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12611. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12612. }
  12613. if (badge) {
  12614. if (evt.packet_loss_pct === 0) {
  12615. 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';
  12616. badge.innerText = '100% OK';
  12617. } else {
  12618. 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';
  12619. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12620. }
  12621. }
  12622. if (tbody) {
  12623. const tr = document.createElement('tr');
  12624. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12625. tr.innerHTML = `
  12626. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12627. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12628. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12629. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12630. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12631. <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>
  12632. `;
  12633. tbody.appendChild(tr);
  12634. }
  12635. } else if (evt.type === 'timeout') {
  12636. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12637. if (lossEl && evt.packet_loss_pct !== undefined) {
  12638. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12639. 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';
  12640. }
  12641. if (badge) {
  12642. 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';
  12643. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12644. }
  12645. if (tbody) {
  12646. const tr = document.createElement('tr');
  12647. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12648. tr.innerHTML = `
  12649. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12650. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12651. <td class="py-2 px-3 text-slate-600">--</td>
  12652. <td class="py-2 px-3 text-slate-600">--</td>
  12653. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12654. <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>
  12655. `;
  12656. tbody.appendChild(tr);
  12657. }
  12658. } else if (evt.type === 'unreach') {
  12659. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12660. if (lossEl && evt.packet_loss_pct !== undefined) {
  12661. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12662. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12663. }
  12664. if (badge) {
  12665. 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';
  12666. badge.innerText = 'UNREACHABLE';
  12667. }
  12668. if (tbody) {
  12669. const tr = document.createElement('tr');
  12670. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12671. tr.innerHTML = `
  12672. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12673. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12674. <td class="py-2 px-3 text-slate-600">--</td>
  12675. <td class="py-2 px-3 text-slate-600">--</td>
  12676. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12677. <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>
  12678. `;
  12679. tbody.appendChild(tr);
  12680. }
  12681. } else if (evt.type === 'stats') {
  12682. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12683. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12684. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12685. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12686. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12687. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12688. }
  12689. } else if (evt.type === 'done') {
  12690. 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');
  12691. }
  12692. }
  12693. async function executeTraceroute(e) {
  12694. if (e) e.preventDefault();
  12695. if (tracerouteAbortController) {
  12696. tracerouteAbortController.abort();
  12697. tracerouteAbortController = null;
  12698. resetTracerouteButton();
  12699. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12700. return;
  12701. }
  12702. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12703. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12704. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12705. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12706. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12707. if (!target) {
  12708. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12709. return;
  12710. }
  12711. clearTracerouteTable();
  12712. const resCard = document.getElementById('tools-tr-results');
  12713. if (resCard) resCard.classList.remove('hidden');
  12714. tracerouteAbortController = new AbortController();
  12715. setTracerouteRunningButton();
  12716. try {
  12717. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12718. method: 'POST',
  12719. headers: { 'Content-Type': 'application/json' },
  12720. body: JSON.stringify({
  12721. target,
  12722. max_hops: maxHops,
  12723. protocol,
  12724. interface: iface,
  12725. resolve
  12726. }),
  12727. signal: tracerouteAbortController.signal
  12728. });
  12729. if (!res.ok) {
  12730. const errText = await res.text();
  12731. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12732. resetTracerouteButton();
  12733. tracerouteAbortController = null;
  12734. return;
  12735. }
  12736. const reader = res.body.getReader();
  12737. const decoder = new TextDecoder('utf-8');
  12738. let buffer = '';
  12739. while (true) {
  12740. const { done, value } = await reader.read();
  12741. if (done) break;
  12742. buffer += decoder.decode(value, { stream: true });
  12743. const blocks = buffer.split('\n\n');
  12744. buffer = blocks.pop() || '';
  12745. for (const block of blocks) {
  12746. const trimmed = block.trim();
  12747. if (!trimmed) continue;
  12748. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12749. try {
  12750. const evt = JSON.parse(line);
  12751. handleLiveTracerouteEvent(evt);
  12752. } catch (parseErr) {
  12753. console.warn('Traceroute SSE parse error:', parseErr, line);
  12754. }
  12755. }
  12756. }
  12757. } catch (err) {
  12758. if (err.name === 'AbortError') {
  12759. // User aborted normally
  12760. } else {
  12761. showToast('Traceroute Error', err.message, 'error');
  12762. }
  12763. } finally {
  12764. tracerouteAbortController = null;
  12765. resetTracerouteButton();
  12766. }
  12767. }
  12768. function handleLiveTracerouteEvent(evt) {
  12769. const statHops = document.getElementById('tools-tr-hops-count');
  12770. const tbody = document.getElementById('tools-tr-tbody');
  12771. const rawEl = document.getElementById('tools-tr-raw');
  12772. if (evt.raw && rawEl) {
  12773. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12774. rawEl.scrollTop = rawEl.scrollHeight;
  12775. }
  12776. if (evt.hops_count !== undefined && statHops) {
  12777. statHops.innerText = `${evt.hops_count} Hops`;
  12778. }
  12779. if (evt.type === 'hop' && evt.hop && tbody) {
  12780. const h = evt.hop;
  12781. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12782. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12783. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12784. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12785. const tr = document.createElement('tr');
  12786. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12787. tr.innerHTML = `
  12788. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12789. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12790. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12791. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12792. <td class="py-2.5 px-3 text-right">
  12793. ${isTimeout
  12794. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12795. : '<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>'}
  12796. </td>
  12797. `;
  12798. tbody.appendChild(tr);
  12799. } else if (evt.type === 'done') {
  12800. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12801. }
  12802. }
  12803. async function executeMTR(e) {
  12804. if (e) e.preventDefault();
  12805. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12806. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12807. if (!target) {
  12808. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12809. return;
  12810. }
  12811. const btn = document.getElementById('tools-mtr-btn');
  12812. const spinner = document.getElementById('tools-mtr-spinner');
  12813. if (btn) btn.disabled = true;
  12814. if (spinner) spinner.classList.remove('hidden');
  12815. try {
  12816. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12817. method: 'POST',
  12818. headers: { 'Content-Type': 'application/json' },
  12819. body: JSON.stringify({ target, count: cycles })
  12820. });
  12821. const data = await res.json();
  12822. if (!res.ok) {
  12823. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12824. return;
  12825. }
  12826. const resCard = document.getElementById('tools-mtr-results');
  12827. if (resCard) resCard.classList.remove('hidden');
  12828. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12829. const statHops = document.getElementById('tools-mtr-hops-count');
  12830. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12831. const tbody = document.getElementById('tools-mtr-tbody');
  12832. if (tbody) {
  12833. if (hopsCount > 0) {
  12834. tbody.innerHTML = data.hops.map(h => {
  12835. 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');
  12836. return `
  12837. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12838. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12839. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12840. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12841. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12842. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12843. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12844. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12845. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12846. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12847. </tr>
  12848. `;
  12849. }).join('');
  12850. } else {
  12851. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12852. }
  12853. }
  12854. const rawEl = document.getElementById('tools-mtr-raw');
  12855. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12856. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12857. } catch (err) {
  12858. showToast('MTR Error', err.message, 'error');
  12859. } finally {
  12860. if (btn) btn.disabled = false;
  12861. if (spinner) spinner.classList.add('hidden');
  12862. }
  12863. }
  12864. async function executeDNS(e) {
  12865. if (e) e.preventDefault();
  12866. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12867. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12868. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12869. if (!domain) {
  12870. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12871. return;
  12872. }
  12873. const btn = document.getElementById('tools-dns-btn');
  12874. const spinner = document.getElementById('tools-dns-spinner');
  12875. if (btn) btn.disabled = true;
  12876. if (spinner) spinner.classList.remove('hidden');
  12877. try {
  12878. const res = await fetch(`${API_BASE}/tools/dns`, {
  12879. method: 'POST',
  12880. headers: { 'Content-Type': 'application/json' },
  12881. body: JSON.stringify({ domain, type, server })
  12882. });
  12883. const data = await res.json();
  12884. if (!res.ok) {
  12885. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12886. return;
  12887. }
  12888. const resCard = document.getElementById('tools-dns-results');
  12889. if (resCard) resCard.classList.remove('hidden');
  12890. const metaEl = document.getElementById('tools-dns-meta');
  12891. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12892. const tbody = document.getElementById('tools-dns-tbody');
  12893. if (tbody) {
  12894. if (Array.isArray(data.records) && data.records.length > 0) {
  12895. tbody.innerHTML = data.records.map(r => `
  12896. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12897. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12898. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12899. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12900. <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>
  12901. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12902. </tr>
  12903. `).join('');
  12904. } else {
  12905. 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>`;
  12906. }
  12907. }
  12908. const rawEl = document.getElementById('tools-dns-raw');
  12909. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12910. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12911. } catch (err) {
  12912. showToast('DNS Error', err.message, 'error');
  12913. } finally {
  12914. if (btn) btn.disabled = false;
  12915. if (spinner) spinner.classList.add('hidden');
  12916. }
  12917. }
  12918. async function executePortProbe(e) {
  12919. if (e) e.preventDefault();
  12920. const target = document.getElementById('tools-port-target')?.value?.trim();
  12921. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12922. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12923. if (!target || !port) {
  12924. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12925. return;
  12926. }
  12927. const btn = document.getElementById('tools-port-btn');
  12928. const spinner = document.getElementById('tools-port-spinner');
  12929. if (btn) btn.disabled = true;
  12930. if (spinner) spinner.classList.remove('hidden');
  12931. try {
  12932. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12933. method: 'POST',
  12934. headers: { 'Content-Type': 'application/json' },
  12935. body: JSON.stringify({ target, port, timeout })
  12936. });
  12937. const data = await res.json();
  12938. if (!res.ok) {
  12939. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12940. return;
  12941. }
  12942. const resCard = document.getElementById('tools-port-results');
  12943. if (resCard) resCard.classList.remove('hidden');
  12944. const banner = document.getElementById('tools-port-banner');
  12945. const icon = document.getElementById('tools-port-icon');
  12946. const title = document.getElementById('tools-port-title');
  12947. const sub = document.getElementById('tools-port-sub');
  12948. const latency = document.getElementById('tools-port-latency');
  12949. if (data.open) {
  12950. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12951. if (icon) {
  12952. 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';
  12953. icon.innerText = '✓';
  12954. }
  12955. if (title) {
  12956. title.className = 'text-sm font-bold text-emerald-300';
  12957. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12958. }
  12959. if (sub) {
  12960. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12961. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12962. }
  12963. if (latency) {
  12964. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12965. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12966. }
  12967. } else {
  12968. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12969. if (icon) {
  12970. 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';
  12971. icon.innerText = '✕';
  12972. }
  12973. if (title) {
  12974. title.className = 'text-sm font-bold text-rose-300';
  12975. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12976. }
  12977. if (sub) {
  12978. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12979. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12980. }
  12981. if (latency) {
  12982. latency.className = 'text-base font-bold font-mono text-slate-500';
  12983. latency.innerText = '--';
  12984. }
  12985. }
  12986. const rawEl = document.getElementById('tools-port-raw');
  12987. 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'}`);
  12988. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12989. } catch (err) {
  12990. showToast('Probe Error', err.message, 'error');
  12991. } finally {
  12992. if (btn) btn.disabled = false;
  12993. if (spinner) spinner.classList.add('hidden');
  12994. }
  12995. }
  12996. // ==========================================
  12997. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12998. // ==========================================
  12999. async function loadDHCPClients(showToastMsg = false) {
  13000. try {
  13001. const [clientsRes, sumRes] = await Promise.all([
  13002. fetch(`${API_BASE}/dhcp/clients`),
  13003. fetch(`${API_BASE}/dhcp/clients/summary`)
  13004. ]);
  13005. if (clientsRes.ok) {
  13006. state.dhcpClients = await clientsRes.json();
  13007. }
  13008. if (sumRes.ok) {
  13009. state.dhcpSummary = await sumRes.json();
  13010. }
  13011. renderDHCPClients();
  13012. updateDHCPSummaryCards();
  13013. const bDhcp = document.getElementById('badge-dhcp-client-count');
  13014. if (bDhcp && state.dhcpSummary) {
  13015. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  13016. }
  13017. if (showToastMsg) {
  13018. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  13019. }
  13020. } catch (err) {
  13021. console.error('Failed to load DHCP clients:', err);
  13022. if (showToastMsg) {
  13023. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  13024. }
  13025. }
  13026. }
  13027. function updateDHCPSummaryCards() {
  13028. const sum = state.dhcpSummary || {
  13029. total_clients: (state.dhcpClients || []).length,
  13030. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  13031. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  13032. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  13033. };
  13034. const totalEl = document.getElementById('dhcp-stat-total');
  13035. const boundEl = document.getElementById('dhcp-stat-bound');
  13036. const searchEl = document.getElementById('dhcp-stat-searching');
  13037. const disEl = document.getElementById('dhcp-stat-disabled');
  13038. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  13039. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  13040. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  13041. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  13042. }
  13043. function renderDHCPClients() {
  13044. const tbody = document.getElementById('dhcp-clients-tbody');
  13045. const emptyState = document.getElementById('dhcp-clients-empty');
  13046. if (!tbody) return;
  13047. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  13048. if (clients.length === 0) {
  13049. tbody.innerHTML = '';
  13050. if (emptyState) emptyState.classList.remove('hidden');
  13051. return;
  13052. }
  13053. if (emptyState) emptyState.classList.add('hidden');
  13054. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  13055. if (tbody.dataset.sig === sig) return;
  13056. tbody.dataset.sig = sig;
  13057. tbody.innerHTML = clients.map(c => {
  13058. let statusBadge = '';
  13059. if (!c.enabled) {
  13060. 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>';
  13061. } else if (c.status === 'bound') {
  13062. 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>';
  13063. } else if (c.status === 'searching') {
  13064. 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>';
  13065. } else if (c.status === 'stopped') {
  13066. 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>';
  13067. } else {
  13068. 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>`;
  13069. }
  13070. 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>';
  13071. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  13072. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  13073. 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>';
  13074. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  13075. // Option flags
  13076. const flags = [];
  13077. 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>');
  13078. 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>');
  13079. 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>');
  13080. 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>`);
  13081. return `
  13082. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  13083. <td class="py-3 px-4">
  13084. <div class="flex items-center gap-2">
  13085. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  13086. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  13087. </div>
  13088. </td>
  13089. <td class="py-3 px-4">${statusBadge}</td>
  13090. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  13091. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  13092. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  13093. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  13094. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  13095. <td class="py-3 px-4">
  13096. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  13097. </td>
  13098. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  13099. ${c.enabled ? `
  13100. <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>
  13101. <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>
  13102. <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>
  13103. ` : `
  13104. <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>
  13105. `}
  13106. <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>
  13107. <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>
  13108. </td>
  13109. </tr>
  13110. `;
  13111. }).join('');
  13112. }
  13113. function openDHCPClientModal(clientId = null) {
  13114. const modal = document.getElementById('modal-dhcp-client');
  13115. if (!modal) return;
  13116. const title = document.getElementById('modal-dhcp-title');
  13117. const idInput = document.getElementById('modal-dhcp-id');
  13118. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13119. const distInput = document.getElementById('modal-dhcp-distance');
  13120. const commentInput = document.getElementById('modal-dhcp-comment');
  13121. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  13122. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  13123. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  13124. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  13125. // Populate interfaces
  13126. if (ifaceSelect) {
  13127. let opts = '<option value="">Select interface...</option>';
  13128. const allIfaces = state.interfaces || [];
  13129. const allVlans = state.vlans || [];
  13130. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  13131. // Group 1: Physical & Bridge Interfaces
  13132. opts += '<optgroup label="Physical & Bridge Interfaces">';
  13133. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  13134. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  13135. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  13136. });
  13137. opts += '</optgroup>';
  13138. // Group 2: VLAN Interfaces
  13139. if (allVlans.length > 0) {
  13140. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  13141. allVlans.forEach(v => {
  13142. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  13143. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  13144. });
  13145. opts += '</optgroup>';
  13146. }
  13147. ifaceSelect.innerHTML = opts;
  13148. }
  13149. if (clientId) {
  13150. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  13151. if (client) {
  13152. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  13153. if (idInput) idInput.value = client.id;
  13154. if (ifaceSelect) {
  13155. ifaceSelect.value = client.interface;
  13156. ifaceSelect.disabled = true; // interface cannot be changed on edit
  13157. }
  13158. if (distInput) distInput.value = client.default_route_distance || 1;
  13159. if (commentInput) commentInput.value = client.comment || '';
  13160. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  13161. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  13162. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  13163. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  13164. }
  13165. } else {
  13166. if (title) title.innerText = 'Add DHCP Client';
  13167. if (idInput) idInput.value = '';
  13168. if (ifaceSelect) {
  13169. ifaceSelect.value = '';
  13170. ifaceSelect.disabled = false;
  13171. }
  13172. if (distInput) distInput.value = 1;
  13173. if (commentInput) commentInput.value = '';
  13174. if (defRouteCheck) defRouteCheck.checked = true;
  13175. if (peerDnsCheck) peerDnsCheck.checked = true;
  13176. if (peerNtpCheck) peerNtpCheck.checked = true;
  13177. if (enabledCheck) enabledCheck.checked = true;
  13178. }
  13179. modal.classList.remove('hidden');
  13180. }
  13181. function openDHCPClientModalForIface(ifaceName) {
  13182. openDHCPClientModal();
  13183. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  13184. if (ifaceSelect && ifaceName) {
  13185. ifaceSelect.value = ifaceName;
  13186. }
  13187. }
  13188. function closeDHCPClientModal() {
  13189. const modal = document.getElementById('modal-dhcp-client');
  13190. if (modal) modal.classList.add('hidden');
  13191. }
  13192. async function submitSaveDHCPClient(e) {
  13193. if (e) e.preventDefault();
  13194. const id = document.getElementById('modal-dhcp-id')?.value;
  13195. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  13196. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  13197. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13198. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13199. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13200. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13201. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13202. if (!id && !iface) {
  13203. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13204. return;
  13205. }
  13206. try {
  13207. let res;
  13208. if (id) {
  13209. // PUT update
  13210. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13211. method: 'PUT',
  13212. headers: { 'Content-Type': 'application/json' },
  13213. body: JSON.stringify({
  13214. enabled,
  13215. add_default_route: defRoute,
  13216. default_route_distance: distance,
  13217. use_peer_dns: peerDns,
  13218. use_peer_ntp: peerNtp,
  13219. comment
  13220. })
  13221. });
  13222. } else {
  13223. // POST create
  13224. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13225. method: 'POST',
  13226. headers: { 'Content-Type': 'application/json' },
  13227. body: JSON.stringify({
  13228. interface: iface,
  13229. enabled,
  13230. add_default_route: defRoute,
  13231. default_route_distance: distance,
  13232. use_peer_dns: peerDns,
  13233. use_peer_ntp: peerNtp,
  13234. comment
  13235. })
  13236. });
  13237. }
  13238. const data = await res.json();
  13239. if (!res.ok) {
  13240. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13241. return;
  13242. }
  13243. closeDHCPClientModal();
  13244. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13245. await loadDHCPClients();
  13246. fetchData(); // refresh interfaces list with new lease/status
  13247. } catch (err) {
  13248. showToast('Error', err.message, 'error');
  13249. }
  13250. }
  13251. async function toggleDHCPClientState(id, enabled) {
  13252. try {
  13253. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13254. method: 'POST',
  13255. headers: { 'Content-Type': 'application/json' },
  13256. body: JSON.stringify({ enabled })
  13257. });
  13258. const data = await res.json();
  13259. if (!res.ok) {
  13260. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13261. return;
  13262. }
  13263. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13264. await loadDHCPClients();
  13265. fetchData();
  13266. } catch (err) {
  13267. showToast('Error', err.message, 'error');
  13268. }
  13269. }
  13270. async function renewDHCPClient(id) {
  13271. try {
  13272. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13273. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13274. method: 'POST'
  13275. });
  13276. const data = await res.json();
  13277. if (!res.ok) {
  13278. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13279. return;
  13280. }
  13281. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13282. setTimeout(() => {
  13283. loadDHCPClients();
  13284. fetchData();
  13285. }, 1500);
  13286. } catch (err) {
  13287. showToast('Error', err.message, 'error');
  13288. }
  13289. }
  13290. async function releaseDHCPClient(id) {
  13291. try {
  13292. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13293. method: 'POST'
  13294. });
  13295. const data = await res.json();
  13296. if (!res.ok) {
  13297. showToast('Error', data.error || 'Failed to release lease', 'error');
  13298. return;
  13299. }
  13300. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13301. await loadDHCPClients();
  13302. fetchData();
  13303. } catch (err) {
  13304. showToast('Error', err.message, 'error');
  13305. }
  13306. }
  13307. async function deleteDHCPClient(id, ifaceName) {
  13308. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13309. return;
  13310. }
  13311. try {
  13312. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13313. method: 'DELETE'
  13314. });
  13315. const data = await res.json();
  13316. if (!res.ok) {
  13317. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13318. return;
  13319. }
  13320. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13321. await loadDHCPClients();
  13322. fetchData();
  13323. } catch (err) {
  13324. showToast('Error', err.message, 'error');
  13325. }
  13326. }
  13327. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13328. async function loadDHCPServer(populate = true) {
  13329. try {
  13330. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13331. fetch(`${API_BASE}/dhcp-server/summary`),
  13332. fetch(`${API_BASE}/dhcp-server/servers`),
  13333. fetch(`${API_BASE}/dhcp-server/networks`),
  13334. fetch(`${API_BASE}/dhcp-server/leases`),
  13335. fetch(`${API_BASE}/dhcp-server/options`)
  13336. ]);
  13337. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13338. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13339. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13340. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13341. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13342. const sum = state.dhcpServerSummary || {};
  13343. const srvs = state.dhcpServers || [];
  13344. const nets = state.dhcpNetworks || [];
  13345. const leases = state.dhcpLeases || [];
  13346. const opts = state.dhcpOptions || [];
  13347. // KPI Cards
  13348. const statActive = document.getElementById('dhcp-server-stat-active');
  13349. if (statActive) {
  13350. const activeCount = srvs.filter(s => s.running).length;
  13351. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13352. }
  13353. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13354. if (statLeases) {
  13355. statLeases.innerText = leases.length;
  13356. }
  13357. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13358. if (statLeasesSub) {
  13359. const dyn = leases.filter(l => l.dynamic).length;
  13360. const st = leases.filter(l => !l.dynamic).length;
  13361. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13362. }
  13363. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13364. if (statNetworks) {
  13365. statNetworks.innerText = nets.length;
  13366. }
  13367. // Subtab Badges
  13368. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13369. if (bSrv) bSrv.innerText = srvs.length;
  13370. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13371. if (bNet) bNet.innerText = nets.length;
  13372. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13373. if (bLease) bLease.innerText = leases.length;
  13374. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13375. if (bOpt) bOpt.innerText = opts.length;
  13376. // Sidebar Badge
  13377. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13378. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13379. renderCurrentDHCPServerTab();
  13380. } catch (err) {
  13381. console.error('Failed to load DHCP Server:', err);
  13382. }
  13383. }
  13384. function switchDHCPServerTab(tab) {
  13385. state.dhcpServerTab = tab;
  13386. const tabs = ['servers', 'networks', 'leases', 'options'];
  13387. tabs.forEach(t => {
  13388. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13389. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13390. if (panel) {
  13391. if (t === tab) panel.classList.remove('hidden');
  13392. else panel.classList.add('hidden');
  13393. }
  13394. if (btn) {
  13395. if (t === tab) {
  13396. 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';
  13397. } else {
  13398. 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';
  13399. }
  13400. }
  13401. });
  13402. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13403. if (addBtn) {
  13404. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13405. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13406. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13407. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13408. }
  13409. renderCurrentDHCPServerTab();
  13410. }
  13411. function handleDHCPServerPrimaryAdd() {
  13412. const tab = state.dhcpServerTab || 'servers';
  13413. if (tab === 'servers') openAddDHCPServerModal();
  13414. else if (tab === 'networks') openAddDHCPNetworkModal();
  13415. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13416. else if (tab === 'options') openAddDHCPOptionModal();
  13417. }
  13418. function renderCurrentDHCPServerTab() {
  13419. const tab = state.dhcpServerTab || 'servers';
  13420. if (tab === 'servers') renderDHCPServers();
  13421. else if (tab === 'networks') renderDHCPNetworks();
  13422. else if (tab === 'leases') renderDHCPLeases();
  13423. else if (tab === 'options') renderDHCPOptions();
  13424. }
  13425. function renderDHCPServers() {
  13426. const tbody = document.getElementById('dhcp-server-tbody');
  13427. const empty = document.getElementById('dhcp-server-empty');
  13428. if (!tbody) return;
  13429. const servers = state.dhcpServers || [];
  13430. if (servers.length === 0) {
  13431. tbody.innerHTML = '';
  13432. empty?.classList.remove('hidden');
  13433. return;
  13434. }
  13435. empty?.classList.add('hidden');
  13436. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13437. if (tbody.dataset.sig === sig) return;
  13438. tbody.dataset.sig = sig;
  13439. tbody.innerHTML = '';
  13440. servers.forEach(s => {
  13441. const tr = document.createElement('tr');
  13442. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13443. tr.innerHTML = `
  13444. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13445. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13446. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13447. <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>
  13448. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13449. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13450. <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>
  13451. <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>
  13452. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13453. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13454. <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>
  13455. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13456. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13457. </td>
  13458. `;
  13459. tbody.appendChild(tr);
  13460. });
  13461. }
  13462. function renderDHCPNetworks() {
  13463. const tbody = document.getElementById('dhcp-networks-tbody');
  13464. const empty = document.getElementById('dhcp-networks-empty');
  13465. if (!tbody) return;
  13466. tbody.innerHTML = '';
  13467. const networks = state.dhcpNetworks || [];
  13468. if (networks.length === 0) {
  13469. empty?.classList.remove('hidden');
  13470. return;
  13471. }
  13472. empty?.classList.add('hidden');
  13473. networks.forEach(n => {
  13474. const tr = document.createElement('tr');
  13475. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13476. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13477. const optionsChips = (n.dhcp_options || []).map(optId => {
  13478. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13479. if (!opt) return '';
  13480. 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>`;
  13481. }).filter(Boolean).join('');
  13482. tr.innerHTML = `
  13483. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13484. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13485. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13486. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13487. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13488. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13489. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13490. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13491. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13492. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13493. </td>
  13494. `;
  13495. tbody.appendChild(tr);
  13496. });
  13497. }
  13498. function renderDHCPLeases() {
  13499. const tbody = document.getElementById('dhcp-leases-tbody');
  13500. const empty = document.getElementById('dhcp-leases-empty');
  13501. if (!tbody) return;
  13502. tbody.innerHTML = '';
  13503. const leases = state.dhcpLeases || [];
  13504. if (leases.length === 0) {
  13505. empty?.classList.remove('hidden');
  13506. return;
  13507. }
  13508. empty?.classList.add('hidden');
  13509. leases.forEach(l => {
  13510. const tr = document.createElement('tr');
  13511. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13512. 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>';
  13513. const statusBadge = l.status === 'bound'
  13514. ? '<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>'
  13515. : l.status === 'static'
  13516. ? '<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>'
  13517. : '<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>';
  13518. const makeStaticBtn = l.dynamic
  13519. ? `<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>`
  13520. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13521. tr.innerHTML = `
  13522. <td class="py-2.5 px-3 text-center">${flag}</td>
  13523. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13524. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13525. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13526. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13527. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13528. <td class="py-2.5 px-3">${statusBadge}</td>
  13529. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13530. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13531. ${makeStaticBtn}
  13532. </td>
  13533. `;
  13534. tbody.appendChild(tr);
  13535. });
  13536. }
  13537. function renderDHCPOptions() {
  13538. const tbody = document.getElementById('dhcp-options-tbody');
  13539. const empty = document.getElementById('dhcp-options-empty');
  13540. if (!tbody) return;
  13541. tbody.innerHTML = '';
  13542. const options = state.dhcpOptions || [];
  13543. if (options.length === 0) {
  13544. empty?.classList.remove('hidden');
  13545. return;
  13546. }
  13547. empty?.classList.add('hidden');
  13548. options.forEach(o => {
  13549. const tr = document.createElement('tr');
  13550. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13551. tr.innerHTML = `
  13552. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13553. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13554. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13555. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13556. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13557. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13558. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13559. </td>
  13560. `;
  13561. tbody.appendChild(tr);
  13562. });
  13563. }
  13564. // ==================== MODALS & ACTIONS: SERVER ====================
  13565. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13566. const sel = document.getElementById(elemId);
  13567. if (!sel) return;
  13568. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13569. const networks = state.dhcpNetworks || [];
  13570. networks.forEach(n => {
  13571. const opt = document.createElement('option');
  13572. opt.value = n.address;
  13573. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13574. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13575. opt.selected = true;
  13576. }
  13577. sel.appendChild(opt);
  13578. });
  13579. }
  13580. function onDHCPServerNetworkChange() {
  13581. const netSel = document.getElementById('dhcp-server-modal-network');
  13582. if (!netSel) return;
  13583. const netVal = netSel.value;
  13584. if (!netVal) return;
  13585. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13586. if (!poolInput) return;
  13587. // Auto-calculate suggested address pool based on subnet CIDR
  13588. const parts = netVal.split('/');
  13589. const ip = parts[0];
  13590. const cidr = parseInt(parts[1] || '24', 10);
  13591. if (cidr === 24) {
  13592. const octets = ip.split('.');
  13593. if (octets.length === 4) {
  13594. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13595. poolInput.value = `${base}.10-${base}.254`;
  13596. }
  13597. }
  13598. }
  13599. function openAddDHCPServerModal() {
  13600. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13601. document.getElementById('dhcp-server-modal-id').value = '';
  13602. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13603. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13604. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13605. document.getElementById('dhcp-server-modal-comment').value = '';
  13606. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13607. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13608. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13609. const networks = state.dhcpNetworks || [];
  13610. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13611. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13612. if (defaultNet) {
  13613. onDHCPServerNetworkChange();
  13614. }
  13615. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13616. }
  13617. function openEditDHCPServerModal(id) {
  13618. const s = (state.dhcpServers || []).find(item => item.id === id);
  13619. if (!s) return;
  13620. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13621. document.getElementById('dhcp-server-modal-id').value = s.id;
  13622. document.getElementById('dhcp-server-modal-name').value = s.name;
  13623. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13624. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13625. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13626. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13627. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13628. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13629. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13630. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13631. }
  13632. function closeDHCPServerModal() {
  13633. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13634. }
  13635. async function submitSaveDHCPServer(e) {
  13636. e.preventDefault();
  13637. const id = document.getElementById('dhcp-server-modal-id').value;
  13638. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13639. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13640. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13641. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13642. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13643. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13644. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13645. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13646. try {
  13647. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13648. method: 'POST',
  13649. headers: { 'Content-Type': 'application/json' },
  13650. body: JSON.stringify({
  13651. id,
  13652. name,
  13653. interface: iface,
  13654. network,
  13655. address_pool: pool,
  13656. lease_time: leaseTime,
  13657. authoritative,
  13658. disabled,
  13659. comment
  13660. })
  13661. });
  13662. if (res.ok) {
  13663. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13664. closeDHCPServerModal();
  13665. loadDHCPServer(false);
  13666. fetchData(false);
  13667. } else {
  13668. const err = await res.text();
  13669. showToast('Error', err, 'error');
  13670. }
  13671. } catch (err) {
  13672. showToast('Error', err.message, 'error');
  13673. }
  13674. }
  13675. async function toggleDHCPServerState(id, disabled) {
  13676. try {
  13677. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13678. method: 'POST',
  13679. headers: { 'Content-Type': 'application/json' },
  13680. body: JSON.stringify({ disabled })
  13681. });
  13682. if (res.ok) {
  13683. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13684. loadDHCPServer(false);
  13685. fetchData(false);
  13686. }
  13687. } catch (err) {
  13688. showToast('Error', err.message, 'error');
  13689. }
  13690. }
  13691. async function deleteDHCPServer(id, name) {
  13692. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13693. try {
  13694. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13695. if (res.ok) {
  13696. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13697. loadDHCPServer(false);
  13698. fetchData(false);
  13699. }
  13700. } catch (err) {
  13701. showToast('Error', err.message, 'error');
  13702. }
  13703. }
  13704. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13705. function openAddDHCPNetworkModal() {
  13706. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13707. document.getElementById('dhcp-network-modal-id').value = '';
  13708. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13709. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13710. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13711. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13712. document.getElementById('dhcp-network-modal-netmask').value = '';
  13713. document.getElementById('dhcp-network-modal-comment').value = '';
  13714. renderDHCPNetworkOptionsCheckboxes([]);
  13715. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13716. }
  13717. function openEditDHCPNetworkModal(id) {
  13718. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13719. if (!n) return;
  13720. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13721. document.getElementById('dhcp-network-modal-id').value = n.id;
  13722. document.getElementById('dhcp-network-modal-address').value = n.address;
  13723. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13724. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13725. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13726. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13727. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13728. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13729. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13730. }
  13731. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13732. const container = document.getElementById('dhcp-network-modal-options-list');
  13733. if (!container) return;
  13734. container.innerHTML = '';
  13735. const opts = state.dhcpOptions || [];
  13736. if (opts.length === 0) {
  13737. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13738. return;
  13739. }
  13740. opts.forEach(o => {
  13741. const isChecked = selectedIds.includes(o.id);
  13742. const label = document.createElement('label');
  13743. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13744. label.innerHTML = `
  13745. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13746. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13747. `;
  13748. container.appendChild(label);
  13749. });
  13750. }
  13751. function closeDHCPNetworkModal() {
  13752. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13753. }
  13754. async function submitSaveDHCPNetwork(e) {
  13755. e.preventDefault();
  13756. const id = document.getElementById('dhcp-network-modal-id').value;
  13757. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13758. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13759. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13760. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13761. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13762. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13763. const selectedOpts = [];
  13764. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13765. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13766. try {
  13767. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13768. method: 'POST',
  13769. headers: { 'Content-Type': 'application/json' },
  13770. body: JSON.stringify({
  13771. id,
  13772. address,
  13773. gateway,
  13774. netmask,
  13775. dns_servers: dnsServers,
  13776. domain,
  13777. dhcp_options: selectedOpts,
  13778. comment
  13779. })
  13780. });
  13781. if (res.ok) {
  13782. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13783. closeDHCPNetworkModal();
  13784. loadDHCPServer(false);
  13785. fetchData(false);
  13786. } else {
  13787. const err = await res.text();
  13788. showToast('Error', err, 'error');
  13789. }
  13790. } catch (err) {
  13791. showToast('Error', err.message, 'error');
  13792. }
  13793. }
  13794. async function deleteDHCPNetwork(id, addr) {
  13795. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13796. try {
  13797. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13798. if (res.ok) {
  13799. showToast('Deleted', `Network ${addr} removed`, 'success');
  13800. loadDHCPServer(false);
  13801. fetchData(false);
  13802. }
  13803. } catch (err) {
  13804. showToast('Error', err.message, 'error');
  13805. }
  13806. }
  13807. // ==================== MODALS & ACTIONS: LEASES ====================
  13808. function openAddDHCPStaticLeaseModal() {
  13809. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13810. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13811. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13812. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13813. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13814. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13815. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13816. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13817. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13818. }
  13819. function closeDHCPStaticLeaseModal() {
  13820. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13821. }
  13822. async function submitSaveDHCPStaticLease(e) {
  13823. e.preventDefault();
  13824. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13825. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13826. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13827. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13828. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13829. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13830. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13831. try {
  13832. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13833. method: 'POST',
  13834. headers: { 'Content-Type': 'application/json' },
  13835. body: JSON.stringify({
  13836. id,
  13837. mac_address: mac,
  13838. address: ip,
  13839. hostname,
  13840. server,
  13841. comment,
  13842. disabled
  13843. })
  13844. });
  13845. if (res.ok) {
  13846. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13847. closeDHCPStaticLeaseModal();
  13848. loadDHCPServer(false);
  13849. fetchData(false);
  13850. } else {
  13851. const err = await res.text();
  13852. showToast('Error', err, 'error');
  13853. }
  13854. } catch (err) {
  13855. showToast('Error', err.message, 'error');
  13856. }
  13857. }
  13858. async function deleteDHCPStaticLease(id) {
  13859. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13860. try {
  13861. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13862. if (res.ok) {
  13863. showToast('Deleted', 'Static lease removed', 'success');
  13864. loadDHCPServer(false);
  13865. fetchData(false);
  13866. }
  13867. } catch (err) {
  13868. showToast('Error', err.message, 'error');
  13869. }
  13870. }
  13871. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13872. try {
  13873. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13874. method: 'POST',
  13875. headers: { 'Content-Type': 'application/json' },
  13876. body: JSON.stringify({
  13877. mac_address: mac,
  13878. address: ip,
  13879. hostname,
  13880. comment: comment || 'Converted to static'
  13881. })
  13882. });
  13883. if (res.ok) {
  13884. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13885. loadDHCPServer(false);
  13886. fetchData(false);
  13887. } else {
  13888. const err = await res.text();
  13889. showToast('Error', err, 'error');
  13890. }
  13891. } catch (err) {
  13892. showToast('Error', err.message, 'error');
  13893. }
  13894. }
  13895. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13896. function openAddDHCPOptionModal() {
  13897. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13898. document.getElementById('dhcp-option-modal-id').value = '';
  13899. document.getElementById('dhcp-option-modal-name').value = '';
  13900. document.getElementById('dhcp-option-modal-code').value = '';
  13901. document.getElementById('dhcp-option-modal-value').value = '';
  13902. document.getElementById('dhcp-option-modal-comment').value = '';
  13903. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13904. }
  13905. function openEditDHCPOptionModal(id) {
  13906. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13907. if (!o) return;
  13908. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13909. document.getElementById('dhcp-option-modal-id').value = o.id;
  13910. document.getElementById('dhcp-option-modal-name').value = o.name;
  13911. document.getElementById('dhcp-option-modal-code').value = o.code;
  13912. document.getElementById('dhcp-option-modal-value').value = o.value;
  13913. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13914. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13915. }
  13916. function closeDHCPOptionModal() {
  13917. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13918. }
  13919. async function submitSaveDHCPOption(e) {
  13920. e.preventDefault();
  13921. const id = document.getElementById('dhcp-option-modal-id').value;
  13922. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13923. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13924. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13925. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13926. try {
  13927. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13928. method: 'POST',
  13929. headers: { 'Content-Type': 'application/json' },
  13930. body: JSON.stringify({ id, name, code, value, comment })
  13931. });
  13932. if (res.ok) {
  13933. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13934. closeDHCPOptionModal();
  13935. loadDHCPServer(false);
  13936. fetchData(false);
  13937. } else {
  13938. const err = await res.text();
  13939. showToast('Error', err, 'error');
  13940. }
  13941. } catch (err) {
  13942. showToast('Error', err.message, 'error');
  13943. }
  13944. }
  13945. async function deleteDHCPOption(id, name) {
  13946. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13947. try {
  13948. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13949. if (res.ok) {
  13950. showToast('Deleted', `Option ${name} removed`, 'success');
  13951. loadDHCPServer(false);
  13952. fetchData(false);
  13953. }
  13954. } catch (err) {
  13955. showToast('Error', err.message, 'error');
  13956. }
  13957. }
  13958. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13959. function openDHCPServerSetupModal() {
  13960. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13961. onDHCPWizardIfaceChange();
  13962. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13963. }
  13964. function closeDHCPServerSetupModal() {
  13965. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13966. }
  13967. function onDHCPWizardIfaceChange() {
  13968. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13969. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13970. let ip = '192.168.88.1';
  13971. let prefix = '24';
  13972. if (iface && iface.ip_address) {
  13973. const parts = iface.ip_address.split('/');
  13974. ip = parts[0];
  13975. if (parts.length > 1) prefix = parts[1];
  13976. }
  13977. // Calculate subnet base (e.g. 192.168.88.0/24)
  13978. const ipParts = ip.split('.');
  13979. if (ipParts.length === 4) {
  13980. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13981. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13982. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13983. document.getElementById('dhcp-wizard-gateway').value = ip;
  13984. document.getElementById('dhcp-wizard-pool').value = pool;
  13985. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13986. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13987. }
  13988. }
  13989. async function submitDHCPServerSetupWizard(e) {
  13990. e.preventDefault();
  13991. const iface = document.getElementById('dhcp-wizard-iface').value;
  13992. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13993. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13994. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13995. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13996. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13997. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13998. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13999. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  14000. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  14001. try {
  14002. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  14003. method: 'POST',
  14004. headers: { 'Content-Type': 'application/json' },
  14005. body: JSON.stringify({
  14006. interface: iface,
  14007. address_space: space,
  14008. gateway: gw,
  14009. address_pool: pool,
  14010. dns_servers: dnsServers,
  14011. lease_time: leaseTime,
  14012. ntp_servers: ntpServers,
  14013. next_server: tftp
  14014. })
  14015. });
  14016. if (res.ok) {
  14017. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  14018. closeDHCPServerSetupModal();
  14019. loadDHCPServer(false);
  14020. fetchData(false);
  14021. } else {
  14022. const err = await res.text();
  14023. showToast('Error', err, 'error');
  14024. }
  14025. } catch (err) {
  14026. showToast('Error', err.message, 'error');
  14027. }
  14028. }
  14029. function populateDHCPIfaceSelect(elemId, selectedVal) {
  14030. const sel = document.getElementById(elemId);
  14031. if (!sel) return;
  14032. sel.innerHTML = '<option value="">Select interface...</option>';
  14033. const ifaces = state.interfaces || [];
  14034. ifaces.forEach(i => {
  14035. if (i.name === 'lo') return;
  14036. const opt = document.createElement('option');
  14037. opt.value = i.name;
  14038. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  14039. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  14040. if (i.name === selectedVal) opt.selected = true;
  14041. sel.appendChild(opt);
  14042. });
  14043. }
  14044. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  14045. function initTableSorting() {
  14046. document.querySelectorAll('table').forEach(setupSortableTable);
  14047. }
  14048. function setupSortableTable(table) {
  14049. const thead = table.querySelector('thead');
  14050. const tbody = table.querySelector('tbody');
  14051. if (!thead || !tbody) return;
  14052. const headerRows = thead.querySelectorAll('tr');
  14053. if (headerRows.length === 0) return;
  14054. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  14055. ths.forEach((th, colIdx) => {
  14056. if (th._sortBound) return;
  14057. th._sortBound = true;
  14058. const rawText = th.innerText.trim().toLowerCase();
  14059. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  14060. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  14061. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  14062. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  14063. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  14064. return;
  14065. }
  14066. th.classList.add('table-sortable', 'group');
  14067. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  14068. let icon = th.querySelector('.table-sort-icon');
  14069. if (!icon) {
  14070. icon = document.createElement('span');
  14071. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  14072. icon.innerHTML = '⇅';
  14073. th.appendChild(icon);
  14074. }
  14075. th.addEventListener('click', (e) => {
  14076. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  14077. handleHeaderClick(table, th, colIdx);
  14078. });
  14079. });
  14080. if (!tbody._sortObserved) {
  14081. tbody._sortObserved = true;
  14082. let sortDebounceTimer = null;
  14083. const observer = new MutationObserver((mutations) => {
  14084. if (tbody._isSorting) return;
  14085. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  14086. if (!hasChildChanges) return;
  14087. clearTimeout(sortDebounceTimer);
  14088. sortDebounceTimer = setTimeout(() => {
  14089. if (tbody._isSorting) return;
  14090. if (table._activeSort && table._activeSort.dir !== 'none') {
  14091. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  14092. } else {
  14093. tagOriginalRowOrder(tbody);
  14094. }
  14095. }, 50);
  14096. });
  14097. tbody._sortObserver = observer;
  14098. observer.observe(tbody, { childList: true });
  14099. }
  14100. tagOriginalRowOrder(tbody);
  14101. }
  14102. function tagOriginalRowOrder(tbody) {
  14103. let idx = 0;
  14104. Array.from(tbody.children).forEach(tr => {
  14105. if (!tr.querySelector('td[colspan]')) {
  14106. if (!tr.hasAttribute('data-orig-idx')) {
  14107. tr.setAttribute('data-orig-idx', idx++);
  14108. }
  14109. }
  14110. });
  14111. }
  14112. function handleHeaderClick(table, th, colIdx) {
  14113. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  14114. let newDir = 'asc';
  14115. if (currentSort.colIdx === colIdx) {
  14116. if (currentSort.dir === 'asc') newDir = 'desc';
  14117. else if (currentSort.dir === 'desc') newDir = 'none';
  14118. else newDir = 'asc';
  14119. } else {
  14120. newDir = 'asc';
  14121. }
  14122. table._activeSort = { colIdx, dir: newDir };
  14123. updateHeaderIcons(table, colIdx, newDir);
  14124. applyTableSort(table, colIdx, newDir, true);
  14125. }
  14126. function updateHeaderIcons(table, activeColIdx, dir) {
  14127. const thead = table.querySelector('thead');
  14128. if (!thead) return;
  14129. const ths = thead.querySelectorAll('th');
  14130. ths.forEach((th, idx) => {
  14131. const icon = th.querySelector('.table-sort-icon');
  14132. if (!icon) return;
  14133. if (idx === activeColIdx && dir !== 'none') {
  14134. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  14135. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  14136. th.classList.add('table-sorted-active');
  14137. } else {
  14138. icon.innerHTML = '⇅';
  14139. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  14140. th.classList.remove('table-sorted-active');
  14141. }
  14142. });
  14143. }
  14144. function applyTableSort(table, colIdx, dir, userInitiated) {
  14145. const tbody = table.querySelector('tbody');
  14146. if (!tbody || tbody.children.length <= 1) return;
  14147. tbody._isSorting = true;
  14148. tagOriginalRowOrder(tbody);
  14149. // Group parent rows and any attached drawer/sub-rows
  14150. const groups = [];
  14151. let currentGroup = null;
  14152. Array.from(tbody.children).forEach(tr => {
  14153. if (tr.querySelector('td[colspan]')) {
  14154. if (currentGroup) {
  14155. currentGroup.subRows.push(tr);
  14156. } else {
  14157. groups.push({ mainRow: tr, subRows: [] });
  14158. }
  14159. } else {
  14160. currentGroup = { mainRow: tr, subRows: [] };
  14161. groups.push(currentGroup);
  14162. }
  14163. });
  14164. if (dir === 'none') {
  14165. groups.sort((a, b) => {
  14166. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14167. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  14168. return idxA - idxB;
  14169. });
  14170. } else {
  14171. groups.sort((a, b) => {
  14172. const cellA = a.mainRow.children[colIdx];
  14173. const cellB = b.mainRow.children[colIdx];
  14174. const res = compareTableCells(cellA, cellB);
  14175. return dir === 'asc' ? res : -res;
  14176. });
  14177. }
  14178. // Check if rows are already in correct order to avoid modifying DOM
  14179. let alreadyOrdered = true;
  14180. let childIdx = 0;
  14181. for (const g of groups) {
  14182. if (tbody.children[childIdx] !== g.mainRow) {
  14183. alreadyOrdered = false;
  14184. break;
  14185. }
  14186. childIdx++;
  14187. for (const sub of g.subRows) {
  14188. if (tbody.children[childIdx] !== sub) {
  14189. alreadyOrdered = false;
  14190. break;
  14191. }
  14192. childIdx++;
  14193. }
  14194. }
  14195. if (alreadyOrdered) {
  14196. tbody._isSorting = false;
  14197. return;
  14198. }
  14199. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14200. if (tbody._sortObserver) {
  14201. tbody._sortObserver.disconnect();
  14202. }
  14203. // Re-append rows in sorted order
  14204. groups.forEach(g => {
  14205. tbody.appendChild(g.mainRow);
  14206. g.subRows.forEach(sub => tbody.appendChild(sub));
  14207. });
  14208. // Drain any queued mutations and re-connect observer
  14209. if (tbody._sortObserver) {
  14210. tbody._sortObserver.takeRecords();
  14211. tbody._sortObserver.observe(tbody, { childList: true });
  14212. }
  14213. tbody._isSorting = false;
  14214. }
  14215. function getCellRawText(cell) {
  14216. if (!cell) return '';
  14217. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14218. const input = cell.querySelector('input, select');
  14219. if (input) {
  14220. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14221. return input.value;
  14222. }
  14223. return cell.innerText.trim();
  14224. }
  14225. function parseTrafficToNumber(str) {
  14226. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14227. if (!m) return null;
  14228. const num = parseFloat(m[1].replace(/,/g, ''));
  14229. if (isNaN(num)) return null;
  14230. const unit = m[2].toUpperCase();
  14231. let mult = 1;
  14232. if (unit.startsWith('K')) mult = 1024;
  14233. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14234. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14235. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14236. return num * mult;
  14237. }
  14238. function parseIpToNumber(str) {
  14239. const clean = str.replace(/^[!~]/, '').trim();
  14240. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14241. if (!m) return null;
  14242. const o1 = parseInt(m[1], 10);
  14243. const o2 = parseInt(m[2], 10);
  14244. const o3 = parseInt(m[3], 10);
  14245. const o4 = parseInt(m[4], 10);
  14246. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14247. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14248. }
  14249. function parseCompoundPackets(str) {
  14250. const m = str.match(/^([\d,]+)p/);
  14251. if (!m) return null;
  14252. return parseInt(m[1].replace(/,/g, ''), 10);
  14253. }
  14254. function compareTableCells(cellA, cellB) {
  14255. const a = getCellRawText(cellA);
  14256. const b = getCellRawText(cellB);
  14257. if (a === '' && b !== '') return 1;
  14258. if (b === '' && a !== '') return -1;
  14259. if (a === b) return 0;
  14260. // 1. IP Addresses / CIDR
  14261. const ipA = parseIpToNumber(a);
  14262. const ipB = parseIpToNumber(b);
  14263. if (ipA !== null && ipB !== null) return ipA - ipB;
  14264. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14265. const pktA = parseCompoundPackets(a);
  14266. const pktB = parseCompoundPackets(b);
  14267. if (pktA !== null && pktB !== null) return pktA - pktB;
  14268. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14269. const trafA = parseTrafficToNumber(a);
  14270. const trafB = parseTrafficToNumber(b);
  14271. if (trafA !== null && trafB !== null) return trafA - trafB;
  14272. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14273. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14274. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14275. const numA = Number(cleanNumA);
  14276. const numB = Number(cleanNumB);
  14277. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14278. return numA - numB;
  14279. }
  14280. // 5. Natural case-insensitive string compare
  14281. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14282. }
  14283. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14284. async function loadVRRP(showToastNotification = false) {
  14285. try {
  14286. const [instRes, sumRes] = await Promise.all([
  14287. fetch(`${API_BASE}/vrrp/instances`),
  14288. fetch(`${API_BASE}/vrrp/summary`)
  14289. ]);
  14290. if (instRes.ok) {
  14291. state.vrrpInstances = await instRes.json();
  14292. renderVRRP();
  14293. }
  14294. if (sumRes.ok) {
  14295. state.vrrpSummary = await sumRes.json();
  14296. renderVRRPSummary();
  14297. }
  14298. if (showToastNotification) {
  14299. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14300. }
  14301. } catch (err) {
  14302. console.error('Failed to load VRRP:', err);
  14303. }
  14304. }
  14305. function renderVRRPSummary() {
  14306. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14307. const elTotal = document.getElementById('vrrp-stat-total');
  14308. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14309. const elMaster = document.getElementById('vrrp-stat-master');
  14310. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14311. const elBackup = document.getElementById('vrrp-stat-backup');
  14312. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14313. const bCount = document.getElementById('badge-vrrp-count');
  14314. if (bCount) bCount.innerText = s.total_instances || 0;
  14315. const dot = document.getElementById('badge-vrrp-dot');
  14316. if (dot) {
  14317. if (s.master_instances > 0) {
  14318. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14319. } else if (s.backup_instances > 0) {
  14320. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14321. } else {
  14322. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14323. }
  14324. }
  14325. }
  14326. function renderVRRP() {
  14327. const tbody = document.getElementById('vrrp-table-tbody');
  14328. const empty = document.getElementById('vrrp-table-empty');
  14329. if (!tbody) return;
  14330. tbody.innerHTML = '';
  14331. const instances = state.vrrpInstances || [];
  14332. if (instances.length === 0) {
  14333. empty?.classList.remove('hidden');
  14334. return;
  14335. }
  14336. empty?.classList.add('hidden');
  14337. instances.forEach(inst => {
  14338. const tr = document.createElement('tr');
  14339. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14340. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14341. 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>`;
  14342. if (inst.disabled) {
  14343. 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>`;
  14344. } else if (inst.state === 'MASTER') {
  14345. 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>`;
  14346. } else if (inst.state === 'BACKUP') {
  14347. 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>`;
  14348. } else if (inst.state === 'FAULT') {
  14349. 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>`;
  14350. }
  14351. // Render State Badge
  14352. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14353. if (!inst.disabled) {
  14354. if (inst.state === 'MASTER') {
  14355. 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>`;
  14356. } else if (inst.state === 'BACKUP') {
  14357. 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>`;
  14358. } else if (inst.state === 'FAULT') {
  14359. 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>`;
  14360. }
  14361. }
  14362. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14363. tr.innerHTML = `
  14364. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14365. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14366. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14367. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14368. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14369. <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>
  14370. <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>
  14371. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14372. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14373. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14374. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14375. <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>
  14376. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14377. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14378. </td>
  14379. `;
  14380. tbody.appendChild(tr);
  14381. });
  14382. }
  14383. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14384. const sel = document.getElementById(elemId);
  14385. if (!sel) return;
  14386. sel.innerHTML = '<option value="">Select interface...</option>';
  14387. const ifaces = state.interfaces || [];
  14388. ifaces.forEach(i => {
  14389. const opt = document.createElement('option');
  14390. opt.value = i.name;
  14391. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14392. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14393. sel.appendChild(opt);
  14394. });
  14395. }
  14396. function openAddVRRPModal() {
  14397. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14398. document.getElementById('modal-vrrp-id').value = '';
  14399. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14400. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14401. document.getElementById('modal-vrrp-priority').value = 100;
  14402. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14403. document.getElementById('modal-vrrp-version').value = '3';
  14404. document.getElementById('modal-vrrp-interval').value = 1;
  14405. document.getElementById('modal-vrrp-authtype').value = 'none';
  14406. document.getElementById('modal-vrrp-authpass').value = '';
  14407. document.getElementById('modal-vrrp-comment').value = '';
  14408. document.getElementById('modal-vrrp-preempt').checked = true;
  14409. document.getElementById('modal-vrrp-disabled').checked = false;
  14410. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14411. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14412. }
  14413. function openEditVRRPModal(id) {
  14414. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14415. if (!inst) return;
  14416. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14417. document.getElementById('modal-vrrp-id').value = inst.id;
  14418. document.getElementById('modal-vrrp-name').value = inst.name;
  14419. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14420. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14421. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14422. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14423. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14424. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14425. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14426. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14427. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14428. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14429. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14430. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14431. }
  14432. function closeVRRPModal() {
  14433. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14434. }
  14435. async function submitSaveVRRP(e) {
  14436. e.preventDefault();
  14437. const id = document.getElementById('modal-vrrp-id').value;
  14438. const name = document.getElementById('modal-vrrp-name').value.trim();
  14439. const iface = document.getElementById('modal-vrrp-iface').value;
  14440. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14441. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14442. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14443. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14444. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14445. const authType = document.getElementById('modal-vrrp-authtype').value;
  14446. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14447. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14448. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14449. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14450. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14451. try {
  14452. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14453. method: 'POST',
  14454. headers: { 'Content-Type': 'application/json' },
  14455. body: JSON.stringify({
  14456. id,
  14457. name,
  14458. interface: iface,
  14459. vrid,
  14460. priority,
  14461. virtual_ips: vips,
  14462. version,
  14463. interval,
  14464. auth_type: authType,
  14465. auth_password: authPass,
  14466. comment,
  14467. preempt,
  14468. disabled
  14469. })
  14470. });
  14471. if (res.ok) {
  14472. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14473. closeVRRPModal();
  14474. loadVRRP(false);
  14475. fetchData(false);
  14476. } else {
  14477. const err = await res.text();
  14478. showToast('Error', err, 'error');
  14479. }
  14480. } catch (err) {
  14481. showToast('Error', err.message, 'error');
  14482. }
  14483. }
  14484. async function deleteVRRP(id, name) {
  14485. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14486. try {
  14487. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14488. if (res.ok) {
  14489. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14490. loadVRRP(false);
  14491. fetchData(false);
  14492. } else {
  14493. const err = await res.text();
  14494. showToast('Error', err, 'error');
  14495. }
  14496. } catch (err) {
  14497. showToast('Error', err.message, 'error');
  14498. }
  14499. }
  14500. async function toggleVRRPState(id, disabled) {
  14501. try {
  14502. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14503. method: 'POST',
  14504. headers: { 'Content-Type': 'application/json' },
  14505. body: JSON.stringify({ disabled })
  14506. });
  14507. if (res.ok) {
  14508. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14509. loadVRRP(false);
  14510. fetchData(false);
  14511. } else {
  14512. const err = await res.text();
  14513. showToast('Error', err, 'error');
  14514. }
  14515. } catch (err) {
  14516. showToast('Error', err.message, 'error');
  14517. }
  14518. }
  14519. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14520. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14521. let docSortDebounce = null;
  14522. const docTableObserver = new MutationObserver((mutations) => {
  14523. let needsInit = false;
  14524. for (const m of mutations) {
  14525. for (const node of m.addedNodes) {
  14526. if (node.nodeType === 1) {
  14527. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14528. needsInit = true;
  14529. break;
  14530. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14531. needsInit = true;
  14532. break;
  14533. }
  14534. }
  14535. }
  14536. if (needsInit) break;
  14537. }
  14538. if (needsInit) {
  14539. clearTimeout(docSortDebounce);
  14540. docSortDebounce = setTimeout(initTableSorting, 100);
  14541. }
  14542. });
  14543. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14544. }
  14545. // =========================================================================
  14546. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14547. // =========================================================================
  14548. const bwtestState = {
  14549. running: false,
  14550. pollTimer: null,
  14551. eventSource: null,
  14552. chartPoints: [],
  14553. maxChartPoints: 60,
  14554. serverConfig: null,
  14555. peakTx: 0,
  14556. peakRx: 0,
  14557. targetDuration: 10,
  14558. lastSampleElapsed: -1,
  14559. sessionID: null
  14560. };
  14561. async function loadBwTestView() {
  14562. resizeBwTestCanvas();
  14563. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14564. }
  14565. async function fetchBwTestServerStatus() {
  14566. try {
  14567. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14568. if (!res.ok) return;
  14569. const s = await res.json();
  14570. bwtestState.serverConfig = s;
  14571. // Update indicator and badges
  14572. const indicator = document.getElementById('bwtest-server-indicator');
  14573. const badge = document.getElementById('bwtest-server-badge');
  14574. const sideBadge = document.getElementById('badge-bwtest-server');
  14575. if (s.enabled && s.running) {
  14576. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14577. if (badge) {
  14578. badge.innerText = `Port ${s.port} (Active)`;
  14579. badge.className = 'text-emerald-400 font-bold';
  14580. }
  14581. if (sideBadge) {
  14582. sideBadge.innerText = s.port;
  14583. 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';
  14584. }
  14585. } else {
  14586. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14587. if (badge) {
  14588. badge.innerText = `Disabled`;
  14589. badge.className = 'text-slate-500 font-bold';
  14590. }
  14591. if (sideBadge) {
  14592. sideBadge.innerText = 'Off';
  14593. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14594. }
  14595. }
  14596. // Modal fields
  14597. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14598. const serverModal = document.getElementById('modal-bwtest-server');
  14599. const editing = serverModal && !serverModal.classList.contains('hidden');
  14600. if (toggle && !editing) toggle.checked = !!s.enabled;
  14601. const portInp = document.getElementById('bwtest-server-port-input');
  14602. if (portInp && !editing) portInp.value = s.port || 2000;
  14603. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14604. if (actSess) actSess.innerText = s.active_sessions || 0;
  14605. const totServ = document.getElementById('bwtest-modal-total-served');
  14606. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14607. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14608. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14609. } catch (err) {
  14610. console.error('Failed to fetch BwTest server status:', err);
  14611. }
  14612. }
  14613. function openBwTestServerModal() {
  14614. const cfg = bwtestState.serverConfig;
  14615. if (cfg) {
  14616. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14617. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14618. }
  14619. fetchBwTestServerStatus();
  14620. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14621. }
  14622. function closeBwTestServerModal() {
  14623. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14624. }
  14625. async function submitBwTestServerSettings(e) {
  14626. e.preventDefault();
  14627. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14628. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14629. try {
  14630. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14631. method: 'POST',
  14632. headers: { 'Content-Type': 'application/json' },
  14633. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14634. });
  14635. if (!res.ok) {
  14636. const err = await res.json();
  14637. throw new Error(err.error || 'Failed to update server configuration');
  14638. }
  14639. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14640. closeBwTestServerModal();
  14641. fetchBwTestServerStatus();
  14642. } catch (err) {
  14643. showToast('Server Configuration Error', err.message, 'error');
  14644. }
  14645. }
  14646. function setBwTestTarget(target) {
  14647. const inp = document.getElementById('bwtest-input-target');
  14648. if (inp) inp.value = target;
  14649. }
  14650. function setBwTestProtocol(proto) {
  14651. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14652. if (hiddenInp) hiddenInp.value = proto;
  14653. const btnUdp = document.getElementById('bwtest-proto-udp');
  14654. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14655. const badge = document.getElementById('bwtest-proto-badge');
  14656. const pktField = document.getElementById('bwtest-field-pktsize');
  14657. 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';
  14658. 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';
  14659. 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';
  14660. if (proto === 'udp') {
  14661. if (btnUdp) {
  14662. btnUdp.className = activeUdpCls;
  14663. const dot = btnUdp.querySelector('span');
  14664. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14665. }
  14666. if (btnTcp) {
  14667. btnTcp.className = inactiveCls;
  14668. const dot = btnTcp.querySelector('span');
  14669. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14670. }
  14671. if (badge) {
  14672. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14673. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14674. }
  14675. if (pktField) pktField.classList.remove('opacity-40');
  14676. } else {
  14677. if (btnUdp) {
  14678. btnUdp.className = inactiveCls;
  14679. const dot = btnUdp.querySelector('span');
  14680. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14681. }
  14682. if (btnTcp) {
  14683. btnTcp.className = activeTcpCls;
  14684. const dot = btnTcp.querySelector('span');
  14685. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14686. }
  14687. if (badge) {
  14688. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14689. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14690. }
  14691. if (pktField) pktField.classList.add('opacity-40');
  14692. }
  14693. }
  14694. function setBwTestDirection(dir) {
  14695. const hiddenInp = document.getElementById('bwtest-input-direction');
  14696. if (hiddenInp) hiddenInp.value = dir;
  14697. const btnBoth = document.getElementById('bwtest-dir-both');
  14698. const btnTx = document.getElementById('bwtest-dir-tx');
  14699. const btnRx = document.getElementById('bwtest-dir-rx');
  14700. 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';
  14701. 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';
  14702. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14703. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14704. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14705. }
  14706. function setBwTestLimit(bps) {
  14707. const sel = document.getElementById('bwtest-input-limit');
  14708. if (sel) sel.value = String(bps);
  14709. }
  14710. async function checkActiveBwTest() {
  14711. try {
  14712. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14713. if (!res.ok) return;
  14714. const st = await res.json();
  14715. if (st.running) {
  14716. setBwTestRunningUI(true);
  14717. processBwTestStatus(st);
  14718. startBwTestTelemetry();
  14719. }
  14720. } catch (err) {
  14721. console.error('Failed to check active BwTest:', err);
  14722. }
  14723. }
  14724. async function startBwTest(e) {
  14725. if (e && e.preventDefault) e.preventDefault();
  14726. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14727. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14728. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14729. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14730. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14731. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14732. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14733. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14734. bwtestState.targetDuration = duration;
  14735. bwtestState.chartPoints = [];
  14736. bwtestState.peakTx = 0;
  14737. bwtestState.peakRx = 0;
  14738. bwtestState.lastSampleElapsed = -1;
  14739. bwtestState.sessionID = null;
  14740. // Clear UI elements
  14741. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14742. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14743. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14744. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14745. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14746. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14747. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14748. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14749. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14750. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14751. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14752. const tbody = document.getElementById('bwtest-samples-tbody');
  14753. if (tbody) tbody.innerHTML = '';
  14754. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14755. setBwTestRunningUI(true);
  14756. try {
  14757. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14758. method: 'POST',
  14759. headers: { 'Content-Type': 'application/json' },
  14760. body: JSON.stringify({
  14761. target,
  14762. port,
  14763. direction,
  14764. protocol,
  14765. bandwidth_limit,
  14766. packet_size,
  14767. streams,
  14768. duration
  14769. })
  14770. });
  14771. if (!res.ok) {
  14772. const err = await res.json();
  14773. throw new Error(err.error || 'Failed to start bandwidth test');
  14774. }
  14775. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14776. startBwTestTelemetry();
  14777. } catch (err) {
  14778. setBwTestRunningUI(false);
  14779. showToast('Start Failed', err.message, 'error');
  14780. }
  14781. }
  14782. function setBwTestRunningUI(running) {
  14783. bwtestState.running = running;
  14784. const startBtn = document.getElementById('bwtest-btn-start');
  14785. const stopBtn = document.getElementById('bwtest-btn-stop');
  14786. const badge = document.getElementById('bwtest-run-status-badge');
  14787. const ph = document.getElementById('bwtest-chart-placeholder');
  14788. if (running) {
  14789. if (startBtn) {
  14790. startBtn.disabled = true;
  14791. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14792. }
  14793. if (stopBtn) {
  14794. stopBtn.disabled = false;
  14795. stopBtn.classList.remove('opacity-40');
  14796. }
  14797. if (badge) {
  14798. badge.innerText = 'TESTING...';
  14799. 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';
  14800. }
  14801. if (ph) ph.style.display = 'none';
  14802. } else {
  14803. if (startBtn) {
  14804. startBtn.disabled = false;
  14805. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14806. }
  14807. if (stopBtn) {
  14808. stopBtn.disabled = true;
  14809. stopBtn.classList.add('opacity-40');
  14810. }
  14811. if (badge) {
  14812. badge.innerText = 'IDLE';
  14813. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14814. }
  14815. }
  14816. }
  14817. async function stopBwTest() {
  14818. try {
  14819. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14820. if (!res.ok) throw new Error(await responseError(res));
  14821. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14822. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14823. } catch (err) {
  14824. showToast('Stop Failed', err.message, 'error');
  14825. }
  14826. }
  14827. async function responseError(res) {
  14828. const text = await res.text();
  14829. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14830. catch { return text || `HTTP ${res.status}`; }
  14831. }
  14832. function processBwTestStatus(st) {
  14833. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14834. bwtestState.sessionID = st.session_id;
  14835. bwtestState.lastSampleElapsed = -1;
  14836. }
  14837. for (const sample of st.recent_samples || []) {
  14838. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14839. handleBwTestSample(sample);
  14840. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14841. }
  14842. }
  14843. if (!st.running) {
  14844. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14845. bwtestState.pollTimer = null;
  14846. setBwTestRunningUI(false);
  14847. handleBwTestFinish(st.summary, st.error);
  14848. }
  14849. }
  14850. function startBwTestTelemetry() {
  14851. if (!state.currentUser) return;
  14852. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14853. let busy = false;
  14854. const poll = async () => {
  14855. if (busy || !state.currentUser || document.hidden) return;
  14856. busy = true;
  14857. try {
  14858. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14859. if (!res.ok) throw new Error(await responseError(res));
  14860. processBwTestStatus(await res.json());
  14861. } catch (err) {
  14862. console.error('BwTest polling error:', err);
  14863. } finally { busy = false; }
  14864. };
  14865. bwtestState.pollTimer = setInterval(poll, 400);
  14866. poll();
  14867. }
  14868. function handleBwTestSample(s) {
  14869. if (!s) return;
  14870. const payloadHint = document.getElementById('bwtest-effective-payload');
  14871. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14872. const txMbps = s.tx_mbps || 0;
  14873. const rxMbps = s.rx_mbps || 0;
  14874. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14875. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14876. // KPI updates
  14877. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14878. if (elTx) {
  14879. elTx.innerText = txMbps.toFixed(2);
  14880. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14881. }
  14882. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14883. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14884. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14885. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14886. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14887. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14888. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14889. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14890. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14891. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14892. const elLoss = document.getElementById('bwtest-stat-loss');
  14893. if (elLoss) {
  14894. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14895. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14896. }
  14897. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14898. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14899. const elJitter = document.getElementById('bwtest-stat-jitter');
  14900. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14901. const elTime = document.getElementById('bwtest-stat-time');
  14902. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14903. const elData = document.getElementById('bwtest-stat-data');
  14904. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14905. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14906. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14907. // Append point to chart buffer
  14908. bwtestState.chartPoints.push({
  14909. elapsed: s.elapsed_sec || 0,
  14910. tx: txMbps,
  14911. rx: rxMbps
  14912. });
  14913. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14914. bwtestState.chartPoints.shift();
  14915. }
  14916. drawBwTestChart();
  14917. // Add row to breakdown table
  14918. const tbody = document.getElementById('bwtest-samples-tbody');
  14919. if (tbody) {
  14920. const tr = document.createElement('tr');
  14921. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14922. tr.innerHTML = `
  14923. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14924. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14925. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14926. <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>
  14927. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14928. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14929. `;
  14930. tbody.insertBefore(tr, tbody.firstChild);
  14931. const countEl = document.getElementById('bwtest-sample-count');
  14932. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14933. }
  14934. }
  14935. function handleBwTestFinish(summary, error) {
  14936. const badge = document.getElementById('bwtest-run-status-badge');
  14937. if (error) {
  14938. showToast('Benchmark Error', error, 'error');
  14939. if (badge) {
  14940. badge.innerText = 'ERROR';
  14941. 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';
  14942. }
  14943. } else if (summary) {
  14944. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14945. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14946. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14947. if (badge) {
  14948. badge.innerText = 'COMPLETED';
  14949. 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';
  14950. }
  14951. }
  14952. loadBwTestHistory();
  14953. fetchBwTestServerStatus();
  14954. }
  14955. function resizeBwTestCanvas() {
  14956. const canvas = document.getElementById('bwtest-chart');
  14957. if (!canvas || !canvas.parentElement) return;
  14958. const rect = canvas.parentElement.getBoundingClientRect();
  14959. const dpr = window.devicePixelRatio || 1;
  14960. canvas.width = rect.width * dpr;
  14961. canvas.height = rect.height * dpr;
  14962. const ctx = canvas.getContext('2d');
  14963. ctx.scale(dpr, dpr);
  14964. drawBwTestChart();
  14965. }
  14966. window.addEventListener('resize', () => {
  14967. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14968. });
  14969. function drawBwTestChart() {
  14970. const canvas = document.getElementById('bwtest-chart');
  14971. if (!canvas) return;
  14972. const ctx = canvas.getContext('2d');
  14973. const dpr = window.devicePixelRatio || 1;
  14974. const width = canvas.width / dpr;
  14975. const height = canvas.height / dpr;
  14976. ctx.clearRect(0, 0, width, height);
  14977. const points = bwtestState.chartPoints;
  14978. if (!points || points.length === 0) return;
  14979. // Determine scale ceiling
  14980. let maxRate = 10;
  14981. for (const p of points) {
  14982. if (p.tx > maxRate) maxRate = p.tx;
  14983. if (p.rx > maxRate) maxRate = p.rx;
  14984. }
  14985. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14986. const paddingLeft = 55;
  14987. const paddingBottom = 24;
  14988. const paddingTop = 12;
  14989. const paddingRight = 16;
  14990. const chartW = width - paddingLeft - paddingRight;
  14991. const chartH = height - paddingTop - paddingBottom;
  14992. // Grid Lines and Y-Axis labels
  14993. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14994. ctx.lineWidth = 1;
  14995. ctx.fillStyle = '#94a3b8';
  14996. ctx.font = '10px monospace';
  14997. ctx.textAlign = 'right';
  14998. const gridSteps = 4;
  14999. for (let i = 0; i <= gridSteps; i++) {
  15000. const val = (maxRate / gridSteps) * i;
  15001. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  15002. ctx.beginPath();
  15003. ctx.moveTo(paddingLeft, y);
  15004. ctx.lineTo(width - paddingRight, y);
  15005. ctx.stroke();
  15006. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  15007. }
  15008. // Draw TX Line (Cyan #22d3ee)
  15009. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  15010. // Draw RX Line (Purple #a855f7)
  15011. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  15012. }
  15013. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  15014. if (points.length < 2) return;
  15015. const stepX = w / Math.max(points.length - 1, 1);
  15016. // Gradient area fill
  15017. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  15018. grad.addColorStop(0, fillColor);
  15019. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  15020. ctx.beginPath();
  15021. points.forEach((p, idx) => {
  15022. const x = left + idx * stepX;
  15023. const val = valFn(p);
  15024. const y = top + h - (val / maxVal) * h;
  15025. if (idx === 0) {
  15026. ctx.moveTo(x, y);
  15027. } else {
  15028. ctx.lineTo(x, y);
  15029. }
  15030. });
  15031. // Complete path for fill
  15032. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  15033. ctx.lineTo(left, top + h);
  15034. ctx.closePath();
  15035. ctx.fillStyle = grad;
  15036. ctx.fill();
  15037. // Draw line stroke
  15038. ctx.beginPath();
  15039. ctx.lineWidth = 2.5;
  15040. ctx.strokeStyle = strokeColor;
  15041. points.forEach((p, idx) => {
  15042. const x = left + idx * stepX;
  15043. const val = valFn(p);
  15044. const y = top + h - (val / maxVal) * h;
  15045. if (idx === 0) {
  15046. ctx.moveTo(x, y);
  15047. } else {
  15048. ctx.lineTo(x, y);
  15049. }
  15050. });
  15051. ctx.stroke();
  15052. // Draw end point halo
  15053. const lastP = points[points.length - 1];
  15054. const lastX = left + (points.length - 1) * stepX;
  15055. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  15056. ctx.fillStyle = strokeColor;
  15057. ctx.beginPath();
  15058. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  15059. ctx.fill();
  15060. }
  15061. async function loadBwTestHistory() {
  15062. try {
  15063. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  15064. if (!res.ok) return;
  15065. const list = await res.json();
  15066. renderBwTestHistory(Array.isArray(list) ? list : []);
  15067. } catch (err) {
  15068. console.error('Failed to load BwTest history:', err);
  15069. }
  15070. }
  15071. function renderBwTestHistory(list) {
  15072. const tbody = document.getElementById('bwtest-history-tbody');
  15073. if (!tbody) return;
  15074. if (list.length === 0) {
  15075. 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>`;
  15076. return;
  15077. }
  15078. tbody.innerHTML = '';
  15079. list.forEach(item => {
  15080. const s = item.summary || {};
  15081. const tr = document.createElement('tr');
  15082. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  15083. const dirBadge = item.direction === 'both'
  15084. ? `<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>`
  15085. : item.direction === 'tx'
  15086. ? `<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>`
  15087. : `<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>`;
  15088. const protoBadge = item.protocol === 'tcp'
  15089. ? `<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>`
  15090. : `<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>`;
  15091. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  15092. tr.innerHTML = `
  15093. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  15094. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  15095. <td class="py-2.5 px-4">${protoBadge}</td>
  15096. <td class="py-2.5 px-4">${dirBadge}</td>
  15097. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  15098. <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>
  15099. <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>
  15100. <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>
  15101. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  15102. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  15103. `;
  15104. tbody.appendChild(tr);
  15105. });
  15106. }
  15107. // ======================== SETTINGS & ROUTER DNS ========================
  15108. state.settingsSubTab = 'dns';
  15109. state.dnsSettings = null;
  15110. state.dnsStaticRecords = [];
  15111. state.dnsStatus = null;
  15112. function switchSettingsSubTab(sub) {
  15113. state.settingsSubTab = sub;
  15114. const btnDns = document.getElementById('btn-settings-subtab-dns');
  15115. const btnSys = document.getElementById('btn-settings-subtab-system');
  15116. const btnBak = document.getElementById('btn-settings-subtab-backup');
  15117. const tabDns = document.getElementById('settings-subtab-dns');
  15118. const tabSys = document.getElementById('settings-subtab-system');
  15119. const tabBak = document.getElementById('settings-subtab-backup');
  15120. 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';
  15121. 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';
  15122. if (btnDns) btnDns.className = inactiveClass;
  15123. if (btnSys) btnSys.className = inactiveClass;
  15124. if (btnBak) btnBak.className = inactiveClass;
  15125. tabDns?.classList.add('hidden');
  15126. tabSys?.classList.add('hidden');
  15127. tabBak?.classList.add('hidden');
  15128. if (sub === 'dns') {
  15129. if (btnDns) btnDns.className = activeClass;
  15130. tabDns?.classList.remove('hidden');
  15131. loadDNSSettings();
  15132. } else if (sub === 'system') {
  15133. if (btnSys) btnSys.className = activeClass;
  15134. tabSys?.classList.remove('hidden');
  15135. loadSystemSettings();
  15136. } else if (sub === 'backup') {
  15137. if (btnBak) btnBak.className = activeClass;
  15138. tabBak?.classList.remove('hidden');
  15139. loadBackupList();
  15140. }
  15141. }
  15142. async function loadSettingsData(showLoading = false) {
  15143. if (state.settingsSubTab === 'system') {
  15144. await loadSystemSettings();
  15145. } else if (state.settingsSubTab === 'backup') {
  15146. await loadBackupList();
  15147. } else {
  15148. await loadDNSSettings();
  15149. }
  15150. }
  15151. async function loadDNSSettings() {
  15152. try {
  15153. const [settingsRes, staticRes, statusRes] = await Promise.all([
  15154. fetch(`${API_BASE}/dns/settings`),
  15155. fetch(`${API_BASE}/dns/static`),
  15156. fetch(`${API_BASE}/dns/status`)
  15157. ]);
  15158. if (settingsRes.ok) {
  15159. state.dnsSettings = await settingsRes.json();
  15160. populateDNSSettingsForm(state.dnsSettings);
  15161. }
  15162. if (staticRes.ok) {
  15163. state.dnsStaticRecords = await staticRes.json();
  15164. renderStaticDNSList();
  15165. }
  15166. if (statusRes.ok) {
  15167. state.dnsStatus = await statusRes.json();
  15168. updateDNSStatusView(state.dnsStatus);
  15169. }
  15170. } catch (err) {
  15171. console.error('Failed to load DNS settings:', err);
  15172. }
  15173. }
  15174. function populateDNSSettingsForm(s) {
  15175. if (!s) return;
  15176. const dnsForm = document.getElementById('form-dns-settings');
  15177. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  15178. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  15179. if (dynamicEl) {
  15180. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  15181. 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(' ');
  15182. } else {
  15183. dynamicEl.innerText = 'None';
  15184. }
  15185. }
  15186. // If user is actively typing or editing in the form, do not overwrite their inputs!
  15187. if (isEditing) return;
  15188. const serversInput = document.getElementById('dns-servers-input');
  15189. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  15190. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  15191. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  15192. const domainInput = document.getElementById('dns-domain-input');
  15193. if (domainInput) domainInput.value = s.domain || '';
  15194. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  15195. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  15196. }
  15197. function updateDNSStatusView(st) {
  15198. if (!st) return;
  15199. const preview = document.getElementById('dns-resolv-preview');
  15200. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15201. const pillText = document.getElementById('dns-live-status-text');
  15202. const pill = document.getElementById('dns-live-status-pill');
  15203. if (pill && pillText) {
  15204. if (st.service_running) {
  15205. 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';
  15206. pillText.innerText = 'DNS Service Active';
  15207. } else {
  15208. 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';
  15209. pillText.innerText = 'DNS Service Inactive';
  15210. }
  15211. }
  15212. }
  15213. function appendDNSPreset(preset) {
  15214. const input = document.getElementById('dns-servers-input');
  15215. if (!input) return;
  15216. const dnsForm = document.getElementById('form-dns-settings');
  15217. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15218. const current = input.value.trim();
  15219. if (!current) {
  15220. input.value = preset;
  15221. } else {
  15222. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15223. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15224. toAdd.forEach(ip => {
  15225. if (!existing.includes(ip)) existing.push(ip);
  15226. });
  15227. input.value = existing.join(', ');
  15228. }
  15229. }
  15230. async function saveDNSSettings(e) {
  15231. e.preventDefault();
  15232. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15233. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15234. if (servers.length === 0) {
  15235. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15236. return;
  15237. }
  15238. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15239. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15240. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15241. try {
  15242. const res = await fetch(`${API_BASE}/dns/settings`, {
  15243. method: 'POST',
  15244. headers: { 'Content-Type': 'application/json' },
  15245. body: JSON.stringify({
  15246. servers: servers,
  15247. cache_size: cacheSize,
  15248. domain: domain,
  15249. allow_remote_requests: allowRemote
  15250. })
  15251. });
  15252. const data = await res.json();
  15253. if (res.ok) {
  15254. const dnsForm = document.getElementById('form-dns-settings');
  15255. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15256. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15257. loadDNSSettings();
  15258. } else {
  15259. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15260. }
  15261. } catch (err) {
  15262. showToast('Error', err.message, 'error');
  15263. }
  15264. }
  15265. async function flushDNSCache() {
  15266. try {
  15267. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15268. if (res.ok) {
  15269. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15270. loadDNSSettings();
  15271. } else {
  15272. const err = await res.json();
  15273. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15274. }
  15275. } catch (err) {
  15276. showToast('Error', err.message, 'error');
  15277. }
  15278. }
  15279. function renderStaticDNSList() {
  15280. const tbody = document.getElementById('dns-static-tbody');
  15281. const empty = document.getElementById('dns-static-empty');
  15282. const badge = document.getElementById('dns-static-count-badge');
  15283. if (!tbody) return;
  15284. tbody.innerHTML = '';
  15285. const records = state.dnsStaticRecords || [];
  15286. if (badge) badge.innerText = `${records.length} Records`;
  15287. if (records.length === 0) {
  15288. empty?.classList.remove('hidden');
  15289. return;
  15290. }
  15291. empty?.classList.add('hidden');
  15292. records.forEach(rec => {
  15293. const tr = document.createElement('tr');
  15294. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15295. tr.innerHTML = `
  15296. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15297. <td class="py-2.5 px-4">
  15298. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15299. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15300. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15301. }">
  15302. ${rec.type || 'A'}
  15303. </span>
  15304. </td>
  15305. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15306. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15307. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15308. <td class="py-2.5 px-4">
  15309. <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'}">
  15310. ${rec.disabled ? 'Disabled' : 'Active'}
  15311. </span>
  15312. </td>
  15313. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15314. <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>
  15315. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15316. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15317. </td>
  15318. `;
  15319. tbody.appendChild(tr);
  15320. });
  15321. }
  15322. function openStaticDNSModal(id = null) {
  15323. const modal = document.getElementById('modal-static-dns');
  15324. const title = document.getElementById('modal-static-dns-title');
  15325. const form = document.getElementById('form-static-dns');
  15326. if (!modal || !form) return;
  15327. form.reset();
  15328. document.getElementById('modal-static-dns-id').value = '';
  15329. if (id) {
  15330. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15331. if (rec) {
  15332. if (title) title.innerText = 'Edit Static DNS Record';
  15333. document.getElementById('modal-static-dns-id').value = rec.id;
  15334. document.getElementById('modal-static-dns-name').value = rec.name;
  15335. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15336. document.getElementById('modal-static-dns-addr').value = rec.address;
  15337. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15338. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15339. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15340. }
  15341. } else {
  15342. if (title) title.innerText = 'Add Static DNS Record';
  15343. }
  15344. modal.classList.remove('hidden');
  15345. }
  15346. function closeStaticDNSModal() {
  15347. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15348. }
  15349. async function submitSaveStaticDNS(e) {
  15350. e.preventDefault();
  15351. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15352. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15353. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15354. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15355. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15356. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15357. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15358. if (!name || !address) {
  15359. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15360. return;
  15361. }
  15362. try {
  15363. const res = await fetch(`${API_BASE}/dns/static`, {
  15364. method: 'POST',
  15365. headers: { 'Content-Type': 'application/json' },
  15366. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15367. });
  15368. const data = await res.json();
  15369. if (res.ok) {
  15370. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15371. closeStaticDNSModal();
  15372. loadDNSSettings();
  15373. } else {
  15374. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15375. }
  15376. } catch (err) {
  15377. showToast('Error', err.message, 'error');
  15378. }
  15379. }
  15380. async function deleteStaticDNS(id) {
  15381. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15382. try {
  15383. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15384. if (res.ok) {
  15385. showToast('Deleted', 'Static DNS record deleted', 'success');
  15386. loadDNSSettings();
  15387. }
  15388. } catch (err) {
  15389. showToast('Error', err.message, 'error');
  15390. }
  15391. }
  15392. async function toggleStaticDNS(id, disabled) {
  15393. try {
  15394. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15395. method: 'POST',
  15396. headers: { 'Content-Type': 'application/json' },
  15397. body: JSON.stringify({ disabled })
  15398. });
  15399. if (res.ok) {
  15400. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15401. loadDNSSettings();
  15402. }
  15403. } catch (err) {
  15404. showToast('Error', err.message, 'error');
  15405. }
  15406. }
  15407. async function loadSystemSettings() {
  15408. try {
  15409. const sysForm = document.getElementById('form-system-settings');
  15410. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15411. const res = await fetch(`${API_BASE}/system/settings`);
  15412. if (res.ok) {
  15413. const data = await res.json();
  15414. if (!isEditing) {
  15415. const hostInput = document.getElementById('system-hostname-input');
  15416. if (hostInput) hostInput.value = data.hostname || '';
  15417. const tzInput = document.getElementById('system-timezone-input');
  15418. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15419. }
  15420. }
  15421. } catch (err) {
  15422. console.error('Failed to load system settings:', err);
  15423. }
  15424. }
  15425. async function saveSystemSettings(e) {
  15426. e.preventDefault();
  15427. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15428. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15429. try {
  15430. const res = await fetch(`${API_BASE}/system/settings`, {
  15431. method: 'POST',
  15432. headers: { 'Content-Type': 'application/json' },
  15433. body: JSON.stringify({ hostname, timezone })
  15434. });
  15435. const data = await res.json();
  15436. if (res.ok) {
  15437. const sysForm = document.getElementById('form-system-settings');
  15438. if (sysForm) sysForm.dataset.dirty = 'false';
  15439. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15440. const sideH = document.getElementById('side-hostname');
  15441. if (sideH) sideH.innerText = data.hostname;
  15442. } else {
  15443. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15444. }
  15445. } catch (err) {
  15446. showToast('Error', err.message, 'error');
  15447. }
  15448. }
  15449. // =============================================================================
  15450. // BACKUP & RESTORE MANAGER
  15451. // =============================================================================
  15452. state.selectedBackupFile = null;
  15453. state.inspectedBackupManifest = null;
  15454. state.pendingRestoreTarget = null;
  15455. state.backupsList = [];
  15456. async function exportBackupDownload() {
  15457. const btn = document.getElementById('btn-export-backup');
  15458. const commentInput = document.getElementById('backup-export-comment');
  15459. const comment = (commentInput?.value || '').trim();
  15460. const originalHtml = btn ? btn.innerHTML : '';
  15461. if (btn) {
  15462. btn.disabled = true;
  15463. 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...`;
  15464. }
  15465. try {
  15466. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15467. if (!res.ok) {
  15468. const err = await res.json().catch(() => ({}));
  15469. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15470. return;
  15471. }
  15472. const blob = await res.blob();
  15473. const disposition = res.headers.get('Content-Disposition') || '';
  15474. let filename = 'debtik-backup.zip';
  15475. const match = disposition.match(/filename="?([^";]+)"?/);
  15476. if (match && match[1]) {
  15477. filename = match[1];
  15478. }
  15479. const blobUrl = window.URL.createObjectURL(blob);
  15480. const a = document.createElement('a');
  15481. a.href = blobUrl;
  15482. a.download = filename;
  15483. document.body.appendChild(a);
  15484. a.click();
  15485. setTimeout(() => {
  15486. window.URL.revokeObjectURL(blobUrl);
  15487. a.remove();
  15488. }, 1000);
  15489. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15490. } catch (err) {
  15491. showToast('Export Error', err.message || 'Network error during download', 'error');
  15492. } finally {
  15493. if (btn) {
  15494. btn.disabled = false;
  15495. btn.innerHTML = originalHtml;
  15496. }
  15497. }
  15498. }
  15499. async function onBackupFileSelected(e) {
  15500. const file = e.target.files?.[0];
  15501. if (!file) return;
  15502. const label = document.getElementById('backup-file-label');
  15503. if (label) {
  15504. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15505. }
  15506. await inspectBackupFile(file);
  15507. }
  15508. async function inspectBackupFile(file) {
  15509. const preview = document.getElementById('backup-inspect-preview');
  15510. const restoreBtn = document.getElementById('btn-restore-backup');
  15511. const formData = new FormData();
  15512. formData.append('backup', file);
  15513. try {
  15514. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15515. method: 'POST',
  15516. body: formData
  15517. });
  15518. const data = await res.json();
  15519. if (!res.ok || !data.success || !data.manifest) {
  15520. if (preview) preview.classList.add('hidden');
  15521. if (restoreBtn) restoreBtn.disabled = true;
  15522. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15523. return;
  15524. }
  15525. const mf = data.manifest;
  15526. state.selectedBackupFile = file;
  15527. state.inspectedBackupManifest = mf;
  15528. const vEl = document.getElementById('backup-inspect-version');
  15529. const hEl = document.getElementById('backup-inspect-hostname');
  15530. const fEl = document.getElementById('backup-inspect-files');
  15531. const dEl = document.getElementById('backup-inspect-date');
  15532. const cEl = document.getElementById('backup-inspect-comment');
  15533. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15534. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15535. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15536. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15537. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15538. if (preview) preview.classList.remove('hidden');
  15539. if (restoreBtn) restoreBtn.disabled = false;
  15540. } catch (err) {
  15541. if (preview) preview.classList.add('hidden');
  15542. if (restoreBtn) restoreBtn.disabled = true;
  15543. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15544. }
  15545. }
  15546. function confirmRestoreBackup(localFilename = null) {
  15547. const modal = document.getElementById('modal-restore-confirm');
  15548. const details = document.getElementById('modal-restore-details');
  15549. const progress = document.getElementById('modal-restore-progress');
  15550. const cancelBtn = document.getElementById('btn-cancel-restore');
  15551. const execBtn = document.getElementById('btn-execute-restore');
  15552. if (progress) progress.classList.add('hidden');
  15553. if (cancelBtn) cancelBtn.disabled = false;
  15554. if (execBtn) {
  15555. execBtn.disabled = false;
  15556. execBtn.innerText = 'Yes, Restore & Reload';
  15557. }
  15558. if (localFilename) {
  15559. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15560. if (details) {
  15561. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15562. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15563. }
  15564. } else {
  15565. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15566. showToast('Error', 'Please select a valid backup archive first', 'error');
  15567. return;
  15568. }
  15569. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15570. const mf = state.inspectedBackupManifest;
  15571. if (details) {
  15572. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15573. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15574. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15575. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15576. }
  15577. }
  15578. if (modal) modal.classList.remove('hidden');
  15579. }
  15580. function closeRestoreModal() {
  15581. const modal = document.getElementById('modal-restore-confirm');
  15582. if (modal) modal.classList.add('hidden');
  15583. }
  15584. async function executeRestoreBackup() {
  15585. const target = state.pendingRestoreTarget;
  15586. if (!target) return;
  15587. const progress = document.getElementById('modal-restore-progress');
  15588. const progressText = document.getElementById('modal-restore-progress-text');
  15589. const cancelBtn = document.getElementById('btn-cancel-restore');
  15590. const execBtn = document.getElementById('btn-execute-restore');
  15591. if (cancelBtn) cancelBtn.disabled = true;
  15592. if (execBtn) execBtn.disabled = true;
  15593. if (progress) progress.classList.remove('hidden');
  15594. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15595. try {
  15596. let res;
  15597. if (target.type === 'file') {
  15598. const formData = new FormData();
  15599. formData.append('backup', target.file);
  15600. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15601. method: 'POST',
  15602. body: formData
  15603. });
  15604. } else {
  15605. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15606. method: 'POST'
  15607. });
  15608. }
  15609. const data = await res.json();
  15610. if (!res.ok || !data.success) {
  15611. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15612. if (cancelBtn) cancelBtn.disabled = false;
  15613. if (execBtn) execBtn.disabled = false;
  15614. if (progress) progress.classList.add('hidden');
  15615. return;
  15616. }
  15617. if (progressText) {
  15618. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15619. }
  15620. pollAfterRestoreReconnect();
  15621. } catch (err) {
  15622. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15623. if (cancelBtn) cancelBtn.disabled = false;
  15624. if (execBtn) execBtn.disabled = false;
  15625. if (progress) progress.classList.add('hidden');
  15626. }
  15627. }
  15628. function pollAfterRestoreReconnect() {
  15629. let attempts = 0;
  15630. const maxAttempts = 25;
  15631. const timer = setInterval(async () => {
  15632. attempts++;
  15633. try {
  15634. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15635. if (res.ok) {
  15636. clearInterval(timer);
  15637. closeRestoreModal();
  15638. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15639. setTimeout(() => {
  15640. window.location.reload();
  15641. }, 1200);
  15642. }
  15643. } catch (_) {
  15644. // Still restarting, retry
  15645. }
  15646. if (attempts >= maxAttempts) {
  15647. clearInterval(timer);
  15648. closeRestoreModal();
  15649. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15650. }
  15651. }, 1500);
  15652. }
  15653. async function loadBackupList() {
  15654. const tbody = document.getElementById('backups-table-tbody');
  15655. const empty = document.getElementById('backups-empty-state');
  15656. if (!tbody) return;
  15657. try {
  15658. const res = await fetch(`${API_BASE}/system/backups`);
  15659. if (!res.ok) return;
  15660. const list = await res.json();
  15661. state.backupsList = list || [];
  15662. renderBackupsTable(state.backupsList);
  15663. } catch (err) {
  15664. console.error('Failed to load backup list:', err);
  15665. }
  15666. }
  15667. function renderBackupsTable(backups) {
  15668. const tbody = document.getElementById('backups-table-tbody');
  15669. const empty = document.getElementById('backups-empty-state');
  15670. if (!tbody) return;
  15671. if (!backups || backups.length === 0) {
  15672. tbody.innerHTML = '';
  15673. if (empty) empty.classList.remove('hidden');
  15674. return;
  15675. }
  15676. if (empty) empty.classList.add('hidden');
  15677. tbody.innerHTML = backups.map(bk => {
  15678. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15679. const badge = isAuto
  15680. ? `<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>`
  15681. : `<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>`;
  15682. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15683. return `<tr class="hover:bg-slate-800/40 transition">
  15684. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15685. ${badge}
  15686. <span>${escapeHtml(bk.filename)}</span>
  15687. </td>
  15688. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15689. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15690. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15691. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15692. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15693. <td class="py-3 px-4 text-right space-x-2">
  15694. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15695. 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">
  15696. Download
  15697. </button>
  15698. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15699. 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">
  15700. Restore
  15701. </button>
  15702. </td>
  15703. </tr>`;
  15704. }).join('');
  15705. }
  15706. async function downloadLocalBackup(filename) {
  15707. try {
  15708. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15709. if (!res.ok) {
  15710. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15711. return;
  15712. }
  15713. const blob = await res.blob();
  15714. const blobUrl = window.URL.createObjectURL(blob);
  15715. const a = document.createElement('a');
  15716. a.href = blobUrl;
  15717. a.download = filename;
  15718. document.body.appendChild(a);
  15719. a.click();
  15720. setTimeout(() => {
  15721. window.URL.revokeObjectURL(blobUrl);
  15722. a.remove();
  15723. }, 1000);
  15724. } catch (err) {
  15725. showToast('Download Error', err.message, 'error');
  15726. }
  15727. }
  15728. // =============================================================================
  15729. // AUTHENTICATION & USER MANAGER
  15730. // =============================================================================
  15731. async function checkAuthStatus() {
  15732. try {
  15733. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15734. headers: {
  15735. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15736. }
  15737. });
  15738. if (res.ok) {
  15739. const user = await res.json();
  15740. state.currentUser = user;
  15741. updateUserProfileHeader(user);
  15742. hideLoginScreen();
  15743. state.isPolling = true;
  15744. fetchData();
  15745. initLiveTrafficStream();
  15746. return true;
  15747. } else {
  15748. showLoginScreen(false);
  15749. return false;
  15750. }
  15751. } catch (err) {
  15752. showLoginScreen(false);
  15753. return false;
  15754. }
  15755. }
  15756. function showLoginScreen(isExpired = false) {
  15757. const el = document.getElementById('login-screen');
  15758. if (el) el.classList.remove('hidden');
  15759. const errEl = document.getElementById('login-error');
  15760. const errTxt = document.getElementById('login-error-text');
  15761. if (isExpired && errEl && errTxt) {
  15762. errTxt.innerText = 'Session expired. Please sign in again.';
  15763. errEl.classList.remove('hidden');
  15764. } else if (errEl) {
  15765. errEl.classList.add('hidden');
  15766. }
  15767. const pwInput = document.getElementById('login-password');
  15768. if (pwInput) pwInput.value = '';
  15769. const userInput = document.getElementById('login-username');
  15770. if (userInput && !userInput.value) userInput.focus();
  15771. else if (pwInput) pwInput.focus();
  15772. }
  15773. function hideLoginScreen() {
  15774. const el = document.getElementById('login-screen');
  15775. if (el) el.classList.add('hidden');
  15776. const errEl = document.getElementById('login-error');
  15777. if (errEl) errEl.classList.add('hidden');
  15778. }
  15779. async function handleLoginSubmit(event) {
  15780. event.preventDefault();
  15781. const username = (document.getElementById('login-username')?.value || '').trim();
  15782. const password = document.getElementById('login-password')?.value || '';
  15783. const errEl = document.getElementById('login-error');
  15784. const errTxt = document.getElementById('login-error-text');
  15785. const btn = document.getElementById('login-submit-btn');
  15786. const btnText = document.getElementById('login-btn-text');
  15787. const spinner = document.getElementById('login-btn-spinner');
  15788. if (!username || !password) {
  15789. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15790. if (errEl) errEl.classList.remove('hidden');
  15791. return;
  15792. }
  15793. if (errEl) errEl.classList.add('hidden');
  15794. if (btn) btn.disabled = true;
  15795. if (btnText) btnText.innerText = 'Authenticating...';
  15796. if (spinner) spinner.classList.remove('hidden');
  15797. try {
  15798. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15799. method: 'POST',
  15800. headers: { 'Content-Type': 'application/json' },
  15801. body: JSON.stringify({ username, password })
  15802. });
  15803. const data = await res.json();
  15804. if (res.ok && data.success) {
  15805. localStorage.setItem('debtik_token', data.token);
  15806. state.currentUser = data.user;
  15807. updateUserProfileHeader(data.user);
  15808. hideLoginScreen();
  15809. state.isPolling = true;
  15810. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15811. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15812. navigate(hash);
  15813. fetchData();
  15814. initLiveTrafficStream();
  15815. // Ensure background telemetry polling is active
  15816. if (!window._telemetryInterval) {
  15817. window._telemetryInterval = setInterval(() => {
  15818. if (state.isPolling && state.currentUser && !document.hidden) {
  15819. fetchData(false);
  15820. }
  15821. }, 5000);
  15822. }
  15823. } else {
  15824. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15825. if (errEl) errEl.classList.remove('hidden');
  15826. }
  15827. } catch (err) {
  15828. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15829. if (errEl) errEl.classList.remove('hidden');
  15830. } finally {
  15831. if (btn) btn.disabled = false;
  15832. if (btnText) btnText.innerText = 'Sign In to Controller';
  15833. if (spinner) spinner.classList.add('hidden');
  15834. }
  15835. }
  15836. async function handleLogoutClick() {
  15837. try {
  15838. await originalFetch(`${API_BASE}/auth/logout`, {
  15839. method: 'POST',
  15840. headers: {
  15841. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15842. }
  15843. });
  15844. } catch (e) {}
  15845. stopSessionPolling();
  15846. localStorage.removeItem('debtik_token');
  15847. state.currentUser = null;
  15848. state.isPolling = false;
  15849. if (window._telemetryInterval) {
  15850. clearInterval(window._telemetryInterval);
  15851. window._telemetryInterval = null;
  15852. }
  15853. if (trafficEventSource) {
  15854. trafficEventSource.close();
  15855. trafficEventSource = null;
  15856. }
  15857. if (trafficPollFallback) {
  15858. clearInterval(trafficPollFallback);
  15859. trafficPollFallback = null;
  15860. }
  15861. showLoginScreen(false);
  15862. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15863. }
  15864. function togglePasswordVisibility(id) {
  15865. const input = document.getElementById(id);
  15866. if (!input) return;
  15867. input.type = input.type === 'password' ? 'text' : 'password';
  15868. }
  15869. function toggleUserMenu() {
  15870. const menu = document.getElementById('user-menu-dropdown');
  15871. if (menu) menu.classList.toggle('hidden');
  15872. }
  15873. function closeUserMenu() {
  15874. const menu = document.getElementById('user-menu-dropdown');
  15875. if (menu) menu.classList.add('hidden');
  15876. }
  15877. // Close user menu on outside click
  15878. document.addEventListener('click', (e) => {
  15879. const menu = document.getElementById('user-menu-dropdown');
  15880. if (!menu || menu.classList.contains('hidden')) return;
  15881. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15882. menu.classList.add('hidden');
  15883. }
  15884. });
  15885. function updateUserProfileHeader(user) {
  15886. if (!user) return;
  15887. const navName = document.getElementById('nav-user-name');
  15888. if (navName) navName.innerText = user.username;
  15889. const dropName = document.getElementById('dropdown-user-name');
  15890. if (dropName) dropName.innerText = user.username;
  15891. const navRole = document.getElementById('nav-user-role');
  15892. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15893. const navAvatar = document.getElementById('nav-user-avatar');
  15894. if (navAvatar) {
  15895. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15896. navAvatar.innerText = initials;
  15897. }
  15898. const statCurUser = document.getElementById('stat-current-user');
  15899. if (statCurUser) statCurUser.innerText = user.username;
  15900. const statCurRole = document.getElementById('stat-current-role');
  15901. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15902. // Role permissions UI visibility: hide user management for non-admins
  15903. const isFullAdmin = user.role === 'full';
  15904. const navUsers = document.getElementById('nav-users');
  15905. if (navUsers) {
  15906. if (isFullAdmin) navUsers.classList.remove('hidden');
  15907. else navUsers.classList.add('hidden');
  15908. }
  15909. const dropdownUsers = document.getElementById('dropdown-item-users');
  15910. if (dropdownUsers) {
  15911. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15912. else dropdownUsers.classList.add('hidden');
  15913. }
  15914. }
  15915. // ================= User Management CRUD =================
  15916. async function loadUsers(isManual = false) {
  15917. try {
  15918. const res = await fetch(`${API_BASE}/users`);
  15919. if (res.status === 403) {
  15920. const tbody = document.getElementById('users-table-tbody');
  15921. if (tbody) {
  15922. tbody.innerHTML = `
  15923. <tr>
  15924. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15925. <div class="inline-flex items-center gap-2">
  15926. <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>
  15927. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15928. </div>
  15929. </td>
  15930. </tr>
  15931. `;
  15932. }
  15933. return;
  15934. }
  15935. if (res.ok) {
  15936. state.users = await res.json();
  15937. renderUsersTable();
  15938. const totalUsers = document.getElementById('stat-total-users');
  15939. if (totalUsers) totalUsers.innerText = state.users.length;
  15940. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15941. const adminUsers = document.getElementById('stat-admin-users');
  15942. if (adminUsers) adminUsers.innerText = adminCount;
  15943. const badgeCount = document.getElementById('badge-users-count');
  15944. if (badgeCount) badgeCount.innerText = state.users.length;
  15945. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15946. }
  15947. } catch (err) {
  15948. console.error('Failed to load users:', err);
  15949. }
  15950. }
  15951. function renderUsersTable() {
  15952. const tbody = document.getElementById('users-table-tbody');
  15953. const emptyState = document.getElementById('users-empty-state');
  15954. if (!tbody) return;
  15955. tbody.innerHTML = '';
  15956. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15957. const filtered = (state.users || []).filter(u => {
  15958. if (!query) return true;
  15959. return u.username.toLowerCase().includes(query) ||
  15960. (u.role || '').toLowerCase().includes(query) ||
  15961. (u.comment || '').toLowerCase().includes(query);
  15962. });
  15963. if (filtered.length === 0) {
  15964. if (emptyState) emptyState.classList.remove('hidden');
  15965. return;
  15966. }
  15967. if (emptyState) emptyState.classList.add('hidden');
  15968. const currentAuthUser = state.currentUser?.username || '';
  15969. filtered.forEach(u => {
  15970. const isSelf = u.username === currentAuthUser;
  15971. const isFull = u.role === 'full';
  15972. const isWrite = u.role === 'write';
  15973. 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>`;
  15974. if (isFull) {
  15975. 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>`;
  15976. } else if (isWrite) {
  15977. 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>`;
  15978. }
  15979. const statusBadge = u.disabled
  15980. ? `<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>`
  15981. : `<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>`;
  15982. let lastLoginText = 'Never';
  15983. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15984. const dt = new Date(u.last_login_at);
  15985. lastLoginText = dt.toLocaleString();
  15986. }
  15987. const initials = u.username.slice(0, 2).toUpperCase();
  15988. const tr = document.createElement('tr');
  15989. tr.className = 'hover:bg-slate-800/40 transition group';
  15990. tr.innerHTML = `
  15991. <td class="py-3 px-4">
  15992. <div class="flex items-center gap-3">
  15993. <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">
  15994. ${initials}
  15995. </div>
  15996. <div>
  15997. <div class="font-bold text-white text-xs flex items-center gap-2">
  15998. <span>${escapeHtml(u.username)}</span>
  15999. ${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>' : ''}
  16000. </div>
  16001. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  16002. </div>
  16003. </div>
  16004. </td>
  16005. <td class="py-3 px-4 font-sans">
  16006. ${roleBadge}
  16007. </td>
  16008. <td class="py-3 px-4 font-sans">
  16009. ${statusBadge}
  16010. </td>
  16011. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  16012. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  16013. </td>
  16014. <td class="py-3 px-4 text-slate-400 text-xs">
  16015. ${lastLoginText}
  16016. </td>
  16017. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  16018. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  16019. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  16020. <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>
  16021. </button>
  16022. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  16023. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  16024. <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>
  16025. </button>
  16026. ${!isSelf ? `
  16027. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  16028. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  16029. <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>
  16030. </button>
  16031. ` : ''}
  16032. </td>
  16033. `;
  16034. tbody.appendChild(tr);
  16035. });
  16036. }
  16037. function openAddUserModal() {
  16038. document.getElementById('user-add-username').value = '';
  16039. document.getElementById('user-add-password').value = '';
  16040. document.getElementById('user-add-confirm').value = '';
  16041. document.getElementById('user-add-role').value = 'full';
  16042. document.getElementById('user-add-comment').value = '';
  16043. document.getElementById('modal-add-user')?.classList.remove('hidden');
  16044. document.getElementById('user-add-username')?.focus();
  16045. }
  16046. function closeAddUserModal() {
  16047. document.getElementById('modal-add-user')?.classList.add('hidden');
  16048. }
  16049. async function submitAddUser(event) {
  16050. event.preventDefault();
  16051. const username = (document.getElementById('user-add-username')?.value || '').trim();
  16052. const password = document.getElementById('user-add-password')?.value || '';
  16053. const confirm = document.getElementById('user-add-confirm')?.value || '';
  16054. const role = document.getElementById('user-add-role')?.value || 'full';
  16055. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  16056. if (password !== confirm) {
  16057. showToast('Validation Error', 'Passwords do not match', 'warning');
  16058. return;
  16059. }
  16060. if (password.length < 4) {
  16061. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16062. return;
  16063. }
  16064. try {
  16065. const res = await fetch(`${API_BASE}/users`, {
  16066. method: 'POST',
  16067. headers: { 'Content-Type': 'application/json' },
  16068. body: JSON.stringify({ username, password, role, comment })
  16069. });
  16070. const data = await res.json();
  16071. if (res.ok) {
  16072. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  16073. closeAddUserModal();
  16074. loadUsers(false);
  16075. } else {
  16076. showToast('Error', data.message || 'Failed to create user', 'error');
  16077. }
  16078. } catch (err) {
  16079. showToast('Error', err.message, 'error');
  16080. }
  16081. }
  16082. function openEditUserModal(username) {
  16083. const user = (state.users || []).find(u => u.username === username);
  16084. if (!user) return;
  16085. document.getElementById('user-edit-username').value = user.username;
  16086. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  16087. document.getElementById('user-edit-role').value = user.role || 'read';
  16088. document.getElementById('user-edit-comment').value = user.comment || '';
  16089. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  16090. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  16091. }
  16092. function closeEditUserModal() {
  16093. document.getElementById('modal-edit-user')?.classList.add('hidden');
  16094. }
  16095. async function submitEditUser(event) {
  16096. event.preventDefault();
  16097. const username = document.getElementById('user-edit-username')?.value;
  16098. const role = document.getElementById('user-edit-role')?.value || 'read';
  16099. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  16100. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  16101. try {
  16102. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16103. method: 'PUT',
  16104. headers: { 'Content-Type': 'application/json' },
  16105. body: JSON.stringify({ role, comment, disabled })
  16106. });
  16107. const data = await res.json();
  16108. if (res.ok) {
  16109. showToast('User Updated', `Updated settings for ${username}`, 'success');
  16110. closeEditUserModal();
  16111. loadUsers(false);
  16112. // If updated own role/disabled status, refresh self profile
  16113. if (username === state.currentUser?.username) {
  16114. checkAuthStatus();
  16115. }
  16116. } else {
  16117. showToast('Error', data.message || 'Failed to update user', 'error');
  16118. }
  16119. } catch (err) {
  16120. showToast('Error', err.message, 'error');
  16121. }
  16122. }
  16123. function openAdminResetPasswordModal(username) {
  16124. document.getElementById('admin-reset-username').value = username;
  16125. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  16126. document.getElementById('admin-reset-new-pw').value = '';
  16127. document.getElementById('admin-reset-confirm-pw').value = '';
  16128. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  16129. document.getElementById('admin-reset-new-pw')?.focus();
  16130. }
  16131. function closeAdminResetPasswordModal() {
  16132. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  16133. }
  16134. async function submitAdminResetPassword(event) {
  16135. event.preventDefault();
  16136. const username = document.getElementById('admin-reset-username')?.value;
  16137. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  16138. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  16139. if (newPassword !== confirm) {
  16140. showToast('Validation Error', 'Passwords do not match', 'warning');
  16141. return;
  16142. }
  16143. if (newPassword.length < 4) {
  16144. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16145. return;
  16146. }
  16147. try {
  16148. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  16149. method: 'POST',
  16150. headers: { 'Content-Type': 'application/json' },
  16151. body: JSON.stringify({ new_password: newPassword })
  16152. });
  16153. const data = await res.json();
  16154. if (res.ok) {
  16155. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  16156. closeAdminResetPasswordModal();
  16157. } else {
  16158. showToast('Error', data.message || 'Failed to reset password', 'error');
  16159. }
  16160. } catch (err) {
  16161. showToast('Error', err.message, 'error');
  16162. }
  16163. }
  16164. async function deleteUser(username) {
  16165. if (username === state.currentUser?.username) {
  16166. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  16167. return;
  16168. }
  16169. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  16170. return;
  16171. }
  16172. try {
  16173. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  16174. method: 'DELETE'
  16175. });
  16176. const data = await res.json();
  16177. if (res.ok) {
  16178. showToast('User Deleted', `User ${username} has been removed`, 'success');
  16179. loadUsers(false);
  16180. } else {
  16181. showToast('Error', data.message || 'Failed to delete user', 'error');
  16182. }
  16183. } catch (err) {
  16184. showToast('Error', err.message, 'error');
  16185. }
  16186. }
  16187. function openSelfPasswordModal() {
  16188. document.getElementById('self-current-password').value = '';
  16189. document.getElementById('self-new-password').value = '';
  16190. document.getElementById('self-confirm-password').value = '';
  16191. document.getElementById('modal-self-password')?.classList.remove('hidden');
  16192. document.getElementById('self-current-password')?.focus();
  16193. }
  16194. function closeSelfPasswordModal() {
  16195. document.getElementById('modal-self-password')?.classList.add('hidden');
  16196. }
  16197. async function submitSelfPassword(event) {
  16198. event.preventDefault();
  16199. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16200. const newPassword = document.getElementById('self-new-password')?.value || '';
  16201. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16202. if (newPassword !== confirm) {
  16203. showToast('Validation Error', 'New passwords do not match', 'warning');
  16204. return;
  16205. }
  16206. if (newPassword.length < 4) {
  16207. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16208. return;
  16209. }
  16210. try {
  16211. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16212. method: 'POST',
  16213. headers: { 'Content-Type': 'application/json' },
  16214. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16215. });
  16216. const data = await res.json();
  16217. if (res.ok) {
  16218. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16219. closeSelfPasswordModal();
  16220. } else {
  16221. showToast('Error', data.message || 'Failed to change password', 'error');
  16222. }
  16223. } catch (err) {
  16224. showToast('Error', err.message, 'error');
  16225. }
  16226. }
  16227. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16228. state.services = [];
  16229. async function loadServices(manual = false) {
  16230. try {
  16231. const res = await fetch(`${API_BASE}/system/services`);
  16232. if (!res.ok) throw new Error('Failed to load services');
  16233. const data = await res.json();
  16234. state.services = data || [];
  16235. renderServicesTable();
  16236. updateCertificatesBadges();
  16237. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16238. } catch (err) {
  16239. if (manual) showToast('Error', err.message, 'error');
  16240. }
  16241. }
  16242. function renderServicesTable() {
  16243. const tbody = document.getElementById('services-table-body');
  16244. if (!tbody) return;
  16245. if (!state.services || state.services.length === 0) {
  16246. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16247. return;
  16248. }
  16249. tbody.innerHTML = state.services.map(s => {
  16250. const isOff = s.disabled;
  16251. const statusBadge = isOff
  16252. ? '<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>'
  16253. : '<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>';
  16254. const toggleBtn = isOff
  16255. ? `<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>`
  16256. : `<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>`;
  16257. let certBadge = '';
  16258. if (s.name === 'www-ssl') {
  16259. if (s.certificate) {
  16260. 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>`;
  16261. } else {
  16262. 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>`;
  16263. }
  16264. }
  16265. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16266. return `
  16267. <tr class="hover:bg-slate-800/40 transition">
  16268. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16269. <td class="py-3 px-4">
  16270. <div class="flex items-center gap-2">
  16271. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16272. <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">
  16273. <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>
  16274. </button>
  16275. </div>
  16276. </td>
  16277. <td class="py-3 px-4">${statusBadge}</td>
  16278. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16279. <td class="py-3 px-4 text-right">
  16280. <div class="flex items-center justify-end gap-2">
  16281. <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">
  16282. <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>
  16283. <span>Edit</span>
  16284. </button>
  16285. ${toggleBtn}
  16286. </div>
  16287. </td>
  16288. </tr>
  16289. `;
  16290. }).join('');
  16291. }
  16292. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16293. document.getElementById('modal-service-name').value = serviceName;
  16294. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16295. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16296. document.getElementById('modal-service-port').value = currentPort;
  16297. const hintEl = document.getElementById('modal-service-port-hint');
  16298. const warnEl = document.getElementById('modal-service-warning');
  16299. const certGroup = document.getElementById('modal-service-cert-group');
  16300. const certSelect = document.getElementById('modal-service-cert-select');
  16301. if (serviceName === 'www') {
  16302. hintEl.textContent = 'Default HTTP web port: 80';
  16303. warnEl.classList.remove('hidden');
  16304. certGroup.classList.add('hidden');
  16305. } else if (serviceName === 'www-ssl') {
  16306. hintEl.textContent = 'Default HTTPS web port: 443';
  16307. warnEl.classList.remove('hidden');
  16308. certGroup.classList.remove('hidden');
  16309. const populateCertOptions = (certs) => {
  16310. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16311. (certs || []).forEach(c => {
  16312. const opt = document.createElement('option');
  16313. opt.value = c.name;
  16314. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16315. if (c.name === currentCert) opt.selected = true;
  16316. certSelect.appendChild(opt);
  16317. });
  16318. };
  16319. if (state.certificates && state.certificates.length > 0) {
  16320. populateCertOptions(state.certificates);
  16321. } else {
  16322. loadCertificates(false).then(() => {
  16323. populateCertOptions(state.certificates);
  16324. });
  16325. }
  16326. } else if (serviceName === 'telnet') {
  16327. hintEl.textContent = 'Default Telnet console port: 8282';
  16328. warnEl.classList.add('hidden');
  16329. certGroup.classList.add('hidden');
  16330. } else if (serviceName === 'ssh') {
  16331. hintEl.textContent = 'Default SSH port: 2222';
  16332. warnEl.classList.add('hidden');
  16333. certGroup.classList.add('hidden');
  16334. } else {
  16335. hintEl.textContent = '';
  16336. warnEl.classList.add('hidden');
  16337. certGroup.classList.add('hidden');
  16338. }
  16339. const modal = document.getElementById('modal-service-edit');
  16340. modal.classList.remove('hidden');
  16341. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16342. }
  16343. function closeEditServiceModal() {
  16344. const modal = document.getElementById('modal-service-edit');
  16345. if (modal) modal.classList.add('hidden');
  16346. }
  16347. async function submitSaveServicePort(event) {
  16348. event.preventDefault();
  16349. const name = document.getElementById('modal-service-name').value;
  16350. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16351. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16352. if (isNaN(port) || port < 1 || port > 65535) {
  16353. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16354. return;
  16355. }
  16356. const certSelect = document.getElementById('modal-service-cert-select');
  16357. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16358. try {
  16359. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16360. method: 'POST',
  16361. headers: { 'Content-Type': 'application/json' },
  16362. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16363. });
  16364. if (!res.ok) {
  16365. const errData = await res.json();
  16366. throw new Error(errData.message || 'Failed to update service settings');
  16367. }
  16368. closeEditServiceModal();
  16369. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16370. await loadServices();
  16371. } catch (err) {
  16372. showToast('Error', err.message, 'error');
  16373. }
  16374. }
  16375. async function toggleServiceState(serviceName, newDisabled) {
  16376. if (serviceName === 'www' && newDisabled) {
  16377. 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?")) {
  16378. return;
  16379. }
  16380. }
  16381. if (serviceName === 'www-ssl' && !newDisabled) {
  16382. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16383. if (!sslSvc || !sslSvc.certificate) {
  16384. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16385. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16386. return;
  16387. }
  16388. }
  16389. try {
  16390. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16391. method: 'POST',
  16392. headers: { 'Content-Type': 'application/json' },
  16393. body: JSON.stringify({ disabled: newDisabled })
  16394. });
  16395. if (!res.ok) {
  16396. const errData = await res.json();
  16397. throw new Error(errData.message || 'Failed to update service');
  16398. }
  16399. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16400. await loadServices();
  16401. } catch (err) {
  16402. showToast('Error', err.message, 'error');
  16403. }
  16404. }
  16405. // ==================== SYSTEM LOGS (/log) ====================
  16406. state.logs = [];
  16407. let logsTimer = null;
  16408. async function loadLogs(manual = false) {
  16409. const limitEl = document.getElementById('logs-limit-select');
  16410. const limit = limitEl ? limitEl.value : '100';
  16411. try {
  16412. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16413. if (!res.ok) throw new Error('Failed to load logs');
  16414. const data = await res.json();
  16415. state.logs = data.logs || [];
  16416. renderLogsTable();
  16417. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16418. } catch (err) {
  16419. if (manual) showToast('Error', err.message, 'error');
  16420. }
  16421. // Setup auto-refresh if enabled and on logs tab
  16422. if (!logsTimer && state.currentUser) {
  16423. logsTimer = setInterval(() => {
  16424. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16425. const auto = document.getElementById('logs-auto-refresh');
  16426. if (auto && auto.checked) {
  16427. loadLogs(false);
  16428. }
  16429. }
  16430. }, 3000);
  16431. }
  16432. }
  16433. function renderLogsTable() {
  16434. const tbody = document.getElementById('logs-table-body');
  16435. if (!tbody) return;
  16436. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16437. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16438. const filtered = state.logs.filter(entry => {
  16439. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16440. return false;
  16441. }
  16442. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16443. return false;
  16444. }
  16445. return true;
  16446. });
  16447. if (filtered.length === 0) {
  16448. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16449. return;
  16450. }
  16451. tbody.innerHTML = filtered.map(l => {
  16452. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16453. const topLower = l.topics.toLowerCase();
  16454. if (topLower.includes('auth')) {
  16455. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16456. } else if (topLower.includes('dhcp')) {
  16457. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16458. } else if (topLower.includes('route')) {
  16459. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16460. } else if (topLower.includes('firewall')) {
  16461. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16462. } else if (topLower.includes('error')) {
  16463. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16464. } else if (topLower.includes('system')) {
  16465. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16466. }
  16467. const d = new Date(l.time);
  16468. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16469. return `
  16470. <tr class="hover:bg-slate-800/40 transition">
  16471. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16472. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16473. <td class="py-2 px-3 whitespace-nowrap">
  16474. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16475. </td>
  16476. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16477. </tr>
  16478. `;
  16479. }).join('');
  16480. }
  16481. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16482. state.certificates = [];
  16483. async function loadCertificates(manual = false) {
  16484. try {
  16485. const res = await fetch(`${API_BASE}/certificates`);
  16486. if (!res.ok) throw new Error('Failed to load certificates');
  16487. state.certificates = await res.json() || [];
  16488. updateCertificatesBadges();
  16489. renderCertificatesTable();
  16490. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16491. } catch (err) {
  16492. if (manual) showToast('Error', err.message, 'error');
  16493. }
  16494. }
  16495. function updateCertificatesBadges() {
  16496. const total = (state.certificates || []).length;
  16497. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16498. const bCount = document.getElementById('badge-certs-count');
  16499. if (bCount) bCount.innerText = total;
  16500. const kpiTotal = document.getElementById('kpi-certs-total');
  16501. if (kpiTotal) kpiTotal.innerText = total;
  16502. const kpiCA = document.getElementById('kpi-certs-ca');
  16503. if (kpiCA) kpiCA.innerText = caCount;
  16504. const kpiHttps = document.getElementById('kpi-https-status');
  16505. if (kpiHttps) {
  16506. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16507. if (sslSvc) {
  16508. if (!sslSvc.disabled) {
  16509. 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>`;
  16510. } else {
  16511. 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>`;
  16512. }
  16513. }
  16514. }
  16515. }
  16516. function renderCertificatesTable() {
  16517. const tbody = document.getElementById('certs-table-body');
  16518. if (!tbody) return;
  16519. if (!state.certificates || state.certificates.length === 0) {
  16520. 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>';
  16521. return;
  16522. }
  16523. tbody.innerHTML = state.certificates.map(c => {
  16524. let typeBadge = '';
  16525. if (c.is_ca) {
  16526. 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>';
  16527. } else if (c.type === 'acme') {
  16528. 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>';
  16529. } else if (c.issuer && c.issuer !== c.common_name) {
  16530. 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>';
  16531. } else {
  16532. 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>';
  16533. }
  16534. const sansHtml = (c.sans && c.sans.length > 0)
  16535. ? 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('')
  16536. : '<span class="text-slate-500">-</span>';
  16537. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16538. let validStr = '-';
  16539. let validBadge = '';
  16540. if (validTo && !isNaN(validTo.getTime())) {
  16541. const now = new Date();
  16542. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16543. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16544. if (daysLeft < 0) {
  16545. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16546. } else if (daysLeft < 30) {
  16547. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16548. } else {
  16549. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16550. }
  16551. }
  16552. return `
  16553. <tr class="hover:bg-slate-800/40 transition">
  16554. <td class="py-3 px-4">${typeBadge}</td>
  16555. <td class="py-3 px-4">
  16556. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16557. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16558. </td>
  16559. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16560. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16561. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16562. <span>${validStr}</span> ${validBadge}
  16563. ${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>` : ''}
  16564. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16565. </td>
  16566. <td class="py-3 px-4 text-right whitespace-nowrap">
  16567. <div class="flex items-center justify-end gap-1.5">
  16568. <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">
  16569. <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>
  16570. <span>View</span>
  16571. </button>
  16572. <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">
  16573. <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>
  16574. </button>
  16575. </div>
  16576. </td>
  16577. </tr>
  16578. `;
  16579. }).join('');
  16580. }
  16581. // Create CA
  16582. function openCreateCAModal() {
  16583. document.getElementById('form-create-ca').reset();
  16584. document.getElementById('ca-days').value = '3650';
  16585. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16586. document.getElementById('ca-country').value = 'GR';
  16587. document.getElementById('ca-key-type').value = 'RSA-2048';
  16588. document.getElementById('modal-create-ca').classList.remove('hidden');
  16589. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16590. }
  16591. function closeCreateCAModal() {
  16592. document.getElementById('modal-create-ca').classList.add('hidden');
  16593. }
  16594. async function submitCreateCA(event) {
  16595. event.preventDefault();
  16596. const payload = {
  16597. name: document.getElementById('ca-name').value.trim(),
  16598. common_name: document.getElementById('ca-cn').value.trim(),
  16599. organization: document.getElementById('ca-org').value.trim(),
  16600. country: document.getElementById('ca-country').value.trim(),
  16601. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16602. key_type: document.getElementById('ca-key-type').value
  16603. };
  16604. try {
  16605. const res = await fetch(`${API_BASE}/certificates/ca`, {
  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 create CA');
  16613. }
  16614. closeCreateCAModal();
  16615. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16616. await loadCertificates();
  16617. } catch (err) {
  16618. showToast('Error', err.message, 'error');
  16619. }
  16620. }
  16621. // Create Cert
  16622. function openCreateCertModal() {
  16623. document.getElementById('form-create-cert').reset();
  16624. document.getElementById('cert-days').value = '730';
  16625. document.getElementById('cert-key-type').value = 'RSA-2048';
  16626. const caSelect = document.getElementById('cert-ca-select');
  16627. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16628. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16629. const opt = document.createElement('option');
  16630. opt.value = ca.name;
  16631. opt.textContent = `${ca.name} (${ca.common_name})`;
  16632. caSelect.appendChild(opt);
  16633. });
  16634. document.getElementById('modal-create-cert').classList.remove('hidden');
  16635. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16636. }
  16637. function closeCreateCertModal() {
  16638. document.getElementById('modal-create-cert').classList.add('hidden');
  16639. }
  16640. async function submitCreateCert(event) {
  16641. event.preventDefault();
  16642. const rawSans = document.getElementById('cert-sans').value;
  16643. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16644. const caName = document.getElementById('cert-ca-select').value;
  16645. const payload = {
  16646. name: document.getElementById('cert-name').value.trim(),
  16647. common_name: document.getElementById('cert-cn').value.trim(),
  16648. ca_name: caName,
  16649. sans: sansList,
  16650. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16651. key_type: document.getElementById('cert-key-type').value,
  16652. is_server: true
  16653. };
  16654. try {
  16655. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16656. method: 'POST',
  16657. headers: { 'Content-Type': 'application/json' },
  16658. body: JSON.stringify(payload)
  16659. });
  16660. if (!res.ok) {
  16661. const errData = await res.json();
  16662. throw new Error(errData.message || 'Failed to issue certificate');
  16663. }
  16664. closeCreateCertModal();
  16665. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16666. await loadCertificates();
  16667. } catch (err) {
  16668. showToast('Error', err.message, 'error');
  16669. }
  16670. }
  16671. // Let's Encrypt
  16672. function openLetsEncryptModal() {
  16673. document.getElementById('form-letsencrypt').reset();
  16674. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16675. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16676. }
  16677. function closeLetsEncryptModal() {
  16678. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16679. }
  16680. async function submitLetsEncrypt(event) {
  16681. event.preventDefault();
  16682. const domain = document.getElementById('le-domain').value.trim();
  16683. const email = document.getElementById('le-email').value.trim();
  16684. let name = document.getElementById('le-name').value.trim();
  16685. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16686. const staging = document.getElementById('le-staging').checked;
  16687. const btn = document.getElementById('btn-submit-letsencrypt');
  16688. const origBtnHtml = btn.innerHTML;
  16689. btn.disabled = true;
  16690. 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>`;
  16691. try {
  16692. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16693. method: 'POST',
  16694. headers: { 'Content-Type': 'application/json' },
  16695. body: JSON.stringify({
  16696. name: name,
  16697. domain: domain,
  16698. email: email,
  16699. staging: staging
  16700. })
  16701. });
  16702. if (!res.ok) {
  16703. const errData = await res.json();
  16704. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16705. }
  16706. closeLetsEncryptModal();
  16707. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16708. await loadCertificates();
  16709. } catch (err) {
  16710. showToast('Let\'s Encrypt Error', err.message, 'error');
  16711. } finally {
  16712. btn.disabled = false;
  16713. btn.innerHTML = origBtnHtml;
  16714. }
  16715. }
  16716. // Import Cert
  16717. function openImportCertModal() {
  16718. document.getElementById('form-import-cert').reset();
  16719. document.getElementById('modal-import-cert').classList.remove('hidden');
  16720. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16721. }
  16722. function closeImportCertModal() {
  16723. document.getElementById('modal-import-cert').classList.add('hidden');
  16724. }
  16725. async function submitImportCert(event) {
  16726. event.preventDefault();
  16727. const payload = {
  16728. name: document.getElementById('import-cert-name').value.trim(),
  16729. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16730. key_pem: document.getElementById('import-key-pem').value.trim()
  16731. };
  16732. try {
  16733. const res = await fetch(`${API_BASE}/certificates/import`, {
  16734. method: 'POST',
  16735. headers: { 'Content-Type': 'application/json' },
  16736. body: JSON.stringify(payload)
  16737. });
  16738. if (!res.ok) {
  16739. const errData = await res.json();
  16740. throw new Error(errData.message || 'Failed to import certificate');
  16741. }
  16742. closeImportCertModal();
  16743. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16744. await loadCertificates();
  16745. } catch (err) {
  16746. showToast('Error', err.message, 'error');
  16747. }
  16748. }
  16749. // View / Export Modal
  16750. async function openViewCertModal(name) {
  16751. const c = (state.certificates || []).find(x => x.name === name);
  16752. if (!c) return;
  16753. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16754. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16755. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16756. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16757. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16758. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16759. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16760. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16761. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16762. document.getElementById('modal-view-cert').classList.remove('hidden');
  16763. try {
  16764. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16765. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16766. const data = await res.json();
  16767. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16768. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16769. } catch (err) {
  16770. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16771. document.getElementById('view-key-pem-text').value = '';
  16772. }
  16773. }
  16774. function closeViewCertModal() {
  16775. document.getElementById('modal-view-cert').classList.add('hidden');
  16776. }
  16777. function copyCertPEM() {
  16778. const text = document.getElementById('view-cert-pem-text').value;
  16779. if (!text) return;
  16780. navigator.clipboard.writeText(text).then(() => {
  16781. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16782. }).catch(() => {
  16783. showToast('Error', 'Failed to copy to clipboard', 'error');
  16784. });
  16785. }
  16786. function copyKeyPEM() {
  16787. const text = document.getElementById('view-key-pem-text').value;
  16788. if (!text) return;
  16789. navigator.clipboard.writeText(text).then(() => {
  16790. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16791. }).catch(() => {
  16792. showToast('Error', 'Failed to copy to clipboard', 'error');
  16793. });
  16794. }
  16795. async function deleteCertificate(name) {
  16796. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16797. return;
  16798. }
  16799. try {
  16800. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16801. method: 'DELETE'
  16802. });
  16803. if (!res.ok) {
  16804. const errData = await res.json();
  16805. throw new Error(errData.message || 'Failed to delete certificate');
  16806. }
  16807. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16808. await loadCertificates();
  16809. } catch (err) {
  16810. showToast('Error', err.message, 'error');
  16811. }
  16812. }
  16813. // Refresh immediately when returning to a backgrounded controller tab.
  16814. document.addEventListener('visibilitychange', () => {
  16815. if (!state.currentUser) return;
  16816. if (document.hidden) {
  16817. if (trafficEventSource) trafficEventSource.close();
  16818. trafficEventSource = null;
  16819. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16820. trafficPollFallback = null;
  16821. } else {
  16822. fetchData(false);
  16823. initLiveTrafficStream();
  16824. if (state.activeTab === 'bwtest') loadBwTestView();
  16825. }
  16826. });
  16827. async function loadUpdateStatus(populate = true) {
  16828. try {
  16829. const res = await fetch(`${API_BASE}/update/status`);
  16830. if (!res.ok) throw new Error(await responseError(res));
  16831. const data = await res.json();
  16832. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16833. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16834. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16835. document.getElementById('update-state').textContent = data.state || 'idle';
  16836. document.getElementById('update-log').textContent = data.log || '';
  16837. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16838. }
  16839. async function saveUpdateConfig() {
  16840. try {
  16841. const repository = document.getElementById('update-repository').value.trim();
  16842. const branch = 'master';
  16843. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16844. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16845. if (!res.ok) throw new Error(await responseError(res));
  16846. document.getElementById('update-install-button').disabled = true;
  16847. document.getElementById('update-available').textContent = '—';
  16848. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16849. await loadUpdateStatus(false);
  16850. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16851. }
  16852. async function checkUpdate() {
  16853. try {
  16854. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16855. if (!res.ok) throw new Error(await responseError(res));
  16856. const data = await res.json();
  16857. document.getElementById('update-available').textContent = data.available_version;
  16858. document.getElementById('update-install-button').disabled = !data.update_available;
  16859. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16860. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16861. }
  16862. async function startUpdate(action) {
  16863. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16864. try {
  16865. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16866. if (!res.ok) throw new Error(await responseError(res));
  16867. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16868. await loadUpdateStatus(false);
  16869. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16870. }
  16871. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16872. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16873. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16874. function safeFirewallRow(row) {
  16875. const result = {...row};
  16876. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16877. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16878. return result;
  16879. }
  16880. function setFirewallDays(prefix, days) {
  16881. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16882. 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); }
  16883. }
  16884. function getFirewallDays(prefix) {
  16885. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16886. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16887. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16888. return selected.join(',');
  16889. }
  16890. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16891. const id = document.getElementById(kind+'-modal-id')?.value;
  16892. if (!id) { resetDisplay(); return; }
  16893. try {
  16894. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16895. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16896. resetDisplay(); await loadFirewall(false);
  16897. } catch(error) { showToast('Error', error.message, 'error'); }
  16898. }
  16899. function reviewLegacyFirewallSettings(kind, id) {
  16900. if (!id) return true;
  16901. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16902. const rule = (rows || []).find(r => r.id === id);
  16903. if (!rule) return true;
  16904. 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'];
  16905. const present = unsupported.filter(key => rule[key]);
  16906. if (!present.length) return true;
  16907. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16908. }
  16909. function refreshFirewallRejectTypes() {
  16910. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16911. const old=select.value;
  16912. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16913. 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'];
  16914. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16915. if(types.includes(old))select.value=old;
  16916. }
  16917. function setFirewallActionSelection(kind, value) {
  16918. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16919. if(!Array.from(select.options).some(option=>option.value===value)) {
  16920. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16921. }
  16922. select.value=value;
  16923. }
  16924. // ==========================================
  16925. // REVERSE PROXY & APPLICATION GATEWAY
  16926. // ==========================================
  16927. state.proxyRules = [];
  16928. state.proxyConfig = null;
  16929. async function loadReverseProxy(manual = false) {
  16930. try {
  16931. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16932. fetch(`${API_BASE}/proxy/config`),
  16933. fetch(`${API_BASE}/proxy/rules`),
  16934. fetch(`${API_BASE}/certificates`).catch(() => null)
  16935. ]);
  16936. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16937. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16938. state.proxyConfig = await cfgRes.json();
  16939. state.proxyRules = await rulesRes.json() || [];
  16940. if (certsRes && certsRes.ok) {
  16941. state.certificates = await certsRes.json() || [];
  16942. }
  16943. renderProxyRules(state.proxyRules);
  16944. updateProxyMetrics();
  16945. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16946. } catch (err) {
  16947. console.error('loadReverseProxy error:', err);
  16948. if (manual) showToast('Error', err.message, 'error');
  16949. }
  16950. }
  16951. function updateProxyMetrics() {
  16952. const badge = document.getElementById('badge-proxy-count');
  16953. if (badge) badge.textContent = (state.proxyRules || []).length;
  16954. const metricRules = document.getElementById('proxy-metric-rules');
  16955. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16956. const cfg = state.proxyConfig;
  16957. const statusEl = document.getElementById('proxy-metric-status');
  16958. const portsEl = document.getElementById('proxy-metric-ports');
  16959. if (cfg) {
  16960. if (statusEl) {
  16961. if (cfg.enabled) {
  16962. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16963. } else {
  16964. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16965. }
  16966. }
  16967. if (portsEl) {
  16968. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16969. }
  16970. }
  16971. let totalRequests = 0;
  16972. const certSet = new Set();
  16973. (state.proxyRules || []).forEach(r => {
  16974. totalRequests += (r.stats && r.stats.requests) || 0;
  16975. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16976. });
  16977. const metricRequests = document.getElementById('proxy-metric-requests');
  16978. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16979. const metricCerts = document.getElementById('proxy-metric-certs');
  16980. if (metricCerts) metricCerts.textContent = certSet.size;
  16981. }
  16982. function renderProxyRules(rules) {
  16983. const tbody = document.getElementById('proxy-rules-table-body');
  16984. if (!tbody) return;
  16985. if (!rules || rules.length === 0) {
  16986. 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>';
  16987. return;
  16988. }
  16989. tbody.innerHTML = rules.map(r => {
  16990. const isEnabled = r.enabled !== false;
  16991. 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>';
  16992. 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>`;
  16993. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16994. 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>';
  16995. 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>';
  16996. 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>` : '';
  16997. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16998. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16999. return `
  17000. <tr class="hover:bg-slate-800/40 transition">
  17001. <td class="py-3 px-4">
  17002. <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'}">
  17003. <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>
  17004. </button>
  17005. </td>
  17006. <td class="py-3 px-4">
  17007. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  17008. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  17009. </td>
  17010. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  17011. ${domainsStr}
  17012. </td>
  17013. <td class="py-3 px-4">
  17014. ${pathBadge}
  17015. </td>
  17016. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  17017. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  17018. </td>
  17019. <td class="py-3 px-4 whitespace-nowrap">
  17020. ${protoBadge}${certBadge}
  17021. </td>
  17022. <td class="py-3 px-4 font-mono">
  17023. ${stripBadge}
  17024. </td>
  17025. <td class="py-3 px-4 font-mono text-slate-300">
  17026. ${requests}
  17027. </td>
  17028. <td class="py-3 px-4 text-right whitespace-nowrap">
  17029. <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>
  17030. <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>
  17031. </td>
  17032. </tr>
  17033. `;
  17034. }).join('');
  17035. }
  17036. function populateProxyCertDropdown(selectedVal = '') {
  17037. const select = document.getElementById('proxy-rule-cert');
  17038. if (!select) return;
  17039. const certs = state.certificates || [];
  17040. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  17041. certs.filter(c => !c.is_ca).forEach(c => {
  17042. const opt = document.createElement('option');
  17043. opt.value = c.name;
  17044. const cn = c.common_name ? ` (${c.common_name})` : '';
  17045. opt.textContent = `${c.name}${cn}`;
  17046. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  17047. opt.selected = true;
  17048. }
  17049. select.appendChild(opt);
  17050. });
  17051. }
  17052. function populateDefaultProxyCertDropdown(selectedVal = '') {
  17053. const select = document.getElementById('proxy-cfg-default-cert');
  17054. if (!select) return;
  17055. const certs = state.certificates || [];
  17056. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  17057. certs.filter(c => !c.is_ca).forEach(c => {
  17058. const opt = document.createElement('option');
  17059. opt.value = c.name;
  17060. const cn = c.common_name ? ` (${c.common_name})` : '';
  17061. opt.textContent = `${c.name}${cn}`;
  17062. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  17063. opt.selected = true;
  17064. }
  17065. select.appendChild(opt);
  17066. });
  17067. }
  17068. function onProxyProtoChange() {
  17069. const proto = document.getElementById('proxy-rule-proto')?.value;
  17070. const certSelect = document.getElementById('proxy-rule-cert');
  17071. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  17072. if (proto === 'http') {
  17073. if (certSelect) certSelect.disabled = true;
  17074. if (redirectCheck) redirectCheck.disabled = true;
  17075. } else {
  17076. if (certSelect) certSelect.disabled = false;
  17077. if (redirectCheck) redirectCheck.disabled = false;
  17078. }
  17079. }
  17080. function openAddProxyRuleModal() {
  17081. const modal = document.getElementById('modal-proxy-rule');
  17082. if (!modal) return;
  17083. document.getElementById('proxy-rule-modal-title').innerHTML = `
  17084. <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>
  17085. <span>Add Reverse Proxy Rule</span>
  17086. `;
  17087. document.getElementById('proxy-rule-id').value = '';
  17088. document.getElementById('proxy-rule-name').value = '';
  17089. document.getElementById('proxy-rule-domains').value = '';
  17090. document.getElementById('proxy-rule-path').value = '/';
  17091. document.getElementById('proxy-rule-target').value = '';
  17092. document.getElementById('proxy-rule-proto').value = 'both';
  17093. document.getElementById('proxy-rule-strip-path').checked = false;
  17094. document.getElementById('proxy-rule-http-to-https').checked = false;
  17095. document.getElementById('proxy-rule-preserve-host').checked = false;
  17096. document.getElementById('proxy-rule-insecure-tls').checked = false;
  17097. document.getElementById('proxy-rule-enabled').checked = true;
  17098. document.getElementById('proxy-rule-comment').value = '';
  17099. populateProxyCertDropdown('');
  17100. onProxyProtoChange();
  17101. modal.classList.remove('hidden');
  17102. }
  17103. function openEditProxyRuleModal(id) {
  17104. const modal = document.getElementById('modal-proxy-rule');
  17105. if (!modal) return;
  17106. const rule = (state.proxyRules || []).find(r => r.id === id);
  17107. if (!rule) {
  17108. showToast('Error', 'Rule not found', 'error');
  17109. return;
  17110. }
  17111. document.getElementById('proxy-rule-modal-title').innerHTML = `
  17112. <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>
  17113. <span>Edit Reverse Proxy Rule</span>
  17114. `;
  17115. document.getElementById('proxy-rule-id').value = rule.id || '';
  17116. document.getElementById('proxy-rule-name').value = rule.name || '';
  17117. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  17118. document.getElementById('proxy-rule-path').value = rule.path || '/';
  17119. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  17120. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  17121. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  17122. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  17123. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  17124. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  17125. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  17126. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  17127. populateProxyCertDropdown(rule.certificate || '');
  17128. onProxyProtoChange();
  17129. modal.classList.remove('hidden');
  17130. }
  17131. function closeProxyRuleModal() {
  17132. const modal = document.getElementById('modal-proxy-rule');
  17133. if (modal) modal.classList.add('hidden');
  17134. }
  17135. async function saveProxyRule(event) {
  17136. event.preventDefault();
  17137. const id = document.getElementById('proxy-rule-id').value;
  17138. const name = document.getElementById('proxy-rule-name').value.trim();
  17139. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  17140. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  17141. const target = document.getElementById('proxy-rule-target').value.trim();
  17142. const proto = document.getElementById('proxy-rule-proto').value;
  17143. const cert = document.getElementById('proxy-rule-cert').value;
  17144. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  17145. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  17146. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  17147. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  17148. const enabled = document.getElementById('proxy-rule-enabled').checked;
  17149. const comment = document.getElementById('proxy-rule-comment').value.trim();
  17150. let domains = [];
  17151. if (rawDomains && rawDomains !== '*') {
  17152. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  17153. }
  17154. const payload = {
  17155. id: id || undefined,
  17156. name,
  17157. domains,
  17158. path: pathVal,
  17159. target_url: target,
  17160. protocol: proto,
  17161. certificate: cert,
  17162. strip_path: stripPath,
  17163. http_to_https: httpToHttps,
  17164. preserve_host: preserveHost,
  17165. insecure_tls: insecureTLS,
  17166. enabled,
  17167. comment
  17168. };
  17169. try {
  17170. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  17171. const method = id ? 'PUT' : 'POST';
  17172. const res = await fetch(url, {
  17173. method,
  17174. headers: { 'Content-Type': 'application/json' },
  17175. body: JSON.stringify(payload)
  17176. });
  17177. if (!res.ok) {
  17178. const errData = await res.json().catch(() => ({}));
  17179. throw new Error(errData.message || 'Failed to save proxy rule');
  17180. }
  17181. closeProxyRuleModal();
  17182. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  17183. await loadReverseProxy(false);
  17184. } catch (err) {
  17185. showToast('Error', err.message, 'error');
  17186. }
  17187. }
  17188. async function deleteProxyRule(id) {
  17189. const rule = (state.proxyRules || []).find(r => r.id === id);
  17190. const name = rule ? rule.name : id;
  17191. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  17192. return;
  17193. }
  17194. try {
  17195. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  17196. method: 'DELETE'
  17197. });
  17198. if (!res.ok) {
  17199. const errData = await res.json().catch(() => ({}));
  17200. throw new Error(errData.message || 'Failed to delete rule');
  17201. }
  17202. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17203. await loadReverseProxy(false);
  17204. } catch (err) {
  17205. showToast('Error', err.message, 'error');
  17206. }
  17207. }
  17208. async function toggleProxyRuleState(id, currentState) {
  17209. try {
  17210. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17211. method: 'POST',
  17212. headers: { 'Content-Type': 'application/json' },
  17213. body: JSON.stringify({ enabled: !currentState })
  17214. });
  17215. if (!res.ok) {
  17216. const errData = await res.json().catch(() => ({}));
  17217. throw new Error(errData.message || 'Failed to toggle rule state');
  17218. }
  17219. await loadReverseProxy(false);
  17220. } catch (err) {
  17221. showToast('Error', err.message, 'error');
  17222. }
  17223. }
  17224. function openProxyConfigModal() {
  17225. const modal = document.getElementById('modal-proxy-config');
  17226. if (!modal) return;
  17227. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17228. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17229. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17230. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17231. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17232. modal.classList.remove('hidden');
  17233. }
  17234. function closeProxyConfigModal() {
  17235. const modal = document.getElementById('modal-proxy-config');
  17236. if (modal) modal.classList.add('hidden');
  17237. }
  17238. async function saveProxyConfig(event) {
  17239. event.preventDefault();
  17240. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17241. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17242. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17243. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17244. const payload = {
  17245. enabled,
  17246. http_port: httpPort,
  17247. https_port: httpsPort,
  17248. default_cert: defaultCert
  17249. };
  17250. try {
  17251. const res = await fetch(`${API_BASE}/proxy/config`, {
  17252. method: 'POST',
  17253. headers: { 'Content-Type': 'application/json' },
  17254. body: JSON.stringify(payload)
  17255. });
  17256. if (!res.ok) {
  17257. const errData = await res.json().catch(() => ({}));
  17258. throw new Error(errData.message || 'Failed to update proxy settings');
  17259. }
  17260. closeProxyConfigModal();
  17261. showToast('Success', 'Reverse proxy settings updated', 'success');
  17262. await loadReverseProxy(false);
  17263. } catch (err) {
  17264. showToast('Error', err.message, 'error');
  17265. }
  17266. }
  17267. // ==================== SD-WAN Controller ====================
  17268. async function loadSDWAN(manual = false) {
  17269. try {
  17270. const [groupsRes, telemetryRes] = await Promise.all([
  17271. fetch(`${API_BASE}/sdwan/groups`),
  17272. fetch(`${API_BASE}/sdwan/telemetry`)
  17273. ]);
  17274. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17275. state.sdwanGroups = await groupsRes.json() || [];
  17276. if (telemetryRes.ok) {
  17277. state.sdwanTelemetry = await telemetryRes.json() || {};
  17278. }
  17279. renderSDWANGroups(state.sdwanGroups);
  17280. renderSDWANMembers(state.sdwanGroups);
  17281. updateSDWANMetrics(state.sdwanTelemetry);
  17282. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17283. } catch (err) {
  17284. console.error('loadSDWAN error:', err);
  17285. if (manual) showToast('Error', err.message, 'error');
  17286. }
  17287. }
  17288. function updateSDWANMetrics(telemetry) {
  17289. const groups = state.sdwanGroups || [];
  17290. const t = telemetry || {};
  17291. const badge = document.getElementById('badge-sdwan-count');
  17292. if (badge) badge.textContent = groups.length;
  17293. const metricGroups = document.getElementById('sdwan-metric-groups');
  17294. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17295. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17296. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17297. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17298. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17299. const metricDown = document.getElementById('sdwan-metric-down');
  17300. if (metricDown) metricDown.textContent = t.down_members || 0;
  17301. }
  17302. function renderSDWANGroups(groups) {
  17303. const tbody = document.getElementById('sdwan-groups-table-body');
  17304. if (!tbody) return;
  17305. if (!groups || groups.length === 0) {
  17306. 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>';
  17307. return;
  17308. }
  17309. tbody.innerHTML = groups.map(g => {
  17310. const isEnabled = g.disabled !== true;
  17311. const members = g.members || [];
  17312. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17313. // Build distribution progress bar
  17314. let distHtml = '';
  17315. if (members.length === 0) {
  17316. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17317. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17318. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17319. const segments = members.map((m, idx) => {
  17320. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17321. const col = colors[idx % colors.length];
  17322. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17323. }).join('');
  17324. const labels = members.map((m, idx) => {
  17325. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17326. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17327. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17328. }).join('');
  17329. distHtml = `
  17330. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17331. <div class="flex flex-wrap">${labels}</div>
  17332. `;
  17333. } else if (g.mode === 'lowest-latency') {
  17334. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17335. } else if (g.mode === 'lowest-loss') {
  17336. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17337. } else if (g.mode === 'failover') {
  17338. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17339. }
  17340. let modeBadge = '';
  17341. switch (g.mode) {
  17342. case 'weighted':
  17343. 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>';
  17344. break;
  17345. case 'pcc':
  17346. 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>';
  17347. break;
  17348. case 'lowest-latency':
  17349. 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>';
  17350. break;
  17351. case 'lowest-loss':
  17352. 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>';
  17353. break;
  17354. case 'failover':
  17355. 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>';
  17356. break;
  17357. default:
  17358. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17359. }
  17360. const autoNatBadge = g.auto_nat
  17361. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17362. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17363. return `
  17364. <tr class="hover:bg-slate-800/40 transition">
  17365. <td class="py-3 px-4">
  17366. <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'}">
  17367. <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>
  17368. </button>
  17369. </td>
  17370. <td class="py-3 px-4">
  17371. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17372. <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>
  17373. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17374. </div>
  17375. </td>
  17376. <td class="py-3 px-4">${modeBadge}</td>
  17377. <td class="py-3 px-4">${distHtml}</td>
  17378. <td class="py-3 px-4">
  17379. <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>
  17380. </td>
  17381. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17382. <td class="py-3 px-4">${autoNatBadge}</td>
  17383. <td class="py-3 px-4 text-right">
  17384. <div class="flex items-center justify-end gap-1.5">
  17385. <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">
  17386. <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>
  17387. </button>
  17388. <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">
  17389. <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>
  17390. </button>
  17391. <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">
  17392. <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>
  17393. </button>
  17394. </div>
  17395. </td>
  17396. </tr>
  17397. `;
  17398. }).join('');
  17399. }
  17400. function renderSDWANMembers(groups) {
  17401. const tbody = document.getElementById('sdwan-members-table-body');
  17402. if (!tbody) return;
  17403. const allMembers = [];
  17404. (groups || []).forEach(g => {
  17405. (g.members || []).forEach(m => {
  17406. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17407. });
  17408. });
  17409. if (allMembers.length === 0) {
  17410. 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>';
  17411. return;
  17412. }
  17413. tbody.innerHTML = allMembers.map(m => {
  17414. const isEnabled = m.disabled !== true;
  17415. 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>';
  17416. if (!isEnabled) {
  17417. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17418. } else if (m.status === 'DEGRADED') {
  17419. 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>';
  17420. } else if (m.status === 'DOWN') {
  17421. 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>';
  17422. }
  17423. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17424. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17425. return `
  17426. <tr class="hover:bg-slate-800/40 transition">
  17427. <td class="py-3 px-4">
  17428. <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'}">
  17429. <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>
  17430. </button>
  17431. </td>
  17432. <td class="py-3 px-4">
  17433. <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>
  17434. </td>
  17435. <td class="py-3 px-4">
  17436. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17437. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17438. </td>
  17439. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17440. <td class="py-3 px-4">
  17441. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17442. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17443. </td>
  17444. <td class="py-3 px-4">${statusBadge}</td>
  17445. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17446. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17447. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17448. </td>
  17449. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17450. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17451. </td>
  17452. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17453. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17454. </td>
  17455. <td class="py-3 px-4 text-right">
  17456. <div class="flex items-center justify-end gap-1.5">
  17457. <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">
  17458. <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>
  17459. </button>
  17460. <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">
  17461. <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>
  17462. </button>
  17463. </div>
  17464. </td>
  17465. </tr>
  17466. `;
  17467. }).join('');
  17468. }
  17469. // Modal handling for SD-WAN Groups
  17470. function openAddSDWANGroupModal() {
  17471. const modal = document.getElementById('modal-sdwan-group');
  17472. if (!modal) return;
  17473. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17474. document.getElementById('sdwan-group-id').value = '';
  17475. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17476. document.getElementById('sdwan-group-name').disabled = false;
  17477. document.getElementById('sdwan-group-mode').value = 'weighted';
  17478. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17479. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17480. document.getElementById('sdwan-group-probe-interval').value = 3;
  17481. document.getElementById('sdwan-group-auto-nat').checked = true;
  17482. document.getElementById('sdwan-group-comment').value = '';
  17483. modal.classList.remove('hidden');
  17484. }
  17485. function openEditSDWANGroupModal(id) {
  17486. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17487. if (!group) return;
  17488. const modal = document.getElementById('modal-sdwan-group');
  17489. if (!modal) return;
  17490. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17491. document.getElementById('sdwan-group-id').value = group.id;
  17492. document.getElementById('sdwan-group-name').value = group.name;
  17493. document.getElementById('sdwan-group-name').disabled = true;
  17494. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17495. if (group.mode === 'pcc') {
  17496. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17497. } else {
  17498. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17499. }
  17500. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17501. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17502. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17503. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17504. modal.classList.remove('hidden');
  17505. }
  17506. function closeSDWANGroupModal() {
  17507. const modal = document.getElementById('modal-sdwan-group');
  17508. if (modal) modal.classList.add('hidden');
  17509. }
  17510. function onSDWANModeChange() {
  17511. const mode = document.getElementById('sdwan-group-mode').value;
  17512. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17513. if (pccContainer) {
  17514. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17515. else pccContainer.classList.add('hidden');
  17516. }
  17517. }
  17518. async function saveSDWANGroup(event) {
  17519. event.preventDefault();
  17520. const id = document.getElementById('sdwan-group-id').value;
  17521. const name = document.getElementById('sdwan-group-name').value.trim();
  17522. const mode = document.getElementById('sdwan-group-mode').value;
  17523. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17524. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17525. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17526. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17527. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17528. const payload = {
  17529. id: id || undefined,
  17530. name,
  17531. mode,
  17532. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17533. probe_interval: probeInterval,
  17534. auto_nat: autoNAT,
  17535. comment,
  17536. members: existing ? existing.members : undefined
  17537. };
  17538. try {
  17539. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17540. method: 'POST',
  17541. headers: { 'Content-Type': 'application/json' },
  17542. body: JSON.stringify(payload)
  17543. });
  17544. if (!res.ok) {
  17545. const err = await res.json().catch(() => ({}));
  17546. throw new Error(err.message || 'Failed to save SD-WAN group');
  17547. }
  17548. closeSDWANGroupModal();
  17549. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17550. await loadSDWAN(false);
  17551. } catch (err) {
  17552. showToast('Error', err.message, 'error');
  17553. }
  17554. }
  17555. async function toggleSDWANGroupState(id, currentState) {
  17556. try {
  17557. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17558. method: 'POST',
  17559. headers: { 'Content-Type': 'application/json' },
  17560. body: JSON.stringify({ disabled: currentState })
  17561. });
  17562. if (!res.ok) throw new Error('Failed to update group state');
  17563. await loadSDWAN(false);
  17564. } catch (err) {
  17565. showToast('Error', err.message, 'error');
  17566. }
  17567. }
  17568. async function deleteSDWANGroup(id) {
  17569. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17570. const name = group ? group.name : id;
  17571. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17572. try {
  17573. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17574. method: 'DELETE'
  17575. });
  17576. if (!res.ok) {
  17577. const err = await res.json().catch(() => ({}));
  17578. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17579. }
  17580. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17581. await loadSDWAN(false);
  17582. } catch (err) {
  17583. showToast('Error', err.message, 'error');
  17584. }
  17585. }
  17586. // Modal handling for SD-WAN Members
  17587. function populateSDWANGroupsSelect(selectedId = '') {
  17588. const sel = document.getElementById('sdwan-member-group-id');
  17589. if (!sel) return;
  17590. sel.innerHTML = '';
  17591. (state.sdwanGroups || []).forEach(g => {
  17592. const opt = document.createElement('option');
  17593. opt.value = g.id;
  17594. opt.textContent = `${g.name} (${g.mode})`;
  17595. if (g.id === selectedId) opt.selected = true;
  17596. sel.appendChild(opt);
  17597. });
  17598. }
  17599. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17600. const sel = document.getElementById('sdwan-member-interface');
  17601. if (!sel) return;
  17602. sel.innerHTML = '';
  17603. (state.interfaces || []).forEach(i => {
  17604. const opt = document.createElement('option');
  17605. opt.value = i.name;
  17606. opt.textContent = `${i.name} (${i.role || i.type})`;
  17607. if (i.name === selectedVal) opt.selected = true;
  17608. sel.appendChild(opt);
  17609. });
  17610. }
  17611. function openAddSDWANMemberModal(defaultGroupId = null) {
  17612. const modal = document.getElementById('modal-sdwan-member');
  17613. if (!modal) return;
  17614. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17615. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17616. return;
  17617. }
  17618. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17619. document.getElementById('sdwan-member-id').value = '';
  17620. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17621. populateSDWANMemberInterfaceSelect();
  17622. document.getElementById('sdwan-member-gateway').value = '';
  17623. document.getElementById('sdwan-member-weight').value = 50;
  17624. document.getElementById('sdwan-member-priority').value = 1;
  17625. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17626. document.getElementById('sdwan-member-max-lat').value = 250;
  17627. document.getElementById('sdwan-member-max-loss').value = 20;
  17628. document.getElementById('sdwan-member-comment').value = '';
  17629. modal.classList.remove('hidden');
  17630. }
  17631. function openEditSDWANMemberModal(groupId, memberId) {
  17632. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17633. if (!group) return;
  17634. const member = (group.members || []).find(m => m.id === memberId);
  17635. if (!member) return;
  17636. const modal = document.getElementById('modal-sdwan-member');
  17637. if (!modal) return;
  17638. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17639. document.getElementById('sdwan-member-id').value = member.id;
  17640. populateSDWANGroupsSelect(group.id);
  17641. document.getElementById('sdwan-member-group-id').disabled = true;
  17642. populateSDWANMemberInterfaceSelect(member.interface);
  17643. document.getElementById('sdwan-member-interface').disabled = true;
  17644. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17645. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17646. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17647. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17648. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17649. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17650. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17651. modal.classList.remove('hidden');
  17652. }
  17653. function closeSDWANMemberModal() {
  17654. const modal = document.getElementById('modal-sdwan-member');
  17655. if (modal) {
  17656. document.getElementById('sdwan-member-group-id').disabled = false;
  17657. document.getElementById('sdwan-member-interface').disabled = false;
  17658. modal.classList.add('hidden');
  17659. }
  17660. }
  17661. async function saveSDWANMember(event) {
  17662. event.preventDefault();
  17663. const id = document.getElementById('sdwan-member-id').value;
  17664. let groupId = document.getElementById('sdwan-member-group-id').value;
  17665. let iface = document.getElementById('sdwan-member-interface').value;
  17666. // In edit mode with disabled selects, fallback to existing member data if needed
  17667. if (id) {
  17668. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17669. if (existingGroup) {
  17670. if (!groupId) groupId = existingGroup.id;
  17671. const mem = (existingGroup.members || []).find(m => m.id === id);
  17672. if (mem && !iface) iface = mem.interface;
  17673. }
  17674. }
  17675. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17676. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17677. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17678. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17679. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17680. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17681. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17682. const payload = {
  17683. id: id || undefined,
  17684. interface: iface,
  17685. gateway,
  17686. weight,
  17687. priority,
  17688. target_probe: targetProbe,
  17689. max_latency: maxLatency,
  17690. max_loss: maxLoss,
  17691. comment
  17692. };
  17693. try {
  17694. const method = id ? 'PUT' : 'POST';
  17695. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17696. method,
  17697. headers: { 'Content-Type': 'application/json' },
  17698. body: JSON.stringify(payload)
  17699. });
  17700. if (!res.ok) {
  17701. const err = await res.json().catch(() => ({}));
  17702. throw new Error(err.message || 'Failed to save member link');
  17703. }
  17704. closeSDWANMemberModal();
  17705. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17706. await loadSDWAN(false);
  17707. } catch (err) {
  17708. showToast('Error', err.message, 'error');
  17709. }
  17710. }
  17711. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17712. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17713. if (!group) return;
  17714. const member = (group.members || []).find(m => m.id === memberId);
  17715. if (!member) return;
  17716. const payload = {
  17717. ...member,
  17718. disabled: currentState
  17719. };
  17720. try {
  17721. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17722. method: 'PUT',
  17723. headers: { 'Content-Type': 'application/json' },
  17724. body: JSON.stringify(payload)
  17725. });
  17726. if (!res.ok) throw new Error('Failed to update member state');
  17727. await loadSDWAN(false);
  17728. } catch (err) {
  17729. showToast('Error', err.message, 'error');
  17730. }
  17731. }
  17732. async function deleteSDWANMember(groupId, iface) {
  17733. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17734. try {
  17735. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17736. method: 'DELETE'
  17737. });
  17738. if (!res.ok) {
  17739. const err = await res.json().catch(() => ({}));
  17740. throw new Error(err.message || 'Failed to remove member link');
  17741. }
  17742. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17743. await loadSDWAN(false);
  17744. } catch (err) {
  17745. showToast('Error', err.message, 'error');
  17746. }
  17747. }
  17748. // ==============================================================================
  17749. async function routingMutation(url, options) {
  17750. try {
  17751. const response = await fetch(url, options);
  17752. if (!response.ok) throw new Error(await responseError(response));
  17753. return true;
  17754. } catch (error) {
  17755. showToast('Routing change failed', error.message || 'Request failed', 'error');
  17756. return false;
  17757. }
  17758. }
  17759. // DYNAMIC ROUTING: RIP MODULE
  17760. // ==============================================================================
  17761. state.ripInstances = [];
  17762. state.ripInterfaces = [];
  17763. state.ripNeighborsLive = [];
  17764. state.ripRoutes = [];
  17765. state.selectedRipRow = {};
  17766. state.activeRipTab = 'instances';
  17767. function switchRipTab(tab) {
  17768. state.activeRipTab = tab;
  17769. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17770. const pane = document.getElementById(`rip-pane-${t}`);
  17771. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17772. if (pane) {
  17773. if (t === tab) pane.classList.remove('hidden');
  17774. else pane.classList.add('hidden');
  17775. }
  17776. if (btn) {
  17777. if (t === tab) {
  17778. 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';
  17779. } else {
  17780. 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';
  17781. }
  17782. }
  17783. });
  17784. }
  17785. function selectRipRow(tab, id) {
  17786. if (!state.selectedRipRow) state.selectedRipRow = {};
  17787. state.selectedRipRow[tab] = id;
  17788. if (tab === 'instances') {
  17789. renderRipInstances();
  17790. const btnEn = document.getElementById('btn-rip-inst-enable');
  17791. const btnDis = document.getElementById('btn-rip-inst-disable');
  17792. const btnRem = document.getElementById('btn-rip-inst-remove');
  17793. if (btnEn) btnEn.disabled = false;
  17794. if (btnDis) btnDis.disabled = false;
  17795. if (btnRem) btnRem.disabled = false;
  17796. } else if (tab === 'interfaces') {
  17797. renderRipInterfaces();
  17798. const btnEn = document.getElementById('btn-rip-iface-enable');
  17799. const btnDis = document.getElementById('btn-rip-iface-disable');
  17800. const btnRem = document.getElementById('btn-rip-iface-remove');
  17801. if (btnEn) btnEn.disabled = false;
  17802. if (btnDis) btnDis.disabled = false;
  17803. if (btnRem) btnRem.disabled = false;
  17804. }
  17805. }
  17806. function renderRipInstances() {
  17807. const tbody = document.getElementById('rip-instances-table-body');
  17808. if (!tbody) return;
  17809. const countEl = document.getElementById('rip-instances-footer-count');
  17810. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17811. let list = state.ripInstances || [];
  17812. if (filter) {
  17813. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17814. }
  17815. if (countEl) countEl.innerText = list.length;
  17816. const selId = state.selectedRipRow?.instances;
  17817. tbody.innerHTML = list.map((inst, idx) => {
  17818. const isSel = inst.id === selId;
  17819. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17820. const flagD = inst.disabled
  17821. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  17822. : (inst.running
  17823. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  17824. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  17825. const redist = [];
  17826. if (inst.redistribute_connected) redist.push('conn');
  17827. if (inst.redistribute_static) redist.push('static');
  17828. if (inst.redistribute_bgp) redist.push('bgp');
  17829. if (inst.redistribute_ospf) redist.push('ospf');
  17830. if (inst.redistribute_default) redist.push('default');
  17831. const filterBadges = [];
  17832. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  17833. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  17834. return `
  17835. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17836. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17837. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17838. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17839. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17840. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17841. ${filterBadges.join(' ')}
  17842. </td>
  17843. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${inst.version == 1 || inst.version === 'ripng' ? 'RIPng' : 'RIPv2'}</td>
  17844. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17845. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17846. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17847. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17848. </tr>
  17849. `;
  17850. }).join('');
  17851. }
  17852. function renderRipInterfaces() {
  17853. const tbody = document.getElementById('rip-interfaces-table-body');
  17854. if (!tbody) return;
  17855. const countEl = document.getElementById('rip-interfaces-footer-count');
  17856. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17857. let list = state.ripInterfaces || [];
  17858. if (filter) {
  17859. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17860. }
  17861. if (countEl) countEl.innerText = list.length;
  17862. const selId = state.selectedRipRow?.interfaces;
  17863. tbody.innerHTML = list.map((iface, idx) => {
  17864. const isSel = iface.id === selId;
  17865. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17866. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17867. return `
  17868. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17869. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17870. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17871. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17872. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17873. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17874. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17875. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17876. <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>
  17877. </tr>
  17878. `;
  17879. }).join('');
  17880. }
  17881. function renderRipNeighbors() {
  17882. const tbody = document.getElementById('rip-neighbors-table-body');
  17883. if (!tbody) return;
  17884. const countEl = document.getElementById('rip-neighbors-footer-count');
  17885. const list = state.ripNeighborsLive || [];
  17886. if (countEl) countEl.innerText = list.length;
  17887. tbody.innerHTML = list.map((nbr, idx) => `
  17888. <tr class="hover:bg-[#1a2636] text-slate-300">
  17889. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17890. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17891. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17892. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17893. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17894. </tr>
  17895. `).join('');
  17896. }
  17897. function renderRipRoutes() {
  17898. const tbody = document.getElementById('rip-routes-table-body');
  17899. if (!tbody) return;
  17900. const countEl = document.getElementById('rip-routes-footer-count');
  17901. const list = state.ripRoutes || [];
  17902. if (countEl) countEl.innerText = list.length;
  17903. tbody.innerHTML = list.map((r, idx) => `
  17904. <tr class="hover:bg-[#1a2636] text-slate-300">
  17905. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17906. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17907. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17908. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17909. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17910. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17911. </tr>
  17912. `).join('');
  17913. }
  17914. function openRipInstanceModal() {
  17915. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17916. document.getElementById('modal-rip-instance-id').value = '';
  17917. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17918. document.getElementById('modal-rip-instance-version').value = '2';
  17919. document.getElementById('modal-rip-instance-update').value = '30';
  17920. document.getElementById('modal-rip-instance-timeout').value = '180';
  17921. document.getElementById('modal-rip-instance-garbage').value = '120';
  17922. document.getElementById('modal-rip-instance-metric').value = '1';
  17923. document.getElementById('modal-rip-instance-comment').value = '';
  17924. document.getElementById('modal-rip-instance-in-filter').value = '';
  17925. document.getElementById('modal-rip-instance-out-filter').value = '';
  17926. document.getElementById('modal-rip-instance-enabled').checked = true;
  17927. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17928. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17929. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17930. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17931. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17932. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17933. }
  17934. function openEditRipInstanceModal(id) {
  17935. const inst = (state.ripInstances || []).find(i => i.id === id);
  17936. if (!inst) return;
  17937. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17938. document.getElementById('modal-rip-instance-id').value = inst.id;
  17939. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17940. document.getElementById('modal-rip-instance-version').value = (inst.version == 1 || inst.version === 'ripng') ? '1' : '2';
  17941. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17942. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17943. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17944. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17945. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17946. document.getElementById('modal-rip-instance-in-filter').value = inst.in_filter || '';
  17947. document.getElementById('modal-rip-instance-out-filter').value = inst.out_filter || '';
  17948. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17949. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17950. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17951. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17952. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17953. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17954. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17955. }
  17956. function closeRipInstanceModal() {
  17957. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17958. }
  17959. async function submitRipInstance(e) {
  17960. e.preventDefault();
  17961. const id = document.getElementById('modal-rip-instance-id').value;
  17962. const payload = {
  17963. id: id || undefined,
  17964. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17965. version: parseInt(document.getElementById('modal-rip-instance-version').value, 10) || 2,
  17966. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17967. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17968. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17969. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17970. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17971. in_filter: (document.getElementById('modal-rip-instance-in-filter')?.value || '').trim(),
  17972. out_filter: (document.getElementById('modal-rip-instance-out-filter')?.value || '').trim(),
  17973. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17974. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17975. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17976. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17977. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17978. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17979. };
  17980. try {
  17981. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17982. method: 'POST',
  17983. headers: { 'Content-Type': 'application/json' },
  17984. body: JSON.stringify(payload)
  17985. });
  17986. if (!res.ok) throw new Error(await res.text());
  17987. closeRipInstanceModal();
  17988. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17989. await loadDynamicRouting(false);
  17990. } catch (err) {
  17991. showToast('Error', err.message, 'error');
  17992. }
  17993. }
  17994. async function enableSelectedRipInstance() {
  17995. const id = state.selectedRipRow?.instances;
  17996. if (!id) return;
  17997. if (!await routingMutation(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  17998. await loadDynamicRouting(false);
  17999. }
  18000. async function disableSelectedRipInstance() {
  18001. const id = state.selectedRipRow?.instances;
  18002. if (!id) return;
  18003. if (!await routingMutation(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18004. await loadDynamicRouting(false);
  18005. }
  18006. async function removeSelectedRipInstance() {
  18007. const id = state.selectedRipRow?.instances;
  18008. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  18009. if (!await routingMutation(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' })) return;
  18010. state.selectedRipRow.instances = null;
  18011. await loadDynamicRouting(false);
  18012. }
  18013. function openRipInterfaceModal() {
  18014. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  18015. document.getElementById('modal-rip-iface-id').value = '';
  18016. const dl = document.getElementById('rip-iface-datalist');
  18017. if (dl) {
  18018. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18019. }
  18020. const instSel = document.getElementById('modal-rip-iface-instance');
  18021. if (instSel && instSel.tagName === 'SELECT') {
  18022. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18023. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18024. }
  18025. document.getElementById('modal-rip-iface-pattern').value = '*';
  18026. if (instSel) instSel.value = (state.ripInstances && state.ripInstances.length > 0) ? state.ripInstances[0].name : 'default';
  18027. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  18028. document.getElementById('modal-rip-iface-metric').value = '1';
  18029. document.getElementById('modal-rip-iface-comment').value = '';
  18030. document.getElementById('modal-rip-iface-enabled').checked = true;
  18031. document.getElementById('modal-rip-iface-passive').checked = false;
  18032. document.getElementById('modal-rip-iface-bfd').checked = false;
  18033. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  18034. }
  18035. function openEditRipInterfaceModal(id) {
  18036. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  18037. if (!iface) return;
  18038. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  18039. document.getElementById('modal-rip-iface-id').value = iface.id;
  18040. const dl = document.getElementById('rip-iface-datalist');
  18041. if (dl) {
  18042. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18043. }
  18044. const instSel = document.getElementById('modal-rip-iface-instance');
  18045. if (instSel && instSel.tagName === 'SELECT') {
  18046. instSel.innerHTML = (state.ripInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18047. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  18048. instSel.value = iface.instance || 'default';
  18049. } else if (instSel) {
  18050. instSel.value = iface.instance || '';
  18051. }
  18052. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '*';
  18053. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  18054. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  18055. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  18056. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  18057. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  18058. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  18059. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  18060. }
  18061. function closeRipInterfaceModal() {
  18062. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  18063. }
  18064. async function submitRipInterface(e) {
  18065. e.preventDefault();
  18066. const id = document.getElementById('modal-rip-iface-id').value;
  18067. const payload = {
  18068. id: id || undefined,
  18069. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  18070. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  18071. mode: document.getElementById('modal-rip-iface-mode').value,
  18072. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  18073. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  18074. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  18075. passive: document.getElementById('modal-rip-iface-passive').checked,
  18076. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  18077. };
  18078. try {
  18079. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  18080. method: 'POST',
  18081. headers: { 'Content-Type': 'application/json' },
  18082. body: JSON.stringify(payload)
  18083. });
  18084. if (!res.ok) throw new Error(await res.text());
  18085. closeRipInterfaceModal();
  18086. showToast('Saved', `RIP interface template saved`, 'success');
  18087. await loadDynamicRouting(false);
  18088. } catch (err) {
  18089. showToast('Error', err.message, 'error');
  18090. }
  18091. }
  18092. async function enableSelectedRipInterface() {
  18093. const id = state.selectedRipRow?.interfaces;
  18094. if (!id) return;
  18095. if (!await routingMutation(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18096. await loadDynamicRouting(false);
  18097. }
  18098. async function disableSelectedRipInterface() {
  18099. const id = state.selectedRipRow?.interfaces;
  18100. if (!id) return;
  18101. if (!await routingMutation(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18102. await loadDynamicRouting(false);
  18103. }
  18104. async function removeSelectedRipInterface() {
  18105. const id = state.selectedRipRow?.interfaces;
  18106. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  18107. if (!await routingMutation(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' })) return;
  18108. state.selectedRipRow.interfaces = null;
  18109. await loadDynamicRouting(false);
  18110. }
  18111. // ==============================================================================
  18112. // DYNAMIC ROUTING: BFD MODULE
  18113. // ==============================================================================
  18114. state.bfdInstance = null;
  18115. state.bfdInterfaces = [];
  18116. state.bfdNeighbors = [];
  18117. state.bfdSessions = [];
  18118. state.selectedBfdRow = {};
  18119. state.activeBfdTab = 'config';
  18120. function switchBfdTab(tab) {
  18121. state.activeBfdTab = tab;
  18122. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  18123. const pane = document.getElementById(`bfd-pane-${t}`);
  18124. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  18125. if (pane) {
  18126. if (t === tab) pane.classList.remove('hidden');
  18127. else pane.classList.add('hidden');
  18128. }
  18129. if (btn) {
  18130. if (t === tab) {
  18131. 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';
  18132. } else {
  18133. 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';
  18134. }
  18135. }
  18136. });
  18137. }
  18138. function selectBfdRow(tab, id) {
  18139. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  18140. state.selectedBfdRow[tab] = id;
  18141. if (tab === 'interfaces') {
  18142. renderBfdInterfaces();
  18143. const btnEn = document.getElementById('btn-bfd-iface-enable');
  18144. const btnDis = document.getElementById('btn-bfd-iface-disable');
  18145. const btnRem = document.getElementById('btn-bfd-iface-remove');
  18146. if (btnEn) btnEn.disabled = false;
  18147. if (btnDis) btnDis.disabled = false;
  18148. if (btnRem) btnRem.disabled = false;
  18149. } else if (tab === 'peers') {
  18150. renderBfdPeers();
  18151. const btnEn = document.getElementById('btn-bfd-peer-enable');
  18152. const btnDis = document.getElementById('btn-bfd-peer-disable');
  18153. const btnRem = document.getElementById('btn-bfd-peer-remove');
  18154. if (btnEn) btnEn.disabled = false;
  18155. if (btnDis) btnDis.disabled = false;
  18156. if (btnRem) btnRem.disabled = false;
  18157. }
  18158. }
  18159. function renderBfdConfig() {
  18160. const inst = state.bfdInstance;
  18161. const pill = document.getElementById('bfd-live-status-pill');
  18162. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  18163. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  18164. const peerStat = document.getElementById('bfd-stat-peers');
  18165. const sessStat = document.getElementById('bfd-stat-sessions');
  18166. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  18167. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  18168. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  18169. const isEnabled = inst && (inst.enabled || inst.running || (!inst.disabled && (state.bfdInterfaces || []).length > 0));
  18170. if (!inst || inst.disabled || !isEnabled) {
  18171. if (pill) {
  18172. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  18173. pill.innerText = 'DISABLED';
  18174. }
  18175. if (toggleBtn) {
  18176. toggleBtn.innerText = 'Enable BFD';
  18177. 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';
  18178. }
  18179. } else {
  18180. if (pill) {
  18181. if (inst.running) {
  18182. 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';
  18183. pill.innerText = 'RUNNING (ACTIVE)';
  18184. } else {
  18185. 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';
  18186. pill.innerText = 'CONFIGURED';
  18187. }
  18188. }
  18189. if (toggleBtn) {
  18190. toggleBtn.innerText = 'Disable BFD';
  18191. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  18192. }
  18193. }
  18194. }
  18195. async function toggleBfdGlobalState() {
  18196. const current = state.bfdInstance;
  18197. const isCurrentlyEnabled = current && (current.enabled || current.running) && !current.disabled;
  18198. const newEnabled = !isCurrentlyEnabled;
  18199. const newDisabled = !newEnabled;
  18200. try {
  18201. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  18202. method: 'POST',
  18203. headers: { 'Content-Type': 'application/json' },
  18204. body: JSON.stringify({ enabled: newEnabled, disabled: newDisabled })
  18205. });
  18206. if (!res.ok) throw new Error(await res.text());
  18207. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  18208. await loadDynamicRouting(false);
  18209. } catch (err) {
  18210. showToast('Error', err.message, 'error');
  18211. }
  18212. }
  18213. function renderBfdInterfaces() {
  18214. const tbody = document.getElementById('bfd-interfaces-table-body');
  18215. if (!tbody) return;
  18216. const countEl = document.getElementById('bfd-interfaces-footer-count');
  18217. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  18218. let list = state.bfdInterfaces || [];
  18219. if (filter) {
  18220. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18221. }
  18222. if (countEl) countEl.innerText = list.length;
  18223. const selId = state.selectedBfdRow?.interfaces;
  18224. tbody.innerHTML = list.map((iface, idx) => {
  18225. const isSel = iface.id === selId;
  18226. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18227. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18228. return `
  18229. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  18230. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18231. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18232. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18233. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18234. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  18235. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  18236. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  18237. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  18238. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  18239. </tr>
  18240. `;
  18241. }).join('');
  18242. }
  18243. function renderBfdPeers() {
  18244. const tbody = document.getElementById('bfd-peers-table-body');
  18245. if (!tbody) return;
  18246. const countEl = document.getElementById('bfd-peers-footer-count');
  18247. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  18248. let list = state.bfdNeighbors || [];
  18249. if (filter) {
  18250. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18251. }
  18252. if (countEl) countEl.innerText = list.length;
  18253. const selId = state.selectedBfdRow?.peers;
  18254. tbody.innerHTML = list.map((p, idx) => {
  18255. const isSel = p.id === selId;
  18256. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18257. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18258. return `
  18259. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18260. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18261. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18262. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18263. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18264. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18265. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(p.local_address || 'auto')}</td>
  18266. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18267. </tr>
  18268. `;
  18269. }).join('');
  18270. }
  18271. function renderBfdSessions() {
  18272. const tbody = document.getElementById('bfd-sessions-table-body');
  18273. if (!tbody) return;
  18274. const countEl = document.getElementById('bfd-sessions-footer-count');
  18275. const list = state.bfdSessions || [];
  18276. if (countEl) countEl.innerText = list.length;
  18277. tbody.innerHTML = list.map((s, idx) => {
  18278. const isUp = (s.state || '').toLowerCase() === 'up';
  18279. const stateBadge = isUp
  18280. ? '<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>'
  18281. : `<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>`;
  18282. return `
  18283. <tr class="hover:bg-[#1a2636] text-slate-300">
  18284. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18285. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18286. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18287. <td class="py-1.5 px-3">${stateBadge}</td>
  18288. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18289. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18290. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18291. </tr>
  18292. `;
  18293. }).join('');
  18294. }
  18295. function openBfdInterfaceModal() {
  18296. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18297. document.getElementById('modal-bfd-iface-id').value = '';
  18298. const dl = document.getElementById('bfd-iface-datalist');
  18299. if (dl) {
  18300. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18301. }
  18302. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18303. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18304. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18305. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18306. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18307. document.getElementById('modal-bfd-iface-comment').value = '';
  18308. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18309. document.getElementById('modal-bfd-iface-passive').checked = false;
  18310. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18311. }
  18312. function openEditBfdInterfaceModal(id) {
  18313. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18314. if (!iface) return;
  18315. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18316. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18317. const dl = document.getElementById('bfd-iface-datalist');
  18318. if (dl) {
  18319. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18320. }
  18321. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18322. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18323. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18324. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18325. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18326. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18327. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18328. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18329. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18330. }
  18331. function closeBfdInterfaceModal() {
  18332. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18333. }
  18334. async function submitBfdInterface(e) {
  18335. e.preventDefault();
  18336. const id = document.getElementById('modal-bfd-iface-id').value;
  18337. const payload = {
  18338. id: id || undefined,
  18339. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18340. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18341. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18342. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18343. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18344. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18345. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18346. passive: document.getElementById('modal-bfd-iface-passive').checked
  18347. };
  18348. try {
  18349. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18350. method: 'POST',
  18351. headers: { 'Content-Type': 'application/json' },
  18352. body: JSON.stringify(payload)
  18353. });
  18354. if (!res.ok) throw new Error(await res.text());
  18355. closeBfdInterfaceModal();
  18356. showToast('Saved', `BFD profile saved`, 'success');
  18357. await loadDynamicRouting(false);
  18358. } catch (err) {
  18359. showToast('Error', err.message, 'error');
  18360. }
  18361. }
  18362. async function enableSelectedBfdInterface() {
  18363. const id = state.selectedBfdRow?.interfaces;
  18364. if (!id) return;
  18365. if (!await routingMutation(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18366. await loadDynamicRouting(false);
  18367. }
  18368. async function disableSelectedBfdInterface() {
  18369. const id = state.selectedBfdRow?.interfaces;
  18370. if (!id) return;
  18371. if (!await routingMutation(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18372. await loadDynamicRouting(false);
  18373. }
  18374. async function removeSelectedBfdInterface() {
  18375. const id = state.selectedBfdRow?.interfaces;
  18376. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18377. if (!await routingMutation(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' })) return;
  18378. state.selectedBfdRow.interfaces = null;
  18379. await loadDynamicRouting(false);
  18380. }
  18381. function openBfdPeerModal() {
  18382. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18383. document.getElementById('modal-bfd-peer-id').value = '';
  18384. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18385. if (dlPeer) {
  18386. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18387. }
  18388. document.getElementById('modal-bfd-peer-address').value = '';
  18389. document.getElementById('modal-bfd-peer-interface').value = '';
  18390. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18391. if (localAddrEl) localAddrEl.value = '';
  18392. document.getElementById('modal-bfd-peer-comment').value = '';
  18393. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18394. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18395. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18396. }
  18397. function openEditBfdPeerModal(id) {
  18398. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18399. if (!p) return;
  18400. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18401. document.getElementById('modal-bfd-peer-id').value = p.id;
  18402. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18403. if (dlPeer) {
  18404. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18405. }
  18406. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18407. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18408. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18409. if (localAddrEl) localAddrEl.value = p.local_address || '';
  18410. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18411. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18412. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18413. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18414. }
  18415. function closeBfdPeerModal() {
  18416. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18417. }
  18418. async function submitBfdPeer(e) {
  18419. e.preventDefault();
  18420. const id = document.getElementById('modal-bfd-peer-id').value;
  18421. const localAddr = document.getElementById('modal-bfd-peer-local-address')?.value.trim() || '';
  18422. const payload = {
  18423. id: id || undefined,
  18424. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18425. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18426. local_address: localAddr,
  18427. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18428. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18429. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18430. };
  18431. try {
  18432. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18433. method: 'POST',
  18434. headers: { 'Content-Type': 'application/json' },
  18435. body: JSON.stringify(payload)
  18436. });
  18437. if (!res.ok) throw new Error(await res.text());
  18438. closeBfdPeerModal();
  18439. showToast('Saved', `BFD peer saved`, 'success');
  18440. await loadDynamicRouting(false);
  18441. } catch (err) {
  18442. showToast('Error', err.message, 'error');
  18443. }
  18444. }
  18445. async function enableSelectedBfdPeer() {
  18446. const id = state.selectedBfdRow?.peers;
  18447. if (!id) return;
  18448. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18449. if (!p) return;
  18450. if (!await routingMutation(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) })) return;
  18451. await loadDynamicRouting(false);
  18452. }
  18453. async function disableSelectedBfdPeer() {
  18454. const id = state.selectedBfdRow?.peers;
  18455. if (!id) return;
  18456. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18457. if (!p) return;
  18458. if (!await routingMutation(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) })) return;
  18459. await loadDynamicRouting(false);
  18460. }
  18461. async function removeSelectedBfdPeer() {
  18462. const id = state.selectedBfdRow?.peers;
  18463. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18464. if (!await routingMutation(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' })) return;
  18465. state.selectedBfdRow.peers = null;
  18466. await loadDynamicRouting(false);
  18467. }
  18468. // ==============================================================================
  18469. // DYNAMIC ROUTING: BABEL MODULE
  18470. // ==============================================================================
  18471. state.babelInstances = [];
  18472. state.babelInterfaces = [];
  18473. state.babelInterfacesLive = [];
  18474. state.babelNeighbors = [];
  18475. state.babelRoutes = [];
  18476. state.selectedBabelRow = {};
  18477. state.activeBabelTab = 'instances';
  18478. function switchBabelTab(tab) {
  18479. state.activeBabelTab = tab;
  18480. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18481. const pane = document.getElementById(`babel-pane-${t}`);
  18482. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18483. if (pane) {
  18484. if (t === tab) pane.classList.remove('hidden');
  18485. else pane.classList.add('hidden');
  18486. }
  18487. if (btn) {
  18488. if (t === tab) {
  18489. 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';
  18490. } else {
  18491. 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';
  18492. }
  18493. }
  18494. });
  18495. }
  18496. function selectBabelRow(tab, id) {
  18497. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18498. state.selectedBabelRow[tab] = id;
  18499. if (tab === 'instances') {
  18500. renderBabelInstances();
  18501. const btnEn = document.getElementById('btn-babel-inst-enable');
  18502. const btnDis = document.getElementById('btn-babel-inst-disable');
  18503. const btnRem = document.getElementById('btn-babel-inst-remove');
  18504. if (btnEn) btnEn.disabled = false;
  18505. if (btnDis) btnDis.disabled = false;
  18506. if (btnRem) btnRem.disabled = false;
  18507. } else if (tab === 'interfaces') {
  18508. renderBabelInterfaces();
  18509. const btnEn = document.getElementById('btn-babel-iface-enable');
  18510. const btnDis = document.getElementById('btn-babel-iface-disable');
  18511. const btnRem = document.getElementById('btn-babel-iface-remove');
  18512. if (btnEn) btnEn.disabled = false;
  18513. if (btnDis) btnDis.disabled = false;
  18514. if (btnRem) btnRem.disabled = false;
  18515. }
  18516. }
  18517. function renderBabelInstances() {
  18518. const tbody = document.getElementById('babel-instances-table-body');
  18519. if (!tbody) return;
  18520. const countEl = document.getElementById('babel-instances-footer-count');
  18521. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18522. let list = state.babelInstances || [];
  18523. if (filter) {
  18524. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18525. }
  18526. if (countEl) countEl.innerText = list.length;
  18527. const selId = state.selectedBabelRow?.instances;
  18528. tbody.innerHTML = list.map((inst, idx) => {
  18529. const isSel = inst.id === selId;
  18530. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18531. const flagD = inst.disabled
  18532. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18533. : (inst.running
  18534. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18535. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18536. const redist = [];
  18537. if (inst.redistribute_connected) redist.push('conn');
  18538. if (inst.redistribute_static) redist.push('static');
  18539. if (inst.redistribute_bgp) redist.push('bgp');
  18540. if (inst.redistribute_ospf) redist.push('ospf');
  18541. if (inst.redistribute_default) redist.push('default');
  18542. const filterBadges = [];
  18543. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  18544. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  18545. return `
  18546. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18547. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18548. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18549. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18550. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18551. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18552. ${filterBadges.join(' ')}
  18553. </td>
  18554. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18555. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18556. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18557. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18558. </tr>
  18559. `;
  18560. }).join('');
  18561. }
  18562. function renderBabelInterfaces() {
  18563. const tbody = document.getElementById('babel-interfaces-table-body');
  18564. if (!tbody) return;
  18565. const countEl = document.getElementById('babel-interfaces-footer-count');
  18566. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18567. let list = state.babelInterfaces || [];
  18568. if (filter) {
  18569. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18570. }
  18571. if (countEl) countEl.innerText = list.length;
  18572. const selId = state.selectedBabelRow?.interfaces;
  18573. tbody.innerHTML = list.map((iface, idx) => {
  18574. const isSel = iface.id === selId;
  18575. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18576. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18577. return `
  18578. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18579. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18580. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18581. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18582. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18583. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18584. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18585. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18586. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18587. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18588. </tr>
  18589. `;
  18590. }).join('');
  18591. }
  18592. function renderBabelLiveInterfaces() {
  18593. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18594. if (!tbody) return;
  18595. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18596. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18597. let list = state.babelInterfacesLive || [];
  18598. if (filter) {
  18599. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18600. }
  18601. if (countEl) countEl.innerText = list.length;
  18602. tbody.innerHTML = list.map((iface, idx) => {
  18603. const isUp = (iface.state || '').toLowerCase() === 'up';
  18604. const stateBadge = isUp
  18605. ? '<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>'
  18606. : '<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>';
  18607. return `
  18608. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18609. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18610. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18611. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18612. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18613. <td class="py-1.5 px-3">${stateBadge}</td>
  18614. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18615. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18616. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18617. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18618. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18619. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18620. </tr>
  18621. `;
  18622. }).join('');
  18623. }
  18624. function renderBabelNeighbors() {
  18625. const tbody = document.getElementById('babel-neighbors-table-body');
  18626. if (!tbody) return;
  18627. const countEl = document.getElementById('babel-neighbors-footer-count');
  18628. const list = state.babelNeighbors || [];
  18629. if (countEl) countEl.innerText = list.length;
  18630. tbody.innerHTML = list.map((nbr, idx) => `
  18631. <tr class="hover:bg-[#1a2636] text-slate-300">
  18632. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18633. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18634. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18635. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18636. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18637. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18638. </tr>
  18639. `).join('');
  18640. }
  18641. function renderBabelRoutes() {
  18642. const tbody = document.getElementById('babel-routes-table-body');
  18643. if (!tbody) return;
  18644. const countEl = document.getElementById('babel-routes-footer-count');
  18645. const list = state.babelRoutes || [];
  18646. if (countEl) countEl.innerText = list.length;
  18647. tbody.innerHTML = list.map((r, idx) => `
  18648. <tr class="hover:bg-[#1a2636] text-slate-300">
  18649. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18650. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18651. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18652. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18653. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18654. </tr>
  18655. `).join('');
  18656. }
  18657. function openBabelInstanceModal() {
  18658. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18659. document.getElementById('modal-babel-instance-id').value = '';
  18660. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18661. document.getElementById('modal-babel-instance-routerid').value = '';
  18662. document.getElementById('modal-babel-instance-metric').value = '10';
  18663. document.getElementById('modal-babel-instance-comment').value = '';
  18664. document.getElementById('modal-babel-instance-in-filter').value = '';
  18665. document.getElementById('modal-babel-instance-out-filter').value = '';
  18666. document.getElementById('modal-babel-instance-enabled').checked = true;
  18667. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18668. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18669. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18670. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18671. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18672. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18673. }
  18674. function openEditBabelInstanceModal(id) {
  18675. const inst = (state.babelInstances || []).find(i => i.id === id);
  18676. if (!inst) return;
  18677. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18678. document.getElementById('modal-babel-instance-id').value = inst.id;
  18679. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18680. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18681. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18682. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18683. document.getElementById('modal-babel-instance-in-filter').value = inst.in_filter || '';
  18684. document.getElementById('modal-babel-instance-out-filter').value = inst.out_filter || '';
  18685. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18686. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18687. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18688. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18689. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18690. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18691. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18692. }
  18693. function closeBabelInstanceModal() {
  18694. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18695. }
  18696. async function submitBabelInstance(e) {
  18697. e.preventDefault();
  18698. const id = document.getElementById('modal-babel-instance-id').value;
  18699. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18700. const payload = {
  18701. id: id || undefined,
  18702. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18703. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18704. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18705. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18706. in_filter: (document.getElementById('modal-babel-instance-in-filter')?.value || '').trim(),
  18707. out_filter: (document.getElementById('modal-babel-instance-out-filter')?.value || '').trim(),
  18708. enabled: isEnabled,
  18709. disabled: !isEnabled,
  18710. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18711. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18712. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18713. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18714. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18715. };
  18716. try {
  18717. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18718. method: 'POST',
  18719. headers: { 'Content-Type': 'application/json' },
  18720. body: JSON.stringify(payload)
  18721. });
  18722. if (!res.ok) throw new Error(await res.text());
  18723. closeBabelInstanceModal();
  18724. showToast('Saved', `Babel instance saved`, 'success');
  18725. await loadDynamicRouting(false);
  18726. } catch (err) {
  18727. showToast('Error', err.message, 'error');
  18728. }
  18729. }
  18730. async function enableSelectedBabelInstance() {
  18731. const id = state.selectedBabelRow?.instances;
  18732. if (!id) return;
  18733. if (!await routingMutation(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18734. await loadDynamicRouting(false);
  18735. }
  18736. async function disableSelectedBabelInstance() {
  18737. const id = state.selectedBabelRow?.instances;
  18738. if (!id) return;
  18739. if (!await routingMutation(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18740. await loadDynamicRouting(false);
  18741. }
  18742. async function removeSelectedBabelInstance() {
  18743. const id = state.selectedBabelRow?.instances;
  18744. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18745. if (!await routingMutation(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' })) return;
  18746. state.selectedBabelRow.instances = null;
  18747. await loadDynamicRouting(false);
  18748. }
  18749. function toggleBabelAuthKey() {
  18750. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18751. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18752. if (wrap) {
  18753. if (authVal === 'mac') wrap.classList.remove('hidden');
  18754. else wrap.classList.add('hidden');
  18755. }
  18756. }
  18757. function openBabelInterfaceModal() {
  18758. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18759. document.getElementById('modal-babel-iface-id').value = '';
  18760. const instSel = document.getElementById('modal-babel-iface-instance');
  18761. if (instSel) {
  18762. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18763. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18764. if (state.babelInstances && state.babelInstances.length > 0) {
  18765. instSel.value = state.babelInstances[0].name;
  18766. }
  18767. }
  18768. const dl = document.getElementById('babel-iface-datalist');
  18769. if (dl) {
  18770. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18771. }
  18772. document.getElementById('modal-babel-iface-pattern').value = '*';
  18773. document.getElementById('modal-babel-iface-type').value = 'wired';
  18774. document.getElementById('modal-babel-iface-auth').value = 'none';
  18775. document.getElementById('modal-babel-iface-auth-key').value = '';
  18776. toggleBabelAuthKey();
  18777. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18778. document.getElementById('modal-babel-iface-hello').value = '4';
  18779. document.getElementById('modal-babel-iface-update').value = '16';
  18780. document.getElementById('modal-babel-iface-comment').value = '';
  18781. document.getElementById('modal-babel-iface-enabled').checked = true;
  18782. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18783. }
  18784. function openEditBabelInterfaceModal(id) {
  18785. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18786. if (!iface) return;
  18787. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18788. document.getElementById('modal-babel-iface-id').value = iface.id;
  18789. const instSel = document.getElementById('modal-babel-iface-instance');
  18790. if (instSel) {
  18791. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18792. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18793. instSel.value = iface.instance || 'all';
  18794. }
  18795. const dl = document.getElementById('babel-iface-datalist');
  18796. if (dl) {
  18797. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18798. }
  18799. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18800. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18801. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18802. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18803. toggleBabelAuthKey();
  18804. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18805. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18806. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18807. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18808. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18809. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18810. }
  18811. function closeBabelInterfaceModal() {
  18812. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18813. }
  18814. async function submitBabelInterface(e) {
  18815. e.preventDefault();
  18816. const id = document.getElementById('modal-babel-iface-id').value;
  18817. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18818. const payload = {
  18819. id: id || undefined,
  18820. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18821. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18822. type: document.getElementById('modal-babel-iface-type').value,
  18823. auth: document.getElementById('modal-babel-iface-auth').value,
  18824. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18825. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18826. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18827. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18828. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18829. disabled: !isEnabled
  18830. };
  18831. try {
  18832. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18833. method: 'POST',
  18834. headers: { 'Content-Type': 'application/json' },
  18835. body: JSON.stringify(payload)
  18836. });
  18837. if (!res.ok) throw new Error(await res.text());
  18838. closeBabelInterfaceModal();
  18839. showToast('Saved', `Babel interface template saved`, 'success');
  18840. await loadDynamicRouting(false);
  18841. } catch (err) {
  18842. showToast('Error', err.message, 'error');
  18843. }
  18844. }
  18845. async function enableSelectedBabelInterface() {
  18846. const id = state.selectedBabelRow?.interfaces;
  18847. if (!id) return;
  18848. if (!await routingMutation(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  18849. await loadDynamicRouting(false);
  18850. }
  18851. async function disableSelectedBabelInterface() {
  18852. const id = state.selectedBabelRow?.interfaces;
  18853. if (!id) return;
  18854. if (!await routingMutation(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  18855. await loadDynamicRouting(false);
  18856. }
  18857. async function removeSelectedBabelInterface() {
  18858. const id = state.selectedBabelRow?.interfaces;
  18859. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18860. if (!await routingMutation(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' })) return;
  18861. state.selectedBabelRow.interfaces = null;
  18862. await loadDynamicRouting(false);
  18863. }
  18864. // ==============================================================================
  18865. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18866. // ==============================================================================
  18867. state.radvInstances = [];
  18868. state.radvInterfaces = [];
  18869. state.selectedRadvRow = {};
  18870. state.activeRadvTab = 'instances';
  18871. function switchRadvTab(tab) {
  18872. state.activeRadvTab = tab;
  18873. ['instances', 'interfaces'].forEach(t => {
  18874. const pane = document.getElementById(`radv-pane-${t}`);
  18875. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18876. if (pane) {
  18877. if (t === tab) pane.classList.remove('hidden');
  18878. else pane.classList.add('hidden');
  18879. }
  18880. if (btn) {
  18881. if (t === tab) {
  18882. 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';
  18883. } else {
  18884. 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';
  18885. }
  18886. }
  18887. });
  18888. }
  18889. function selectRadvRow(tab, id) {
  18890. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18891. state.selectedRadvRow[tab] = id;
  18892. if (tab === 'instances') {
  18893. renderRAdvInstances();
  18894. const btnEn = document.getElementById('btn-radv-inst-enable');
  18895. const btnDis = document.getElementById('btn-radv-inst-disable');
  18896. const btnRem = document.getElementById('btn-radv-inst-remove');
  18897. if (btnEn) btnEn.disabled = false;
  18898. if (btnDis) btnDis.disabled = false;
  18899. if (btnRem) btnRem.disabled = false;
  18900. } else if (tab === 'interfaces') {
  18901. renderRAdvInterfaces();
  18902. const btnEn = document.getElementById('btn-radv-iface-enable');
  18903. const btnDis = document.getElementById('btn-radv-iface-disable');
  18904. const btnRem = document.getElementById('btn-radv-iface-remove');
  18905. if (btnEn) btnEn.disabled = false;
  18906. if (btnDis) btnDis.disabled = false;
  18907. if (btnRem) btnRem.disabled = false;
  18908. }
  18909. }
  18910. function renderRAdvInstances() {
  18911. const tbody = document.getElementById('radv-instances-table-body');
  18912. if (!tbody) return;
  18913. const countEl = document.getElementById('radv-instances-footer-count');
  18914. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18915. let list = state.radvInstances || [];
  18916. if (filter) {
  18917. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18918. }
  18919. if (countEl) countEl.innerText = list.length;
  18920. const selId = state.selectedRadvRow?.instances;
  18921. tbody.innerHTML = list.map((inst, idx) => {
  18922. const isSel = inst.id === selId;
  18923. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18924. const flagD = inst.disabled
  18925. ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>'
  18926. : (inst.running
  18927. ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>'
  18928. : '<span class="text-amber-400 font-bold" title="Inactive (I)">I</span>');
  18929. return `
  18930. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18931. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18932. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18933. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18934. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18935. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18936. </td>
  18937. <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>
  18938. </tr>
  18939. `;
  18940. }).join('');
  18941. }
  18942. function renderRAdvInterfaces() {
  18943. const tbody = document.getElementById('radv-interfaces-table-body');
  18944. if (!tbody) return;
  18945. const countEl = document.getElementById('radv-interfaces-footer-count');
  18946. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18947. let list = state.radvInterfaces || [];
  18948. if (filter) {
  18949. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18950. }
  18951. if (countEl) countEl.innerText = list.length;
  18952. const selId = state.selectedRadvRow?.interfaces;
  18953. tbody.innerHTML = list.map((iface, idx) => {
  18954. const isSel = iface.id === selId;
  18955. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18956. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18957. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18958. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18959. return `
  18960. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18961. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18962. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18963. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18964. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18965. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18966. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18967. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18968. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18969. </tr>
  18970. `;
  18971. }).join('');
  18972. }
  18973. function openRAdvInstanceModal() {
  18974. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18975. document.getElementById('modal-radv-instance-id').value = '';
  18976. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18977. document.getElementById('modal-radv-instance-comment').value = '';
  18978. document.getElementById('modal-radv-instance-enabled').checked = true;
  18979. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18980. }
  18981. function openEditRAdvInstanceModal(id) {
  18982. const inst = (state.radvInstances || []).find(i => i.id === id);
  18983. if (!inst) return;
  18984. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18985. document.getElementById('modal-radv-instance-id').value = inst.id;
  18986. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18987. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18988. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18989. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18990. }
  18991. function closeRAdvInstanceModal() {
  18992. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18993. }
  18994. async function submitRAdvInstance(e) {
  18995. e.preventDefault();
  18996. const id = document.getElementById('modal-radv-instance-id').value;
  18997. const payload = {
  18998. id: id || undefined,
  18999. name: document.getElementById('modal-radv-instance-name').value.trim(),
  19000. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  19001. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  19002. };
  19003. try {
  19004. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  19005. method: 'POST',
  19006. headers: { 'Content-Type': 'application/json' },
  19007. body: JSON.stringify(payload)
  19008. });
  19009. if (!res.ok) throw new Error(await res.text());
  19010. closeRAdvInstanceModal();
  19011. showToast('Saved', `RAdv instance saved`, 'success');
  19012. await loadDynamicRouting(false);
  19013. } catch (err) {
  19014. showToast('Error', err.message, 'error');
  19015. }
  19016. }
  19017. async function enableSelectedRadvInstance() {
  19018. const id = state.selectedRadvRow?.instances;
  19019. if (!id) return;
  19020. if (!await routingMutation(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19021. await loadDynamicRouting(false);
  19022. }
  19023. async function disableSelectedRadvInstance() {
  19024. const id = state.selectedRadvRow?.instances;
  19025. if (!id) return;
  19026. if (!await routingMutation(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19027. await loadDynamicRouting(false);
  19028. }
  19029. async function removeSelectedRadvInstance() {
  19030. const id = state.selectedRadvRow?.instances;
  19031. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  19032. if (!await routingMutation(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' })) return;
  19033. state.selectedRadvRow.instances = null;
  19034. await loadDynamicRouting(false);
  19035. }
  19036. function openRAdvInterfaceModal() {
  19037. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  19038. document.getElementById('modal-radv-iface-id').value = '';
  19039. const dl = document.getElementById('radv-iface-datalist');
  19040. if (dl) {
  19041. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19042. }
  19043. const instSel = document.getElementById('modal-radv-iface-instance');
  19044. if (instSel && instSel.tagName === 'SELECT') {
  19045. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  19046. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  19047. instSel.value = (state.radvInstances && state.radvInstances.length > 0) ? state.radvInstances[0].name : 'default';
  19048. } else if (instSel) {
  19049. instSel.value = 'default';
  19050. }
  19051. document.getElementById('modal-radv-iface-interface').value = '*';
  19052. document.getElementById('modal-radv-iface-min-ra').value = '200';
  19053. document.getElementById('modal-radv-iface-max-ra').value = '600';
  19054. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  19055. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  19056. document.getElementById('modal-radv-iface-prefixes').value = '';
  19057. document.getElementById('modal-radv-iface-rdnss').value = '';
  19058. document.getElementById('modal-radv-iface-comment').value = '';
  19059. document.getElementById('modal-radv-iface-enabled').checked = true;
  19060. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  19061. }
  19062. function openEditRAdvInterfaceModal(id) {
  19063. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  19064. if (!iface) return;
  19065. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  19066. document.getElementById('modal-radv-iface-id').value = iface.id;
  19067. const dl = document.getElementById('radv-iface-datalist');
  19068. if (dl) {
  19069. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19070. }
  19071. const instSel = document.getElementById('modal-radv-iface-instance');
  19072. if (instSel && instSel.tagName === 'SELECT') {
  19073. instSel.innerHTML = (state.radvInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  19074. if (instSel.innerHTML === '') instSel.innerHTML = '<option value="default">default</option>';
  19075. instSel.value = iface.instance || 'default';
  19076. } else if (instSel) {
  19077. instSel.value = iface.instance || '';
  19078. }
  19079. document.getElementById('modal-radv-iface-interface').value = iface.interface || '*';
  19080. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  19081. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  19082. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  19083. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  19084. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  19085. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  19086. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  19087. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  19088. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  19089. }
  19090. function closeRAdvInterfaceModal() {
  19091. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  19092. }
  19093. async function submitRAdvInterface(e) {
  19094. e.preventDefault();
  19095. const id = document.getElementById('modal-radv-iface-id').value;
  19096. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  19097. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  19098. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  19099. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  19100. const payload = {
  19101. id: id || undefined,
  19102. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  19103. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  19104. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  19105. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  19106. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  19107. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  19108. prefixes: prefixes,
  19109. rdnss: rdnss,
  19110. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  19111. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  19112. };
  19113. try {
  19114. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  19115. method: 'POST',
  19116. headers: { 'Content-Type': 'application/json' },
  19117. body: JSON.stringify(payload)
  19118. });
  19119. if (!res.ok) throw new Error(await res.text());
  19120. closeRAdvInterfaceModal();
  19121. showToast('Saved', `RAdv interface saved`, 'success');
  19122. await loadDynamicRouting(false);
  19123. } catch (err) {
  19124. showToast('Error', err.message, 'error');
  19125. }
  19126. }
  19127. async function enableSelectedRadvInterface() {
  19128. const id = state.selectedRadvRow?.interfaces;
  19129. if (!id) return;
  19130. if (!await routingMutation(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19131. await loadDynamicRouting(false);
  19132. }
  19133. async function disableSelectedRadvInterface() {
  19134. const id = state.selectedRadvRow?.interfaces;
  19135. if (!id) return;
  19136. if (!await routingMutation(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19137. await loadDynamicRouting(false);
  19138. }
  19139. async function removeSelectedRadvInterface() {
  19140. const id = state.selectedRadvRow?.interfaces;
  19141. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  19142. if (!await routingMutation(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' })) return;
  19143. state.selectedRadvRow.interfaces = null;
  19144. await loadDynamicRouting(false);
  19145. }
  19146. // ================= EIGRP ROUTING CONTROLLER =================
  19147. state.selectedEigrpRow = { instances: null, networks: null, interfaces: null };
  19148. function switchEigrpTab(tab) {
  19149. state.activeEigrpTab = tab;
  19150. const tabs = ['instances', 'networks', 'interfaces', 'neighbors', 'topology'];
  19151. tabs.forEach(t => {
  19152. const btn = document.getElementById(`eigrp-tab-btn-${t}`);
  19153. const pane = document.getElementById(`eigrp-pane-${t}`);
  19154. if (btn) {
  19155. if (t === tab) {
  19156. 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';
  19157. } else {
  19158. 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';
  19159. }
  19160. }
  19161. if (pane) {
  19162. if (t === tab) pane.classList.remove('hidden');
  19163. else pane.classList.add('hidden');
  19164. }
  19165. });
  19166. const dlIface = document.getElementById('eigrp-iface-datalist');
  19167. if (dlIface && state.interfaces) {
  19168. dlIface.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19169. }
  19170. const dlNet = document.getElementById('eigrp-net-datalist');
  19171. if (dlNet && state.interfaces) {
  19172. const cidrs = [];
  19173. state.interfaces.forEach(i => {
  19174. (i.addrs || []).forEach(a => {
  19175. if (a.includes('.') && a.includes('/')) cidrs.push(a);
  19176. });
  19177. });
  19178. dlNet.innerHTML = '<option value="0.0.0.0/0">' + cidrs.map(c => `<option value="${escapeHtml(c)}">`).join('');
  19179. }
  19180. }
  19181. function selectEigrpRow(kind, id) {
  19182. if (!state.selectedEigrpRow) state.selectedEigrpRow = {};
  19183. if (state.selectedEigrpRow[kind] === id) {
  19184. state.selectedEigrpRow[kind] = null;
  19185. } else {
  19186. state.selectedEigrpRow[kind] = id;
  19187. }
  19188. if (kind === 'instances') {
  19189. renderEigrpInstances();
  19190. const isSel = !!state.selectedEigrpRow.instances;
  19191. const btnEn = document.getElementById('btn-eigrp-inst-enable');
  19192. const btnDis = document.getElementById('btn-eigrp-inst-disable');
  19193. const btnRem = document.getElementById('btn-eigrp-inst-remove');
  19194. if (btnEn) btnEn.disabled = !isSel;
  19195. if (btnDis) btnDis.disabled = !isSel;
  19196. if (btnRem) btnRem.disabled = !isSel;
  19197. } else if (kind === 'networks') {
  19198. renderEigrpNetworks();
  19199. const isSel = !!state.selectedEigrpRow.networks;
  19200. const btnRem = document.getElementById('btn-eigrp-net-remove');
  19201. if (btnRem) btnRem.disabled = !isSel;
  19202. } else if (kind === 'interfaces') {
  19203. renderEigrpInterfaces();
  19204. const isSel = !!state.selectedEigrpRow.interfaces;
  19205. const btnEn = document.getElementById('btn-eigrp-iface-enable');
  19206. const btnDis = document.getElementById('btn-eigrp-iface-disable');
  19207. const btnRem = document.getElementById('btn-eigrp-iface-remove');
  19208. if (btnEn) btnEn.disabled = !isSel;
  19209. if (btnDis) btnDis.disabled = !isSel;
  19210. if (btnRem) btnRem.disabled = !isSel;
  19211. }
  19212. }
  19213. // --- EIGRP INSTANCES ---
  19214. function renderEigrpInstances() {
  19215. const tbody = document.getElementById('eigrp-instances-table-body');
  19216. if (!tbody) return;
  19217. const countEl = document.getElementById('eigrp-instances-footer-count');
  19218. const filter = (document.getElementById('filter-eigrp-instances')?.value || '').toLowerCase();
  19219. let list = state.eigrpInstances || [];
  19220. if (filter) {
  19221. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || String(i.as || '').includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19222. }
  19223. if (countEl) countEl.innerText = list.length;
  19224. const selId = state.selectedEigrpRow?.instances;
  19225. tbody.innerHTML = list.map((inst, idx) => {
  19226. const isSel = inst.id === selId;
  19227. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19228. const flagD = inst.disabled
  19229. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  19230. : (inst.running
  19231. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  19232. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  19233. const redist = [];
  19234. if (inst.redistribute_connected) redist.push('conn');
  19235. if (inst.redistribute_static) redist.push('static');
  19236. if (inst.redistribute_ospf) redist.push('ospf');
  19237. if (inst.redistribute_bgp) redist.push('bgp');
  19238. const filterBadges = [];
  19239. if (inst.in_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(inst.in_filter)}</span>`);
  19240. if (inst.out_filter) filterBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/50" title="Out Filter">OUT: ${escapeHtml(inst.out_filter)}</span>`);
  19241. return `
  19242. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('instances', '${inst.id}')" ondblclick="openEditEigrpInstanceModal('${inst.id}')">
  19243. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19244. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19245. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  19246. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  19247. <span class="text-purple-400">⚡</span> <span>${escapeHtml(inst.name || 'default')}</span>
  19248. ${filterBadges.join(' ')}
  19249. </td>
  19250. <td class="py-1.5 px-3 font-mono text-purple-300 font-bold">${inst.as || 100}</td>
  19251. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  19252. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  19253. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.variance || 1}</td>
  19254. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.max_paths || 4}</td>
  19255. </tr>
  19256. `;
  19257. }).join('');
  19258. }
  19259. function openEigrpInstanceModal() {
  19260. document.getElementById('eigrp-instance-modal-title').innerText = 'Add EIGRP Instance';
  19261. document.getElementById('modal-eigrp-instance-id').value = '';
  19262. document.getElementById('modal-eigrp-instance-name').value = 'eigrp' + ((state.eigrpInstances || []).length + 1);
  19263. document.getElementById('modal-eigrp-instance-as').value = '100';
  19264. document.getElementById('modal-eigrp-instance-routerid').value = '';
  19265. document.getElementById('modal-eigrp-instance-comment').value = '';
  19266. document.getElementById('modal-eigrp-instance-in-filter').value = '';
  19267. document.getElementById('modal-eigrp-instance-out-filter').value = '';
  19268. document.getElementById('modal-eigrp-instance-variance').value = '1';
  19269. document.getElementById('modal-eigrp-instance-maxpaths').value = '4';
  19270. document.getElementById('modal-eigrp-instance-metric').value = '10000';
  19271. document.getElementById('modal-eigrp-instance-redist-conn').checked = false;
  19272. document.getElementById('modal-eigrp-instance-redist-static').checked = false;
  19273. document.getElementById('modal-eigrp-instance-redist-ospf').checked = false;
  19274. document.getElementById('modal-eigrp-instance-redist-bgp').checked = false;
  19275. document.getElementById('modal-eigrp-instance-enabled').checked = true;
  19276. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19277. }
  19278. function openEditEigrpInstanceModal(id) {
  19279. const inst = (state.eigrpInstances || []).find(i => i.id === id);
  19280. if (!inst) return;
  19281. document.getElementById('eigrp-instance-modal-title').innerText = `Edit EIGRP Instance: ${inst.name}`;
  19282. document.getElementById('modal-eigrp-instance-id').value = inst.id;
  19283. document.getElementById('modal-eigrp-instance-name').value = inst.name || '';
  19284. document.getElementById('modal-eigrp-instance-as').value = inst.as || 100;
  19285. document.getElementById('modal-eigrp-instance-routerid').value = inst.router_id || '';
  19286. document.getElementById('modal-eigrp-instance-comment').value = inst.comment || '';
  19287. document.getElementById('modal-eigrp-instance-in-filter').value = inst.in_filter || '';
  19288. document.getElementById('modal-eigrp-instance-out-filter').value = inst.out_filter || '';
  19289. document.getElementById('modal-eigrp-instance-variance').value = inst.variance || 1;
  19290. document.getElementById('modal-eigrp-instance-maxpaths').value = inst.max_paths || 4;
  19291. document.getElementById('modal-eigrp-instance-metric').value = inst.default_metric || 10000;
  19292. document.getElementById('modal-eigrp-instance-redist-conn').checked = !!inst.redistribute_connected;
  19293. document.getElementById('modal-eigrp-instance-redist-static').checked = !!inst.redistribute_static;
  19294. document.getElementById('modal-eigrp-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  19295. document.getElementById('modal-eigrp-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  19296. document.getElementById('modal-eigrp-instance-enabled').checked = !inst.disabled;
  19297. document.getElementById('eigrp-instance-modal')?.classList.remove('hidden');
  19298. }
  19299. function closeEigrpInstanceModal() {
  19300. document.getElementById('eigrp-instance-modal')?.classList.add('hidden');
  19301. }
  19302. async function submitEigrpInstance(e) {
  19303. e.preventDefault();
  19304. const payload = {
  19305. id: document.getElementById('modal-eigrp-instance-id').value.trim() || undefined,
  19306. name: document.getElementById('modal-eigrp-instance-name').value.trim(),
  19307. as: parseInt(document.getElementById('modal-eigrp-instance-as').value, 10) || 100,
  19308. router_id: document.getElementById('modal-eigrp-instance-routerid').value.trim(),
  19309. comment: document.getElementById('modal-eigrp-instance-comment').value.trim(),
  19310. in_filter: (document.getElementById('modal-eigrp-instance-in-filter')?.value || '').trim(),
  19311. out_filter: (document.getElementById('modal-eigrp-instance-out-filter')?.value || '').trim(),
  19312. variance: parseInt(document.getElementById('modal-eigrp-instance-variance').value, 10) || 1,
  19313. max_paths: parseInt(document.getElementById('modal-eigrp-instance-maxpaths').value, 10) || 4,
  19314. default_metric: parseInt(document.getElementById('modal-eigrp-instance-metric').value, 10) || 10000,
  19315. redistribute_connected: document.getElementById('modal-eigrp-instance-redist-conn').checked,
  19316. redistribute_static: document.getElementById('modal-eigrp-instance-redist-static').checked,
  19317. redistribute_ospf: document.getElementById('modal-eigrp-instance-redist-ospf').checked,
  19318. redistribute_bgp: document.getElementById('modal-eigrp-instance-redist-bgp').checked,
  19319. disabled: !document.getElementById('modal-eigrp-instance-enabled').checked
  19320. };
  19321. try {
  19322. const res = await fetch(`${API_BASE}/routing/eigrp/instances`, {
  19323. method: 'POST',
  19324. headers: { 'Content-Type': 'application/json' },
  19325. body: JSON.stringify(payload)
  19326. });
  19327. if (!res.ok) throw new Error(await res.text());
  19328. closeEigrpInstanceModal();
  19329. showToast('Saved', `EIGRP instance saved`, 'success');
  19330. await loadDynamicRouting(false);
  19331. } catch (err) {
  19332. showToast('Error', err.message, 'error');
  19333. }
  19334. }
  19335. async function enableSelectedEigrpInstance() {
  19336. const id = state.selectedEigrpRow?.instances;
  19337. if (!id) return;
  19338. if (!await routingMutation(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19339. await loadDynamicRouting(false);
  19340. }
  19341. async function disableSelectedEigrpInstance() {
  19342. const id = state.selectedEigrpRow?.instances;
  19343. if (!id) return;
  19344. if (!await routingMutation(`${API_BASE}/routing/eigrp/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19345. await loadDynamicRouting(false);
  19346. }
  19347. async function removeSelectedEigrpInstance() {
  19348. const id = state.selectedEigrpRow?.instances;
  19349. if (!id || !confirm('Are you sure you want to remove this EIGRP instance?')) return;
  19350. if (!await routingMutation(`${API_BASE}/routing/eigrp/instances/${id}`, { method: 'DELETE' })) return;
  19351. state.selectedEigrpRow.instances = null;
  19352. await loadDynamicRouting(false);
  19353. }
  19354. // --- EIGRP NETWORKS ---
  19355. function renderEigrpNetworks() {
  19356. const tbody = document.getElementById('eigrp-networks-table-body');
  19357. if (!tbody) return;
  19358. const countEl = document.getElementById('eigrp-networks-footer-count');
  19359. const filter = (document.getElementById('filter-eigrp-networks')?.value || '').toLowerCase();
  19360. let list = state.eigrpNetworks || [];
  19361. if (filter) {
  19362. list = list.filter(n => (n.network || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  19363. }
  19364. if (countEl) countEl.innerText = list.length;
  19365. const selId = state.selectedEigrpRow?.networks;
  19366. tbody.innerHTML = list.map((net, idx) => {
  19367. const isSel = net.id === selId;
  19368. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19369. return `
  19370. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('networks', '${net.id}')">
  19371. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19372. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(net.comment || '')}</td>
  19373. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(net.network || '')}</td>
  19374. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(net.instance || 'all')}</td>
  19375. </tr>
  19376. `;
  19377. }).join('');
  19378. }
  19379. function openEigrpNetworkModal() {
  19380. document.getElementById('modal-eigrp-network-id').value = '';
  19381. const instSel = document.getElementById('modal-eigrp-network-instance');
  19382. if (instSel) {
  19383. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19384. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19385. }
  19386. document.getElementById('modal-eigrp-network-cidr').value = '0.0.0.0/0';
  19387. document.getElementById('modal-eigrp-network-comment').value = '';
  19388. document.getElementById('eigrp-network-modal')?.classList.remove('hidden');
  19389. }
  19390. function closeEigrpNetworkModal() {
  19391. document.getElementById('eigrp-network-modal')?.classList.add('hidden');
  19392. }
  19393. async function submitEigrpNetwork(e) {
  19394. e.preventDefault();
  19395. const payload = {
  19396. id: document.getElementById('modal-eigrp-network-id').value.trim() || undefined,
  19397. instance: document.getElementById('modal-eigrp-network-instance').value,
  19398. network: document.getElementById('modal-eigrp-network-cidr').value.trim(),
  19399. comment: document.getElementById('modal-eigrp-network-comment').value.trim()
  19400. };
  19401. try {
  19402. const res = await fetch(`${API_BASE}/routing/eigrp/networks`, {
  19403. method: 'POST',
  19404. headers: { 'Content-Type': 'application/json' },
  19405. body: JSON.stringify(payload)
  19406. });
  19407. if (!res.ok) throw new Error(await res.text());
  19408. closeEigrpNetworkModal();
  19409. showToast('Saved', `EIGRP network saved`, 'success');
  19410. await loadDynamicRouting(false);
  19411. } catch (err) {
  19412. showToast('Error', err.message, 'error');
  19413. }
  19414. }
  19415. async function removeSelectedEigrpNetwork() {
  19416. const id = state.selectedEigrpRow?.networks;
  19417. if (!id || !confirm('Are you sure you want to remove this EIGRP network?')) return;
  19418. if (!await routingMutation(`${API_BASE}/routing/eigrp/networks/${id}`, { method: 'DELETE' })) return;
  19419. state.selectedEigrpRow.networks = null;
  19420. await loadDynamicRouting(false);
  19421. }
  19422. // --- EIGRP INTERFACES ---
  19423. function renderEigrpInterfaces() {
  19424. const tbody = document.getElementById('eigrp-interfaces-table-body');
  19425. if (!tbody) return;
  19426. const countEl = document.getElementById('eigrp-interfaces-footer-count');
  19427. const filter = (document.getElementById('filter-eigrp-interfaces')?.value || '').toLowerCase();
  19428. let list = state.eigrpInterfaces || [];
  19429. if (filter) {
  19430. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  19431. }
  19432. if (countEl) countEl.innerText = list.length;
  19433. const selId = state.selectedEigrpRow?.interfaces;
  19434. tbody.innerHTML = list.map((iface, idx) => {
  19435. const isSel = iface.id === selId;
  19436. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-purple-400' : 'hover:bg-[#1a2636] text-slate-300';
  19437. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400 font-bold">E</span>';
  19438. return `
  19439. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectEigrpRow('interfaces', '${iface.id}')" ondblclick="openEditEigrpInterfaceModal('${iface.id}')">
  19440. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19441. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  19442. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  19443. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  19444. <td class="py-1.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  19445. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 5}s / ${iface.hold_time || 15}s</td>
  19446. <td class="py-1.5 px-3 font-mono ${iface.passive ? 'text-amber-400 font-bold' : 'text-slate-400'}">${iface.passive ? 'Yes' : 'No'}</td>
  19447. <td class="py-1.5 px-3 font-mono ${iface.split_horizon ? 'text-emerald-400' : 'text-slate-400'}">${iface.split_horizon ? 'Yes' : 'No'}</td>
  19448. <td class="py-1.5 px-3 text-slate-300 uppercase font-mono">${escapeHtml(iface.auth_mode || 'none')}</td>
  19449. </tr>
  19450. `;
  19451. }).join('');
  19452. }
  19453. function toggleEigrpAuthKey() {
  19454. const mode = document.getElementById('modal-eigrp-iface-auth-mode')?.value;
  19455. const wrap = document.getElementById('modal-eigrp-iface-auth-key-wrap');
  19456. if (wrap) {
  19457. if (mode === 'md5') wrap.classList.remove('hidden');
  19458. else wrap.classList.add('hidden');
  19459. }
  19460. }
  19461. function openEigrpInterfaceModal() {
  19462. document.getElementById('eigrp-interface-modal-title').innerText = 'Add EIGRP Interface Profile';
  19463. document.getElementById('modal-eigrp-iface-id').value = '';
  19464. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19465. if (instSel) {
  19466. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19467. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19468. }
  19469. const dl = document.getElementById('eigrp-iface-datalist');
  19470. if (dl && state.interfaces) {
  19471. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19472. }
  19473. document.getElementById('modal-eigrp-iface-interface').value = '*';
  19474. document.getElementById('modal-eigrp-iface-hello').value = '5';
  19475. document.getElementById('modal-eigrp-iface-hold').value = '15';
  19476. document.getElementById('modal-eigrp-iface-auth-mode').value = 'none';
  19477. document.getElementById('modal-eigrp-iface-auth-key').value = '';
  19478. toggleEigrpAuthKey();
  19479. document.getElementById('modal-eigrp-iface-passive').checked = false;
  19480. document.getElementById('modal-eigrp-iface-split-horizon').checked = true;
  19481. document.getElementById('modal-eigrp-iface-comment').value = '';
  19482. document.getElementById('modal-eigrp-iface-enabled').checked = true;
  19483. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19484. }
  19485. function openEditEigrpInterfaceModal(id) {
  19486. const iface = (state.eigrpInterfaces || []).find(i => i.id === id);
  19487. if (!iface) return;
  19488. document.getElementById('eigrp-interface-modal-title').innerText = `Edit EIGRP Interface: ${iface.interface}`;
  19489. document.getElementById('modal-eigrp-iface-id').value = iface.id;
  19490. const instSel = document.getElementById('modal-eigrp-iface-instance');
  19491. if (instSel) {
  19492. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  19493. (state.eigrpInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} (AS ${i.as})</option>`).join('');
  19494. instSel.value = iface.instance || 'all';
  19495. }
  19496. const dl = document.getElementById('eigrp-iface-datalist');
  19497. if (dl && state.interfaces) {
  19498. dl.innerHTML = '<option value="*">' + state.interfaces.map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  19499. }
  19500. document.getElementById('modal-eigrp-iface-interface').value = iface.interface || '*';
  19501. document.getElementById('modal-eigrp-iface-hello').value = iface.hello_interval || 5;
  19502. document.getElementById('modal-eigrp-iface-hold').value = iface.hold_time || 15;
  19503. document.getElementById('modal-eigrp-iface-auth-mode').value = iface.auth_mode || 'none';
  19504. document.getElementById('modal-eigrp-iface-auth-key').value = iface.auth_key || '';
  19505. toggleEigrpAuthKey();
  19506. document.getElementById('modal-eigrp-iface-passive').checked = !!iface.passive;
  19507. document.getElementById('modal-eigrp-iface-split-horizon').checked = iface.split_horizon !== false;
  19508. document.getElementById('modal-eigrp-iface-comment').value = iface.comment || '';
  19509. document.getElementById('modal-eigrp-iface-enabled').checked = !iface.disabled;
  19510. document.getElementById('eigrp-interface-modal')?.classList.remove('hidden');
  19511. }
  19512. function closeEigrpInterfaceModal() {
  19513. document.getElementById('eigrp-interface-modal')?.classList.add('hidden');
  19514. }
  19515. async function submitEigrpInterface(e) {
  19516. e.preventDefault();
  19517. const payload = {
  19518. id: document.getElementById('modal-eigrp-iface-id').value.trim() || undefined,
  19519. instance: document.getElementById('modal-eigrp-iface-instance').value,
  19520. interface: document.getElementById('modal-eigrp-iface-interface').value.trim(),
  19521. hello_interval: parseInt(document.getElementById('modal-eigrp-iface-hello').value, 10) || 5,
  19522. hold_time: parseInt(document.getElementById('modal-eigrp-iface-hold').value, 10) || 15,
  19523. passive: document.getElementById('modal-eigrp-iface-passive').checked,
  19524. split_horizon: document.getElementById('modal-eigrp-iface-split-horizon').checked,
  19525. auth_mode: document.getElementById('modal-eigrp-iface-auth-mode').value,
  19526. auth_key: document.getElementById('modal-eigrp-iface-auth-key').value.trim(),
  19527. comment: document.getElementById('modal-eigrp-iface-comment').value.trim(),
  19528. disabled: !document.getElementById('modal-eigrp-iface-enabled').checked
  19529. };
  19530. try {
  19531. const res = await fetch(`${API_BASE}/routing/eigrp/interfaces`, {
  19532. method: 'POST',
  19533. headers: { 'Content-Type': 'application/json' },
  19534. body: JSON.stringify(payload)
  19535. });
  19536. if (!res.ok) throw new Error(await res.text());
  19537. closeEigrpInterfaceModal();
  19538. showToast('Saved', `EIGRP interface saved`, 'success');
  19539. await loadDynamicRouting(false);
  19540. } catch (err) {
  19541. showToast('Error', err.message, 'error');
  19542. }
  19543. }
  19544. async function enableSelectedEigrpInterface() {
  19545. const id = state.selectedEigrpRow?.interfaces;
  19546. if (!id) return;
  19547. if (!await routingMutation(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) })) return;
  19548. await loadDynamicRouting(false);
  19549. }
  19550. async function disableSelectedEigrpInterface() {
  19551. const id = state.selectedEigrpRow?.interfaces;
  19552. if (!id) return;
  19553. if (!await routingMutation(`${API_BASE}/routing/eigrp/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) })) return;
  19554. await loadDynamicRouting(false);
  19555. }
  19556. async function removeSelectedEigrpInterface() {
  19557. const id = state.selectedEigrpRow?.interfaces;
  19558. if (!id || !confirm('Are you sure you want to remove this EIGRP interface?')) return;
  19559. if (!await routingMutation(`${API_BASE}/routing/eigrp/interfaces/${id}`, { method: 'DELETE' })) return;
  19560. state.selectedEigrpRow.interfaces = null;
  19561. await loadDynamicRouting(false);
  19562. }
  19563. // --- EIGRP NEIGHBORS (LIVE) ---
  19564. function renderEigrpNeighbors() {
  19565. const tbody = document.getElementById('eigrp-neighbors-table-body');
  19566. if (!tbody) return;
  19567. const countEl = document.getElementById('eigrp-neighbors-footer-count');
  19568. const filter = (document.getElementById('filter-eigrp-neighbors')?.value || '').toLowerCase();
  19569. let list = state.eigrpNeighbors || [];
  19570. if (filter) {
  19571. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.interface || '').toLowerCase().includes(filter) || String(n.as || '').includes(filter));
  19572. }
  19573. if (countEl) countEl.innerText = list.length;
  19574. tbody.innerHTML = list.map((nbr, idx) => `
  19575. <tr class="hover:bg-[#1a2636] text-slate-300">
  19576. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19577. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${nbr.as || '-'}</td>
  19578. <td class="py-1.5 px-3 font-mono font-semibold text-purple-300">${escapeHtml(nbr.address || '')}</td>
  19579. <td class="py-1.5 px-3 font-mono text-white">${escapeHtml(nbr.interface || '')}</td>
  19580. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.hold_time || 0}s</td>
  19581. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '-')}</td>
  19582. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.srtt || 0}</td>
  19583. <td class="py-1.5 px-3 font-mono text-slate-300">${nbr.rto || 0}</td>
  19584. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.q_cnt || 0}</td>
  19585. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.seq_num || 0}</td>
  19586. </tr>
  19587. `).join('');
  19588. }
  19589. // --- EIGRP TOPOLOGY (LIVE) ---
  19590. function renderEigrpTopology() {
  19591. const tbody = document.getElementById('eigrp-topology-table-body');
  19592. if (!tbody) return;
  19593. const countEl = document.getElementById('eigrp-topology-footer-count');
  19594. const filter = (document.getElementById('filter-eigrp-topology')?.value || '').toLowerCase();
  19595. let list = state.eigrpTopology || [];
  19596. if (filter) {
  19597. 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));
  19598. }
  19599. if (countEl) countEl.innerText = list.length;
  19600. tbody.innerHTML = list.map((top, idx) => `
  19601. <tr class="hover:bg-[#1a2636] text-slate-300">
  19602. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  19603. <td class="py-1.5 px-3 font-mono font-bold text-purple-400">${top.as || '-'}</td>
  19604. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(top.network || '')}</td>
  19605. <td class="py-1.5 px-3 font-mono text-slate-300">${top.successors || 1}</td>
  19606. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(top.fd || '-')}</td>
  19607. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(top.next_hop || '-')}</td>
  19608. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(top.interface || '-')}</td>
  19609. </tr>
  19610. `).join('');
  19611. }