app.js 735 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. pppSecrets: [],
  109. pppProfiles: [],
  110. pppActiveSessions: [],
  111. pppoeServer: null,
  112. pptpServer: null,
  113. l2tpServer: null,
  114. ipsecServer: null,
  115. ifaceFilter: 'all',
  116. currentModalIface: null,
  117. isPolling: false,
  118. expandedParents: new Set(['eth0']),
  119. pppoeData: null,
  120. wgData: null,
  121. ipsecData: null,
  122. l2tpData: null,
  123. pptpData: null,
  124. fwSummary: null,
  125. filterRules: [],
  126. natRules: [],
  127. mangleRules: [],
  128. addressLists: [],
  129. connections: [],
  130. policyRules: [],
  131. routingTables: [],
  132. routingFilters: [],
  133. filterChainSelected: 'all',
  134. activeToolsSubTab: 'ping',
  135. dhcpClients: [],
  136. dhcpSummary: null,
  137. dhcpServerTab: 'servers',
  138. dhcpServers: [],
  139. dhcpNetworks: [],
  140. dhcpLeases: [],
  141. dhcpOptions: [],
  142. dhcpServerSummary: null
  143. };
  144. const API_BASE = '/api';
  145. function escapeHtml(str) {
  146. if (str === null || str === undefined) return '';
  147. return String(str)
  148. .replace(/&/g, '&')
  149. .replace(/</g, '&lt;')
  150. .replace(/>/g, '&gt;')
  151. .replace(/"/g, '&quot;')
  152. .replace(/'/g, '&#039;');
  153. }
  154. function formatBytes(bytes) {
  155. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  156. const k = 1024;
  157. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  158. const i = Math.floor(Math.log(bytes) / Math.log(k));
  159. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  160. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  161. }
  162. // Initialize on page load
  163. document.addEventListener('DOMContentLoaded', async () => {
  164. initTableSorting();
  165. // Verify authentication before bootstrapping telemetry and views
  166. const isAuthenticated = await checkAuthStatus();
  167. if (isAuthenticated) {
  168. const hash = window.location.hash.replace('#', '') || 'dashboard';
  169. navigate(hash);
  170. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  171. if (!window._telemetryInterval) {
  172. window._telemetryInterval = setInterval(() => {
  173. if (state.isPolling && state.currentUser && !document.hidden) {
  174. fetchData(false);
  175. }
  176. }, 5000);
  177. }
  178. }
  179. });
  180. let trafficEventSource = null;
  181. let trafficPollFallback = null;
  182. function initLiveTrafficStream() {
  183. if (trafficEventSource) {
  184. try { trafficEventSource.close(); } catch(e) {}
  185. trafficEventSource = null;
  186. }
  187. if (trafficPollFallback) {
  188. clearInterval(trafficPollFallback);
  189. trafficPollFallback = null;
  190. }
  191. if (window.EventSource) {
  192. try {
  193. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  194. trafficEventSource.onmessage = (event) => {
  195. try {
  196. const data = JSON.parse(event.data);
  197. updateLiveInterfaceTraffic(data);
  198. } catch (e) {
  199. console.error('Error parsing live traffic event:', e);
  200. }
  201. };
  202. trafficEventSource.onerror = () => {
  203. // Fallback polling if SSE disconnects
  204. if (!trafficPollFallback) {
  205. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  206. }
  207. };
  208. trafficEventSource.onopen = () => {
  209. if (trafficPollFallback) {
  210. clearInterval(trafficPollFallback);
  211. trafficPollFallback = null;
  212. }
  213. };
  214. return;
  215. } catch (e) {
  216. console.warn('EventSource failed, using 1s polling fallback:', e);
  217. }
  218. }
  219. // Fallback if EventSource is unavailable
  220. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  221. }
  222. async function pollLiveTrafficSnapshot() {
  223. try {
  224. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  225. if (res.ok) {
  226. const data = await res.json();
  227. updateLiveInterfaceTraffic(data);
  228. }
  229. } catch (e) {}
  230. }
  231. function updateLiveInterfaceTraffic(data) {
  232. if (!data || !data.interfaces) return;
  233. state.latestTraffic = data;
  234. // 1. Update Top & Dashboard Total Bandwidth Indicators
  235. const rxHuman = data.total_rx_human || '0 B/s';
  236. const txHuman = data.total_tx_human || '0 B/s';
  237. const statRx = document.getElementById('stat-traffic-rx');
  238. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  239. const statTx = document.getElementById('stat-traffic-tx');
  240. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  241. // 2. Update state.interfaces rates in-memory
  242. if (Array.isArray(state.interfaces)) {
  243. state.interfaces.forEach(i => {
  244. const live = data.interfaces[i.name];
  245. if (live) {
  246. i.rate = {
  247. rx_bytes_sec: live.rx_bytes_sec,
  248. tx_bytes_sec: live.tx_bytes_sec,
  249. rx_human: live.rx_human,
  250. tx_human: live.tx_human
  251. };
  252. i.stats = {
  253. rx_bytes: live.rx_bytes,
  254. tx_bytes: live.tx_bytes,
  255. rx_packets: live.rx_packets,
  256. tx_packets: live.tx_packets,
  257. rx_errors: live.rx_errors,
  258. tx_errors: live.tx_errors,
  259. rx_dropped: live.rx_dropped,
  260. tx_dropped: live.tx_dropped
  261. };
  262. }
  263. });
  264. }
  265. // 3. Update all live UI rate spans in-place (ZERO flicker)
  266. Object.keys(data.interfaces).forEach(name => {
  267. const live = data.interfaces[name];
  268. // Dashboard Port Matrix Card
  269. const cardRate = document.getElementById(`port-card-rate-${name}`);
  270. if (cardRate && cardRate.innerText !== live.rx_human) {
  271. cardRate.innerText = live.rx_human;
  272. }
  273. // Dashboard Quick Interfaces Table
  274. const quickRx = document.getElementById(`quick-rx-${name}`);
  275. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  276. const quickTx = document.getElementById(`quick-tx-${name}`);
  277. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  278. // Main Interfaces Tree Table
  279. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  280. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  281. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  282. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  283. // VLAN Sub-interfaces Table
  284. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  285. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  286. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  287. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  288. // VLAN Page Table
  289. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  290. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  291. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  292. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  293. });
  294. }
  295. // Navigation Handler
  296. function navigate(tabName) {
  297. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  298. navigate('bgp');
  299. return;
  300. }
  301. if (tabName === 'vlans') {
  302. navigate('interfaces');
  303. return;
  304. }
  305. if (tabName === 'persistence') {
  306. navigate('dashboard');
  307. return;
  308. }
  309. stopFwStatPolling();
  310. stopNATStatPolling();
  311. stopMangleStatPolling();
  312. state.activeTab = tabName;
  313. window.location.hash = tabName;
  314. // Update nav links styling
  315. document.querySelectorAll('.nav-link').forEach(link => {
  316. 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';
  317. });
  318. const activeNav = document.getElementById(`nav-${tabName}`);
  319. if (activeNav) {
  320. 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';
  321. }
  322. // Update page headers
  323. const titles = {
  324. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  325. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  326. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  327. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  328. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  329. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  330. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  331. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  332. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  333. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  334. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  335. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  336. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  337. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  338. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  339. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  340. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  341. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  342. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  343. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  344. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  345. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  346. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  347. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  348. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  349. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  350. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  351. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  352. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  353. };
  354. const header = titles[tabName] || titles.dashboard;
  355. const pTitle = document.getElementById('page-title');
  356. if (pTitle) pTitle.innerText = header.title;
  357. const pSub = document.getElementById('page-subtitle');
  358. if (pSub) pSub.innerText = header.sub;
  359. // Toggle sections dynamically for all section elements
  360. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  361. if (el.id === `section-${tabName}`) {
  362. el.classList.remove('hidden');
  363. } else {
  364. el.classList.add('hidden');
  365. }
  366. });
  367. if (tabName === 'interfaces') {
  368. loadRoles();
  369. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  370. else switchIfaceSubTab('tree');
  371. }
  372. if (tabName === 'bridge') loadBridge();
  373. if (tabName === 'firewall') loadFirewall();
  374. if (tabName === 'routes') loadRoutes();
  375. if (tabName === 'bgp') {
  376. loadDynamicRouting();
  377. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  378. }
  379. if (tabName === 'ospf') {
  380. loadDynamicRouting();
  381. switchOspfTab(state.activeOspfTab || 'instances');
  382. }
  383. if (tabName === 'routing-filters') loadDynamicRouting();
  384. if (tabName === 'dynamic-routing') loadDynamicRouting();
  385. if (tabName === 'ppp') loadPPP();
  386. if (tabName === 'eoip') loadEoIP();
  387. if (tabName === 'aerotun') loadAeroTUN();
  388. if (tabName === 'pppoe') loadPPPoE();
  389. if (tabName === 'wireguard') loadWireGuard();
  390. if (tabName === 'ipsec') loadIPSec();
  391. if (tabName === 'l2tp') loadL2TP();
  392. if (tabName === 'pptp') loadPPTP();
  393. if (tabName === 'tools') loadToolsView();
  394. if (tabName === 'dhcp-client') loadDHCPClients();
  395. if (tabName === 'dhcp-server') loadDHCPServer();
  396. if (tabName === 'vrrp') loadVRRP();
  397. if (tabName === 'bwtest') loadBwTestView();
  398. if (tabName === 'settings') loadSettingsData();
  399. if (tabName === 'users') loadUsers();
  400. if (tabName === 'certificates') loadCertificates();
  401. if (tabName === 'services') loadServices();
  402. if (tabName === 'updates') loadUpdateStatus();
  403. if (tabName === 'logs') loadLogs();
  404. setTimeout(initTableSorting, 50);
  405. }
  406. // Fetch all core system, network and VPN telemetry
  407. function fetchData(isManual = false) {
  408. if (coreRefreshPromise) return coreRefreshPromise;
  409. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  410. return coreRefreshPromise;
  411. }
  412. async function refreshCoreData(isManual = false) {
  413. const spinner = document.getElementById('refresh-spinner');
  414. if (isManual && spinner) spinner.classList.add('animate-spin');
  415. try {
  416. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  417. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  418. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  419. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  420. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  421. summaryFetch('/vlans'),
  422. summaryFetch('/vpn/status'),
  423. summaryFetch('/firewall/summary'),
  424. summaryFetch('/routing/dynamic/summary'),
  425. summaryFetch('/bridge/summary'),
  426. summaryFetch('/dhcp/clients/summary'),
  427. summaryFetch('/dhcp/clients'),
  428. summaryFetch('/vrrp/summary').catch(() => null),
  429. summaryFetch('/roles').catch(() => null)
  430. ]);
  431. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  432. if (rolesRes && rolesRes.ok) {
  433. state.roles = await rolesRes.json();
  434. const countEl = document.getElementById('badge-roles-count');
  435. if (countEl) countEl.innerText = (state.roles || []).length;
  436. }
  437. if (vrrpSumRes && vrrpSumRes.ok) {
  438. state.vrrpSummary = await vrrpSumRes.json();
  439. renderVRRPSummary();
  440. }
  441. if (dhcpSumRes && dhcpSumRes.ok) {
  442. state.dhcpSummary = await dhcpSumRes.json();
  443. const bDhcp = document.getElementById('badge-dhcp-client-count');
  444. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  445. }
  446. if (dhcpClientsRes && dhcpClientsRes.ok) {
  447. state.dhcpClients = await dhcpClientsRes.json();
  448. }
  449. if (brSummaryRes.ok) {
  450. state.bridgeSummary = await brSummaryRes.json();
  451. const bBridge = document.getElementById('badge-bridge-count');
  452. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  453. const sBr = document.getElementById('bridge-stat-bridges');
  454. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  455. const sPorts = document.getElementById('bridge-stat-ports');
  456. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  457. const sHosts = document.getElementById('bridge-stat-hosts');
  458. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  459. }
  460. if (statusRes.ok) state.systemStatus = await statusRes.json();
  461. if (ifacesRes.ok) {
  462. const ifacesData = await ifacesRes.json();
  463. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  464. state.interfaces = rawIfaces.filter(i => {
  465. if (!i.name) return false;
  466. if (i.name.startsWith('ep_')) return false;
  467. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  468. });
  469. try { populateToolsInterfaces(); } catch (e) {}
  470. }
  471. if (vlansRes.ok) {
  472. const vlansData = await vlansRes.json();
  473. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  474. }
  475. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  476. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  477. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  478. updateSystemMetrics();
  479. updateBadges();
  480. if (state.activeTab === 'dashboard') renderDashboard();
  481. if (state.activeTab === 'interfaces') {
  482. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  483. else renderInterfacesList();
  484. }
  485. if (state.activeTab === 'vlans') renderVlansList();
  486. if (state.activeTab === 'firewall') await loadFirewall(false);
  487. if (state.activeTab === 'routes') await loadRoutes(false);
  488. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') await loadDynamicRouting(false);
  489. if (state.activeTab === 'ppp') await loadPPP(false);
  490. if (state.activeTab === 'eoip') await loadEoIP(false);
  491. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  492. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  493. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  494. if (state.activeTab === 'ipsec') await loadIPSec(false);
  495. if (state.activeTab === 'l2tp') await loadL2TP(false);
  496. if (state.activeTab === 'pptp') await loadPPTP(false);
  497. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  498. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  499. if (state.activeTab === 'vrrp') await loadVRRP(false);
  500. if (state.activeTab === 'settings') await loadSettingsData(false);
  501. if (state.activeTab === 'users') await loadUsers(false);
  502. if (state.activeTab === 'certificates') await loadCertificates(false);
  503. if (state.activeTab === 'services') await loadServices(false);
  504. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  505. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  506. } catch (err) {
  507. console.error('Failed to fetch router state:', err);
  508. } finally {
  509. if (isManual && spinner) {
  510. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  511. }
  512. }
  513. }
  514. // Update Top KPI and Sidebar Telemetry
  515. function updateSystemMetrics() {
  516. const s = state.systemStatus;
  517. const v = state.vpnStatus;
  518. if (!s) return;
  519. // Sidebar Host & Uptime
  520. const sideHost = document.getElementById('side-hostname');
  521. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  522. const sideUp = document.getElementById('side-uptime');
  523. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  524. const sideGw = document.getElementById('side-gateway-ip');
  525. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  526. // Compute CPU Metrics
  527. let cpuPct = 0;
  528. if (s.cpu_pct !== undefined) {
  529. cpuPct = s.cpu_pct;
  530. } else if (s.cpu_load && s.cpu_load.length > 0) {
  531. const cores = s.cpu_cores || 1;
  532. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  533. }
  534. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  535. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  536. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  537. // Sidebar CPU
  538. const sideCpuVal = document.getElementById('side-cpu-val');
  539. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  540. const sideCpuBar = document.getElementById('side-cpu-bar');
  541. if (sideCpuBar) {
  542. sideCpuBar.style.width = cpuWidth;
  543. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  544. }
  545. // Dashboard CPU Card
  546. const dashCpuVal = document.getElementById('dash-cpu-val');
  547. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  548. const dashCpuBar = document.getElementById('dash-cpu-bar');
  549. if (dashCpuBar) {
  550. dashCpuBar.style.width = cpuWidth;
  551. if (cpuPct > 85) {
  552. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  553. } else if (cpuPct > 65) {
  554. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  555. } else {
  556. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  557. }
  558. }
  559. const dashCpuCores = document.getElementById('dash-cpu-cores');
  560. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  561. const dashCpuLoad = document.getElementById('dash-cpu-load');
  562. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  563. const dashCpuStatus = document.getElementById('dash-cpu-status');
  564. if (dashCpuStatus) {
  565. if (cpuPct > 85) {
  566. dashCpuStatus.innerText = 'High';
  567. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  568. } else if (cpuPct > 65) {
  569. dashCpuStatus.innerText = 'Heavy';
  570. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  571. } else {
  572. dashCpuStatus.innerText = 'Normal';
  573. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  574. }
  575. }
  576. // Compute RAM Metrics
  577. const memPct = Math.round(s.mem_usage_pct || 0);
  578. const memPctStr = `${memPct}%`;
  579. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  580. const usedMB = s.mem_used_mb || 0;
  581. const totalMB = s.mem_total_mb || 0;
  582. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  583. function fmtMemMB(mb) {
  584. if (mb >= 1024) {
  585. return `${(mb / 1024).toFixed(1)} GB`;
  586. }
  587. return `${mb} MB`;
  588. }
  589. // Sidebar RAM
  590. const sideRamVal = document.getElementById('side-ram-val');
  591. if (sideRamVal) sideRamVal.innerText = memPctStr;
  592. const sideRamBar = document.getElementById('side-ram-bar');
  593. if (sideRamBar) sideRamBar.style.width = memWidth;
  594. // Dashboard RAM Card
  595. const dashRamVal = document.getElementById('dash-ram-val');
  596. if (dashRamVal) dashRamVal.innerText = memPctStr;
  597. const dashRamBar = document.getElementById('dash-ram-bar');
  598. if (dashRamBar) {
  599. dashRamBar.style.width = memWidth;
  600. if (memPct > 85) {
  601. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  602. } else if (memPct > 70) {
  603. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  604. } else {
  605. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  606. }
  607. }
  608. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  609. if (dashRamUsedTotal) {
  610. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  611. }
  612. const dashRamFree = document.getElementById('dash-ram-free');
  613. if (dashRamFree) {
  614. dashRamFree.innerText = fmtMemMB(freeMB);
  615. }
  616. const dashRamStatus = document.getElementById('dash-ram-status');
  617. if (dashRamStatus) {
  618. if (memPct > 85) {
  619. dashRamStatus.innerText = 'High';
  620. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  621. } else {
  622. dashRamStatus.innerText = 'Active';
  623. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  624. }
  625. }
  626. // Legacy Dashboard Stats (Safe checks)
  627. const elIfacesUp = document.getElementById('stat-ifaces-up');
  628. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  629. const elIfacesTot = document.getElementById('stat-ifaces-total');
  630. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  631. const elIfacesDown = document.getElementById('stat-ifaces-down');
  632. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  633. const elVlans = document.getElementById('stat-vlans-count');
  634. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  635. // VPN Status Indicators
  636. if (v) {
  637. const totalActive = v.total_active_tunnels || 0;
  638. const statVpnActive = document.getElementById('stat-vpn-active');
  639. if (statVpnActive) statVpnActive.innerText = totalActive;
  640. const tunnelsDot = document.getElementById('tunnels-dot');
  641. const tunnelsLabel = document.getElementById('tunnels-label');
  642. if (tunnelsDot && tunnelsLabel) {
  643. if (totalActive > 0) {
  644. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  645. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  646. } else {
  647. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  648. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  649. }
  650. }
  651. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  652. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  653. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  654. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  655. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  656. }
  657. // Total Live Bandwidth Rate
  658. let totalRx = 0;
  659. let totalTx = 0;
  660. (state.interfaces || []).forEach(i => {
  661. if (i.rate) {
  662. totalRx += i.rate.rx_bytes_sec || 0;
  663. totalTx += i.rate.tx_bytes_sec || 0;
  664. }
  665. });
  666. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  667. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  668. }
  669. function setDotBadge(id, active) {
  670. const el = document.getElementById(id);
  671. if (!el) return;
  672. if (active) {
  673. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  674. } else {
  675. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  676. }
  677. }
  678. function updateBadges() {
  679. const bIfaces = document.getElementById('badge-ifaces-count');
  680. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  681. const bVlans = document.getElementById('badge-vlans-count');
  682. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  683. if (state.fwSummary) {
  684. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  685. const badgeFw = document.getElementById('badge-firewall-count');
  686. if (badgeFw) badgeFw.innerText = totalFwRules;
  687. }
  688. if (state.vpnStatus) {
  689. const v = state.vpnStatus;
  690. const bEoIP = document.getElementById('badge-eoip-count');
  691. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  692. const bAero = document.getElementById('badge-aerotun-count');
  693. if (bAero) bAero.innerText = v.total_aerotun || 0;
  694. const bPPPSess = document.getElementById('badge-ppp-sessions');
  695. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  696. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  697. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  698. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  699. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  700. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  701. }
  702. if (state.dynSummary) {
  703. const d = state.dynSummary;
  704. setDotBadge('badge-bgp-dot', d.bgp_running);
  705. setDotBadge('badge-ospf-dot', d.ospf_running);
  706. const bBgp = document.getElementById('badge-bgp-count');
  707. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  708. const bOspf = document.getElementById('badge-ospf-count');
  709. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  710. const bFilters = document.getElementById('badge-filters-count');
  711. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  712. }
  713. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  714. if (bDhcpServer) {
  715. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  716. }
  717. }
  718. // Render Dashboard View
  719. function renderDashboard() {
  720. const matrix = document.getElementById('port-matrix');
  721. if (!matrix) return;
  722. const ifaces = state.interfaces || [];
  723. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  724. if (matrix.dataset.sig === sig) {
  725. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  726. }
  727. matrix.dataset.sig = sig;
  728. matrix.innerHTML = '';
  729. (state.interfaces || []).forEach(iface => {
  730. const isUp = iface.state === 'UP';
  731. const isVlan = iface.is_vlan;
  732. const portCard = document.createElement('div');
  733. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  734. isUp
  735. ? (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')
  736. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  737. }`;
  738. portCard.onclick = () => openIfaceModal(iface.name);
  739. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  740. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  741. portCard.innerHTML = `
  742. <div class="flex items-center justify-between mb-2">
  743. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  744. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  745. </div>
  746. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  747. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  748. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  749. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  750. </div>
  751. `;
  752. matrix.appendChild(portCard);
  753. });
  754. const ifaceTbody = document.getElementById('quick-interfaces-table');
  755. if (ifaceTbody) {
  756. ifaceTbody.innerHTML = '';
  757. (state.interfaces || []).forEach(i => {
  758. const isUp = i.state === 'UP';
  759. const tr = document.createElement('tr');
  760. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  761. tr.onclick = () => openIfaceModal(i.name);
  762. const rxStr = i.rate?.rx_human || '0 B/s';
  763. const txStr = i.rate?.tx_human || '0 B/s';
  764. tr.innerHTML = `
  765. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  766. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  767. <span>${i.name}</span>
  768. </td>
  769. <td class="py-2.5 text-slate-300 font-sans">
  770. ${getRoleBadge(i.role || 'LAN')}
  771. </td>
  772. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  773. <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>
  774. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  775. <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>
  776. </td>
  777. <td class="py-2.5 text-right font-sans font-semibold">
  778. <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>
  779. </td>
  780. `;
  781. ifaceTbody.appendChild(tr);
  782. });
  783. }
  784. const vlanTbody = document.getElementById('quick-vlans-table');
  785. if (vlanTbody) {
  786. vlanTbody.innerHTML = '';
  787. }
  788. }
  789. // Expand / Collapse Handlers
  790. function toggleExpand(parentName) {
  791. if (state.expandedParents.has(parentName)) {
  792. state.expandedParents.delete(parentName);
  793. } else {
  794. state.expandedParents.add(parentName);
  795. }
  796. renderInterfacesList();
  797. }
  798. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  799. function supportsVLAN(iface) {
  800. if (!iface) return false;
  801. if (iface.is_vlan) return false;
  802. const name = (iface.name || '').toLowerCase();
  803. const type = (iface.type || '').toLowerCase();
  804. const role = (iface.role || '').toLowerCase();
  805. // Exclude loopback
  806. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  807. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  808. if (type === 'wireguard' || name.startsWith('wg')) return false;
  809. // Exclude PPP / PPPoE
  810. if (type === 'ppp' || name.startsWith('ppp')) return false;
  811. // Exclude other Layer 3 tunnels and dummy devices
  812. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  813. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  814. return false;
  815. }
  816. // If name already contains a dot, it's already a sub-interface
  817. if (name.includes('.')) return false;
  818. return true;
  819. }
  820. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  821. function supportsDHCPClient(iface) {
  822. if (!iface) return false;
  823. const name = (iface.name || '').toLowerCase();
  824. const type = (iface.type || '').toLowerCase();
  825. const role = (iface.role || '').toLowerCase();
  826. // Exclude loopback
  827. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  828. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  829. if (type === 'wireguard' || name.startsWith('wg')) return false;
  830. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  831. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  832. // Exclude other Layer 3 tunnels and dummy devices
  833. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  834. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  835. return false;
  836. }
  837. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  838. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  839. if (isBridgePort) return false;
  840. return true;
  841. }
  842. // Expand / Collapse Handlers
  843. function toggleExpand(parentName) {
  844. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  845. if (childVlans.length === 0) {
  846. // Cannot expand an interface with no VLANs
  847. state.expandedParents.delete(parentName);
  848. return;
  849. }
  850. if (state.expandedParents.has(parentName)) {
  851. state.expandedParents.delete(parentName);
  852. } else {
  853. state.expandedParents.add(parentName);
  854. }
  855. renderInterfacesList();
  856. }
  857. function expandAllIfaces(expand) {
  858. if (expand) {
  859. (state.interfaces || []).forEach(i => {
  860. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  861. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  862. });
  863. } else {
  864. state.expandedParents.clear();
  865. }
  866. renderInterfacesList();
  867. }
  868. // =========================================================================
  869. // INTERFACE ROLE TAGS MANAGEMENT
  870. // =========================================================================
  871. const ROLE_COLORS = {
  872. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  873. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  874. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  875. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  876. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  877. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  878. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  879. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  880. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  881. };
  882. function getRoleBadge(roleName) {
  883. const name = roleName || 'LAN';
  884. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  885. const colorKey = (role?.color || 'blue').toLowerCase();
  886. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  887. 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>`;
  888. }
  889. function switchIfaceSubTab(subTab) {
  890. state.activeIfaceSubTab = subTab;
  891. const treeTab = document.getElementById('ifaces-subtab-tree');
  892. const rolesTab = document.getElementById('ifaces-subtab-roles');
  893. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  894. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  895. if (subTab === 'roles') {
  896. treeTab?.classList.add('hidden');
  897. rolesTab?.classList.remove('hidden');
  898. if (btnRoles) {
  899. 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';
  900. }
  901. if (btnTree) {
  902. 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';
  903. }
  904. loadRoles();
  905. } else {
  906. rolesTab?.classList.add('hidden');
  907. treeTab?.classList.remove('hidden');
  908. if (btnTree) {
  909. 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';
  910. }
  911. if (btnRoles) {
  912. 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';
  913. }
  914. renderInterfacesList();
  915. }
  916. }
  917. async function loadRoles() {
  918. try {
  919. const res = await fetch(`${API_BASE}/roles`);
  920. if (res.ok) {
  921. state.roles = await res.json();
  922. const countEl = document.getElementById('badge-roles-count');
  923. if (countEl) countEl.innerText = (state.roles || []).length;
  924. renderRolesTable();
  925. populateRoleSelects();
  926. }
  927. } catch (err) {
  928. console.error('Failed to load role tags:', err);
  929. }
  930. }
  931. function renderRolesTable() {
  932. const tbody = document.getElementById('roles-table-body');
  933. const empty = document.getElementById('roles-empty-state');
  934. if (!tbody) return;
  935. const roles = state.roles || [];
  936. if (roles.length === 0) {
  937. tbody.innerHTML = '';
  938. empty?.classList.remove('hidden');
  939. return;
  940. }
  941. empty?.classList.add('hidden');
  942. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  943. if (tbody.dataset.sig === sig) return;
  944. tbody.dataset.sig = sig;
  945. tbody.innerHTML = roles.map(r => {
  946. const colorKey = (r.color || 'blue').toLowerCase();
  947. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  948. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  949. const ifacesChips = ifaces.length > 0
  950. ? 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('')
  951. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  952. return `
  953. <tr class="hover:bg-slate-800/40 transition">
  954. <td class="py-3 px-4">
  955. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  956. ${escapeHtml(r.name)}
  957. </span>
  958. </td>
  959. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  960. <span>${escapeHtml(r.name)}</span>
  961. ${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>' : ''}
  962. </td>
  963. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  964. <span class="inline-flex items-center gap-1.5">
  965. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  966. <span>${escapeHtml(r.color || 'blue')}</span>
  967. </span>
  968. </td>
  969. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  970. <td class="py-3 px-4 font-sans">
  971. <div class="flex flex-wrap items-center">
  972. ${ifacesChips}
  973. </div>
  974. </td>
  975. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  976. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  977. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  978. Edit
  979. </button>
  980. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  981. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  982. Delete
  983. </button>
  984. </td>
  985. </tr>
  986. `;
  987. }).join('');
  988. }
  989. function openRoleModal(id = null) {
  990. const modal = document.getElementById('role-modal');
  991. if (!modal) return;
  992. const idInput = document.getElementById('role-modal-id');
  993. const nameInput = document.getElementById('role-modal-name');
  994. const colorSelect = document.getElementById('role-modal-color');
  995. const descInput = document.getElementById('role-modal-desc');
  996. const title = document.getElementById('role-modal-title');
  997. if (id) {
  998. const role = (state.roles || []).find(r => r.id === id);
  999. if (role) {
  1000. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1001. if (idInput) idInput.value = role.id;
  1002. if (nameInput) nameInput.value = role.name;
  1003. if (colorSelect) colorSelect.value = role.color || 'blue';
  1004. if (descInput) descInput.value = role.description || '';
  1005. }
  1006. } else {
  1007. if (title) title.innerText = 'Add Role Tag';
  1008. if (idInput) idInput.value = '';
  1009. if (nameInput) nameInput.value = '';
  1010. if (colorSelect) colorSelect.value = 'blue';
  1011. if (descInput) descInput.value = '';
  1012. }
  1013. updateRoleModalPreview();
  1014. modal.classList.remove('hidden');
  1015. }
  1016. function closeRoleModal() {
  1017. const modal = document.getElementById('role-modal');
  1018. if (modal) modal.classList.add('hidden');
  1019. }
  1020. function updateRoleModalPreview() {
  1021. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1022. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1023. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1024. const preview = document.getElementById('role-modal-preview');
  1025. if (preview) {
  1026. preview.innerText = name;
  1027. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1028. }
  1029. }
  1030. async function submitSaveRole(e) {
  1031. e.preventDefault();
  1032. const id = document.getElementById('role-modal-id')?.value;
  1033. const name = document.getElementById('role-modal-name')?.value.trim();
  1034. const color = document.getElementById('role-modal-color')?.value;
  1035. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1036. if (!name) return;
  1037. try {
  1038. const payload = { id, name, color, description: desc };
  1039. const method = id ? 'PUT' : 'POST';
  1040. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1041. const res = await fetch(url, {
  1042. method,
  1043. headers: { 'Content-Type': 'application/json' },
  1044. body: JSON.stringify(payload)
  1045. });
  1046. if (res.ok) {
  1047. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1048. closeRoleModal();
  1049. await loadRoles();
  1050. fetchData(false);
  1051. } else {
  1052. const err = await res.json();
  1053. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1054. }
  1055. } catch (err) {
  1056. showToast('Error', err.message, 'error');
  1057. }
  1058. }
  1059. async function deleteRoleTag(id, name) {
  1060. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1061. try {
  1062. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1063. method: 'DELETE'
  1064. });
  1065. if (res.ok) {
  1066. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1067. await loadRoles();
  1068. fetchData(false);
  1069. } else {
  1070. const err = await res.json();
  1071. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1072. }
  1073. } catch (err) {
  1074. showToast('Error', err.message, 'error');
  1075. }
  1076. }
  1077. function populateRoleSelects(selectedRole = '') {
  1078. const ifaceSelect = document.getElementById('modal-iface-role');
  1079. const vlanSelect = document.getElementById('vlan-role');
  1080. const roles = state.roles || [];
  1081. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1082. if (ifaceSelect) {
  1083. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1084. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1085. ifaceSelect.innerHTML = optionsHtml;
  1086. ifaceSelect.dataset.optionsSig = optionsHtml;
  1087. }
  1088. if (currentVal) ifaceSelect.value = currentVal;
  1089. }
  1090. if (vlanSelect) {
  1091. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1092. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1093. vlanSelect.innerHTML = optionsHtml;
  1094. vlanSelect.dataset.optionsSig = optionsHtml;
  1095. }
  1096. if (currentVal) vlanSelect.value = currentVal;
  1097. }
  1098. }
  1099. // Filter and Render Hierarchical Interfaces List
  1100. function filterIfaces(filter) {
  1101. state.ifaceFilter = filter || 'all';
  1102. renderInterfacesList();
  1103. }
  1104. function renderInterfacesList() {
  1105. const tbody = document.getElementById('interfaces-tree-tbody');
  1106. const emptyState = document.getElementById('interfaces-empty-state');
  1107. const summary = document.getElementById('ifaces-list-summary');
  1108. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1109. const allIfaces = state.interfaces || [];
  1110. const allVlans = state.vlans || [];
  1111. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1112. const filteredParents = parentIfaces.filter(parent => {
  1113. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1114. if (query) {
  1115. const matchName = parent.name.toLowerCase().includes(query);
  1116. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1117. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1118. const matchType = (parent.type || '').toLowerCase().includes(query);
  1119. const matchVlan = childVlans.some(v =>
  1120. v.name.toLowerCase().includes(query) ||
  1121. String(v.vlan_id).includes(query) ||
  1122. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1123. (v.description || '').toLowerCase().includes(query)
  1124. );
  1125. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1126. }
  1127. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1128. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1129. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1130. return true;
  1131. });
  1132. if (summary) {
  1133. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1134. }
  1135. if (filteredParents.length === 0) {
  1136. emptyState?.classList.remove('hidden');
  1137. tbody.innerHTML = '';
  1138. return;
  1139. }
  1140. emptyState?.classList.add('hidden');
  1141. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1142. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1143. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1144. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1145. }).join(';');
  1146. if (tbody.dataset.sig === sig) {
  1147. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1148. }
  1149. tbody.dataset.sig = sig;
  1150. tbody.innerHTML = '';
  1151. filteredParents.forEach(parent => {
  1152. const isUp = parent.state === 'UP';
  1153. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1154. const hasVlans = childVlans.length > 0;
  1155. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1156. const canHaveVlan = supportsVLAN(parent);
  1157. const parentRow = document.createElement('tr');
  1158. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1159. parentRow.innerHTML = `
  1160. <td class="py-3 px-3 text-center">
  1161. ${hasVlans ? `
  1162. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1163. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1164. <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">
  1165. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1166. </svg>
  1167. </button>
  1168. ` : `
  1169. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1170. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1171. </div>
  1172. `}
  1173. </td>
  1174. <td class="py-3 px-4">
  1175. <div class="flex items-center space-x-2.5">
  1176. <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">
  1177. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1178. </div>
  1179. <div>
  1180. <div class="flex items-center gap-2">
  1181. <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'}">
  1182. <span>${parent.name}</span>
  1183. <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>
  1184. </span>
  1185. ${hasVlans ? `
  1186. <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>
  1187. ` : `
  1188. <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>
  1189. `}
  1190. </div>
  1191. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1192. </div>
  1193. </div>
  1194. </td>
  1195. <td class="py-3 px-4 font-sans">
  1196. <div class="flex items-center gap-1.5">
  1197. ${getRoleBadge(parent.role || 'LAN')}
  1198. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1199. </div>
  1200. </td>
  1201. <td class="py-3 px-4">
  1202. ${parent.ipv4 && parent.ipv4.length > 0
  1203. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1204. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1205. }
  1206. ${(() => {
  1207. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1208. if (!c) return '';
  1209. 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');
  1210. 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>`;
  1211. })()}
  1212. </td>
  1213. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1214. <div>${parent.mac || 'N/A'}</div>
  1215. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1216. </td>
  1217. <td class="py-3 px-4 text-[11px]">
  1218. <div class="flex items-center space-x-2">
  1219. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1220. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1221. </div>
  1222. </td>
  1223. <td class="py-3 px-4 font-sans">
  1224. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1225. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1226. 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'
  1227. }" title="Click to toggle link status">
  1228. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1229. <span>${parent.state}</span>
  1230. </button>
  1231. </td>
  1232. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1233. ${(() => {
  1234. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1235. if (c) {
  1236. 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>`;
  1237. }
  1238. if (!supportsDHCPClient(parent)) {
  1239. return '';
  1240. }
  1241. 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>`;
  1242. })()}
  1243. ${canHaveVlan ? `
  1244. <button onclick="openVlanModal('${parent.name}')"
  1245. 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">
  1246. + Add VLAN
  1247. </button>
  1248. ` : ''}
  1249. <button onclick="openIfaceModal('${parent.name}')"
  1250. 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">
  1251. Edit
  1252. </button>
  1253. </td>
  1254. `;
  1255. tbody.appendChild(parentRow);
  1256. if (isExpanded) {
  1257. const drawerRow = document.createElement('tr');
  1258. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1259. const drawerCell = document.createElement('td');
  1260. drawerCell.colSpan = 8;
  1261. drawerCell.className = 'p-0';
  1262. drawerCell.innerHTML = `
  1263. <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">
  1264. <div class="flex items-center justify-between mb-3">
  1265. <div class="flex items-center space-x-3">
  1266. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1267. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1268. </span>
  1269. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1270. ${childVlans.length} Attached
  1271. </span>
  1272. </div>
  1273. <button onclick="openVlanModal('${parent.name}')"
  1274. 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">
  1275. <span>+ Create VLAN on ${parent.name}</span>
  1276. </button>
  1277. </div>
  1278. ${childVlans.length === 0 ? `
  1279. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1280. <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>
  1281. <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">
  1282. <span>+ Create Your First VLAN on ${parent.name}</span>
  1283. </button>
  1284. </div>
  1285. ` : `
  1286. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1287. <table class="w-full text-left text-xs font-mono">
  1288. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1289. <tr>
  1290. <th class="py-2.5 px-4">VLAN ID</th>
  1291. <th class="py-2.5 px-4">Interface Device</th>
  1292. <th class="py-2.5 px-4">Subnet Gateway</th>
  1293. <th class="py-2.5 px-4">Role / Alias</th>
  1294. <th class="py-2.5 px-4">MTU</th>
  1295. <th class="py-2.5 px-4">Throughput</th>
  1296. <th class="py-2.5 px-4">Status</th>
  1297. <th class="py-2.5 px-4 text-right">Actions</th>
  1298. </tr>
  1299. </thead>
  1300. <tbody class="divide-y divide-slate-800/70">
  1301. ${childVlans.map(v => {
  1302. const isVlanUp = v.state === 'UP';
  1303. return `
  1304. <tr class="hover:bg-slate-800/40 transition">
  1305. <td class="py-2.5 px-4">
  1306. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1307. VLAN ${v.vlan_id}
  1308. </span>
  1309. </td>
  1310. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1311. <span class="text-cyan-500">└─</span>
  1312. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1313. <span>${v.name}</span>
  1314. <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>
  1315. </span>
  1316. </td>
  1317. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1318. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1319. ${(() => {
  1320. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1321. if (!c) return '';
  1322. 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';
  1323. 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>`;
  1324. })()}
  1325. </td>
  1326. <td class="py-2.5 px-4 font-sans text-slate-300">
  1327. <div class="flex items-center gap-1.5">
  1328. ${getRoleBadge(v.role || 'LAN')}
  1329. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1330. </div>
  1331. </td>
  1332. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1333. <td class="py-2.5 px-4 text-[11px]">
  1334. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1335. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1336. </td>
  1337. <td class="py-2.5 px-4 font-sans">
  1338. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1339. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1340. 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'
  1341. }">
  1342. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1343. <span>${v.state}</span>
  1344. </button>
  1345. </td>
  1346. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1347. ${(() => {
  1348. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1349. if (c) {
  1350. 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>`;
  1351. }
  1352. if (!supportsDHCPClient(v)) {
  1353. return '';
  1354. }
  1355. 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>`;
  1356. })()}
  1357. <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>
  1358. <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>
  1359. </td>
  1360. </tr>
  1361. `;
  1362. }).join('')}
  1363. </tbody>
  1364. </table>
  1365. </div>
  1366. `}
  1367. </div>
  1368. `;
  1369. drawerRow.appendChild(drawerCell);
  1370. tbody.appendChild(drawerRow);
  1371. }
  1372. });
  1373. }
  1374. // Render VLANs Dedicated View
  1375. function renderVlansList() {
  1376. const tbody = document.getElementById('vlans-table-body');
  1377. if (!tbody) return;
  1378. const emptyState = document.getElementById('vlans-empty-state');
  1379. const countBadge = document.getElementById('vlans-table-count');
  1380. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1381. const allVlans = state.vlans || [];
  1382. if (countBadge) countBadge.innerText = allVlans.length;
  1383. const filtered = allVlans.filter(v => {
  1384. if (!query) return true;
  1385. return v.name.toLowerCase().includes(query) ||
  1386. String(v.vlan_id).includes(query) ||
  1387. (v.description || '').toLowerCase().includes(query) ||
  1388. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1389. });
  1390. if (allVlans.length === 0) {
  1391. emptyState.classList.remove('hidden');
  1392. tbody.innerHTML = '';
  1393. return;
  1394. }
  1395. emptyState.classList.add('hidden');
  1396. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1397. if (tbody.dataset.sig === sig) return;
  1398. tbody.dataset.sig = sig;
  1399. tbody.innerHTML = '';
  1400. filtered.forEach(v => {
  1401. const isUp = v.state === 'UP';
  1402. const tr = document.createElement('tr');
  1403. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1404. tr.innerHTML = `
  1405. <td class="py-3 px-4">
  1406. <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">
  1407. VLAN ${v.vlan_id}
  1408. </span>
  1409. </td>
  1410. <td class="py-3 px-4 font-bold text-white">
  1411. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1412. <span>${v.name}</span>
  1413. <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>
  1414. </span>
  1415. </td>
  1416. <td class="py-3 px-4 text-slate-300">
  1417. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1418. </td>
  1419. <td class="py-3 px-4 text-emerald-400 font-medium">
  1420. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1421. </td>
  1422. <td class="py-3 px-4 text-slate-300 font-sans">
  1423. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1424. </td>
  1425. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1426. <td class="py-3 px-4 font-sans">
  1427. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1428. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1429. 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'
  1430. }">
  1431. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1432. <span>${v.state}</span>
  1433. </button>
  1434. </td>
  1435. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1436. <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>
  1437. <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>
  1438. </td>
  1439. `;
  1440. tbody.appendChild(tr);
  1441. });
  1442. }
  1443. // Toggle interface UP / DOWN
  1444. async function toggleInterfaceState(name, newState) {
  1445. try {
  1446. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1447. method: 'POST',
  1448. headers: { 'Content-Type': 'application/json' },
  1449. body: JSON.stringify({ state: newState })
  1450. });
  1451. const data = await res.json();
  1452. if (res.ok) {
  1453. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1454. fetchData(false);
  1455. } else {
  1456. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1457. }
  1458. } catch (err) {
  1459. showToast('Error', err.message, 'error');
  1460. }
  1461. }
  1462. // ---------------- MikroTik Flag & Utilities ----------------
  1463. function renderMikroTikFlag(running, disabled) {
  1464. if (running) {
  1465. 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>`;
  1466. }
  1467. if (disabled) {
  1468. 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>`;
  1469. }
  1470. 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>`;
  1471. }
  1472. function copyToClipboard(text, label = 'Text') {
  1473. navigator.clipboard.writeText(text).then(() => {
  1474. showToast('Copied', `${label} copied to clipboard`, 'success');
  1475. }).catch(() => {
  1476. prompt('Copy value:', text);
  1477. });
  1478. }
  1479. // ======================== PPP Profiles Shared Helper ========================
  1480. async function fetchPPPProfilesList() {
  1481. try {
  1482. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1483. if (res.ok) {
  1484. state.pppProfiles = await res.json();
  1485. }
  1486. } catch (err) {
  1487. console.error('Failed to load PPP profiles:', err);
  1488. }
  1489. }
  1490. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1491. const sel = document.getElementById(selectId);
  1492. if (!sel) return;
  1493. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1494. { name: 'default', use_encryption: 'no' },
  1495. { name: 'default-encryption', use_encryption: 'required' }
  1496. ];
  1497. sel.innerHTML = '';
  1498. profiles.forEach(p => {
  1499. const opt = document.createElement('option');
  1500. opt.value = p.name;
  1501. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1502. opt.innerText = `${p.name}${encBadge}`;
  1503. sel.appendChild(opt);
  1504. });
  1505. if (selectedVal) {
  1506. sel.value = selectedVal;
  1507. } else {
  1508. sel.value = defaultVal;
  1509. }
  1510. if (!sel.value && sel.options.length > 0) {
  1511. sel.selectedIndex = 0;
  1512. }
  1513. }
  1514. // ======================== PPPoE Multi-Instance ========================
  1515. async function loadPPPoE(populateInputs = true) {
  1516. try {
  1517. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1518. await fetchPPPProfilesList();
  1519. }
  1520. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1521. const list = await res.json();
  1522. state.pppoeList = Array.isArray(list) ? list : [];
  1523. const badge = document.getElementById('pppoe-count-badge');
  1524. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1525. const tbody = document.getElementById('pppoe-table-body');
  1526. const empty = document.getElementById('pppoe-empty');
  1527. if (!tbody) return;
  1528. tbody.innerHTML = '';
  1529. if (state.pppoeList.length === 0) {
  1530. if (empty) empty.classList.remove('hidden');
  1531. } else {
  1532. if (empty) empty.classList.add('hidden');
  1533. state.pppoeList.forEach(inst => {
  1534. const tr = document.createElement('tr');
  1535. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1536. tr.innerHTML = `
  1537. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1538. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1539. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1540. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1541. <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>
  1542. <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>
  1543. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1544. <td class="py-2.5 px-3 text-center">
  1545. <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'}">
  1546. ${inst.default_route ? 'Yes' : 'No'}
  1547. </span>
  1548. </td>
  1549. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1550. ${inst.running ? `
  1551. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1552. ` : `
  1553. <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>
  1554. `}
  1555. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1556. ${inst.disabled ? 'Enable' : 'Disable'}
  1557. </button>
  1558. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1559. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1560. </td>
  1561. `;
  1562. tbody.appendChild(tr);
  1563. });
  1564. }
  1565. } catch (err) {
  1566. console.error('Failed to load PPPoE:', err);
  1567. }
  1568. }
  1569. function openAddPPPoEModal() {
  1570. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1571. document.getElementById('pppoe-modal-edit-orig').value = '';
  1572. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1573. document.getElementById('pppoe-modal-name').readOnly = false;
  1574. document.getElementById('pppoe-modal-user').value = '';
  1575. document.getElementById('pppoe-modal-pass').value = '';
  1576. document.getElementById('pppoe-modal-service').value = '';
  1577. document.getElementById('pppoe-modal-mtu').value = '1492';
  1578. document.getElementById('pppoe-modal-defroute').checked = true;
  1579. document.getElementById('pppoe-modal-reconnect').checked = true;
  1580. document.getElementById('pppoe-modal-disabled').checked = false;
  1581. // Populate profiles
  1582. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1583. // Populate interfaces
  1584. const sel = document.getElementById('pppoe-modal-iface');
  1585. sel.innerHTML = '';
  1586. (state.interfaces || []).forEach(i => {
  1587. if (i.name === 'lo') return;
  1588. const opt = document.createElement('option');
  1589. opt.value = i.name;
  1590. opt.innerText = `${i.name} (${i.role || i.type})`;
  1591. sel.appendChild(opt);
  1592. });
  1593. document.getElementById('pppoe-modal').classList.remove('hidden');
  1594. }
  1595. function openEditPPPoEModal(name) {
  1596. const inst = (state.pppoeList || []).find(i => i.name === name);
  1597. if (!inst) return;
  1598. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1599. document.getElementById('pppoe-modal-edit-orig').value = name;
  1600. document.getElementById('pppoe-modal-name').value = inst.name;
  1601. document.getElementById('pppoe-modal-name').readOnly = true;
  1602. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1603. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1604. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1605. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1606. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1607. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1608. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1609. // Populate profiles
  1610. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1611. const sel = document.getElementById('pppoe-modal-iface');
  1612. sel.innerHTML = '';
  1613. (state.interfaces || []).forEach(i => {
  1614. if (i.name === 'lo') return;
  1615. const opt = document.createElement('option');
  1616. opt.value = i.name;
  1617. opt.innerText = `${i.name} (${i.role || i.type})`;
  1618. if (i.name === inst.interface) opt.selected = true;
  1619. sel.appendChild(opt);
  1620. });
  1621. document.getElementById('pppoe-modal').classList.remove('hidden');
  1622. }
  1623. function closePPPoEModal() {
  1624. document.getElementById('pppoe-modal').classList.add('hidden');
  1625. }
  1626. async function submitSavePPPoE(e) {
  1627. e.preventDefault();
  1628. const name = document.getElementById('pppoe-modal-name').value.trim();
  1629. const iface = document.getElementById('pppoe-modal-iface').value;
  1630. const user = document.getElementById('pppoe-modal-user').value.trim();
  1631. const pass = document.getElementById('pppoe-modal-pass').value;
  1632. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1633. const service = document.getElementById('pppoe-modal-service').value.trim();
  1634. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1635. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1636. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1637. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1638. try {
  1639. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1640. method: 'POST',
  1641. headers: { 'Content-Type': 'application/json' },
  1642. body: JSON.stringify({
  1643. name,
  1644. interface: iface,
  1645. username: user,
  1646. password: pass,
  1647. profile: profile,
  1648. service_name: service,
  1649. mtu,
  1650. default_route: defRoute,
  1651. auto_reconnect: reconnect,
  1652. disabled
  1653. })
  1654. });
  1655. if (res.ok) {
  1656. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1657. closePPPoEModal();
  1658. loadPPPoE(false);
  1659. fetchData(false);
  1660. } else {
  1661. const err = await res.json();
  1662. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1663. }
  1664. } catch (err) {
  1665. showToast('Error', err.message, 'error');
  1666. }
  1667. }
  1668. async function connectPPPoEInstance(name) {
  1669. try {
  1670. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1671. if (res.ok) {
  1672. showToast('Connecting', `Dialing ${name}...`, 'info');
  1673. setTimeout(() => loadPPPoE(false), 2000);
  1674. }
  1675. } catch (err) {
  1676. showToast('Error', err.message, 'error');
  1677. }
  1678. }
  1679. async function disconnectPPPoEInstance(name) {
  1680. try {
  1681. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1682. if (res.ok) {
  1683. showToast('Disconnected', `${name} session terminated`, 'info');
  1684. setTimeout(() => loadPPPoE(false), 1000);
  1685. }
  1686. } catch (err) {
  1687. showToast('Error', err.message, 'error');
  1688. }
  1689. }
  1690. async function togglePPPoEState(name, enable) {
  1691. try {
  1692. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1693. method: 'POST',
  1694. headers: { 'Content-Type': 'application/json' },
  1695. body: JSON.stringify({ enabled: enable })
  1696. });
  1697. if (res.ok) {
  1698. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1699. loadPPPoE(false);
  1700. }
  1701. } catch (err) {
  1702. showToast('Error', err.message, 'error');
  1703. }
  1704. }
  1705. async function deletePPPoEInstance(name) {
  1706. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1707. try {
  1708. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1709. if (res.ok) {
  1710. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1711. loadPPPoE(false);
  1712. fetchData(false);
  1713. }
  1714. } catch (err) {
  1715. showToast('Error', err.message, 'error');
  1716. }
  1717. }
  1718. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1719. state.wgSubTab = 'ifaces';
  1720. function switchWGSubTab(tab) {
  1721. state.wgSubTab = tab;
  1722. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1723. const peersPanel = document.getElementById('wg-subtab-peers');
  1724. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1725. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1726. if (tab === 'ifaces') {
  1727. ifacesPanel?.classList.remove('hidden');
  1728. peersPanel?.classList.add('hidden');
  1729. 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';
  1730. 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';
  1731. } else {
  1732. ifacesPanel?.classList.add('hidden');
  1733. peersPanel?.classList.remove('hidden');
  1734. 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';
  1735. 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';
  1736. renderWGPeers();
  1737. }
  1738. }
  1739. async function loadWireGuard(populateInputs = true) {
  1740. try {
  1741. const [ifacesRes, peersRes] = await Promise.all([
  1742. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1743. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1744. ]);
  1745. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1746. const peers = peersRes.ok ? await peersRes.json() : [];
  1747. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1748. state.wgPeers = Array.isArray(peers) ? peers : [];
  1749. // Badges
  1750. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1751. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1752. const peersCountBadge = document.getElementById('wg-peers-count');
  1753. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1754. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1755. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1756. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1757. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1758. // Render Interfaces
  1759. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1760. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1761. if (ifacesTbody) {
  1762. ifacesTbody.innerHTML = '';
  1763. if (state.wgInterfaces.length === 0) {
  1764. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1765. } else {
  1766. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1767. state.wgInterfaces.forEach(iface => {
  1768. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1769. const tr = document.createElement('tr');
  1770. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1771. tr.innerHTML = `
  1772. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1773. <td class="py-2.5 px-3">
  1774. <div class="flex items-center gap-1.5">
  1775. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1776. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1777. </div>
  1778. </td>
  1779. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1780. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1781. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1782. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1783. ${(iface.public_key || '').substring(0, 10)}... 📋
  1784. </span>
  1785. </td>
  1786. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1787. <td class="py-2.5 px-3 text-center">
  1788. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1789. </td>
  1790. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1791. ${iface.running ? `
  1792. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1793. ` : `
  1794. <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>
  1795. `}
  1796. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1797. ${iface.disabled ? 'Enable' : 'Disable'}
  1798. </button>
  1799. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1800. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1801. </td>
  1802. `;
  1803. ifacesTbody.appendChild(tr);
  1804. });
  1805. }
  1806. }
  1807. // Populate filter dropdown in peers tab
  1808. const filterSel = document.getElementById('wg-peers-filter-iface');
  1809. if (filterSel) {
  1810. const currentVal = filterSel.value;
  1811. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1812. state.wgInterfaces.forEach(i => {
  1813. const opt = document.createElement('option');
  1814. opt.value = i.name;
  1815. opt.innerText = i.name;
  1816. if (i.name === currentVal) opt.selected = true;
  1817. filterSel.appendChild(opt);
  1818. });
  1819. }
  1820. renderWGPeers();
  1821. } catch (err) {
  1822. console.error('Failed to load WireGuard:', err);
  1823. }
  1824. }
  1825. function formatWGPeerEndpoint(address, port) {
  1826. if (!address || address === '(none)') return '--';
  1827. let addr = address.trim();
  1828. let p = port || 0;
  1829. while (addr.includes(':') && !addr.startsWith('[')) {
  1830. const lastColon = addr.lastIndexOf(':');
  1831. const maybePort = addr.substring(lastColon + 1);
  1832. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1833. if (!p) p = parseInt(maybePort, 10);
  1834. addr = addr.substring(0, lastColon);
  1835. } else {
  1836. break;
  1837. }
  1838. }
  1839. return p ? `${addr}:${p}` : addr;
  1840. }
  1841. function renderWGPeers() {
  1842. const filterSel = document.getElementById('wg-peers-filter-iface');
  1843. const selectedIface = filterSel ? filterSel.value : '';
  1844. const tbody = document.getElementById('wg-peers-table-body');
  1845. const empty = document.getElementById('wg-peers-empty');
  1846. if (!tbody) return;
  1847. tbody.innerHTML = '';
  1848. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1849. if (filtered.length === 0) {
  1850. if (empty) empty.classList.remove('hidden');
  1851. } else {
  1852. if (empty) empty.classList.add('hidden');
  1853. filtered.forEach(p => {
  1854. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1855. const tr = document.createElement('tr');
  1856. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1857. tr.innerHTML = `
  1858. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1859. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1860. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1861. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1862. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1863. ${(p.public_key || '').substring(0, 10)}... 📋
  1864. </span>
  1865. </td>
  1866. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1867. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1868. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1869. <td class="py-2.5 px-3 font-mono text-[11px]">
  1870. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1871. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1872. </td>
  1873. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1874. <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">
  1875. ${p.disabled ? 'Enable' : 'Disable'}
  1876. </button>
  1877. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1878. <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>
  1879. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1880. </td>
  1881. `;
  1882. tbody.appendChild(tr);
  1883. });
  1884. }
  1885. }
  1886. function openAddWGInterfaceModal() {
  1887. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1888. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1889. const nameEl = document.getElementById('wg-iface-modal-name');
  1890. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1891. nameEl.readOnly = false;
  1892. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1893. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1894. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1895. document.getElementById('wg-iface-modal-comment').value = '';
  1896. document.getElementById('wg-iface-modal-pubkey').value = '';
  1897. document.getElementById('wg-iface-modal-privkey').value = '';
  1898. document.getElementById('wg-iface-modal-disabled').checked = false;
  1899. generateWGInterfaceKeys();
  1900. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1901. }
  1902. function openEditWGInterfaceModal(name) {
  1903. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1904. if (!iface) return;
  1905. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1906. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1907. const nameEl = document.getElementById('wg-iface-modal-name');
  1908. nameEl.value = iface.name;
  1909. nameEl.readOnly = false; // ALLOW RENAMING
  1910. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1911. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1912. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1913. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1914. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1915. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1916. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1917. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1918. }
  1919. function closeAddWGInterfaceModal() {
  1920. document.getElementById('wg-iface-modal').classList.add('hidden');
  1921. }
  1922. async function generateWGInterfaceKeys() {
  1923. try {
  1924. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1925. const keys = await res.json();
  1926. if (res.ok) {
  1927. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1928. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1929. }
  1930. } catch (err) {
  1931. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1932. }
  1933. }
  1934. async function onWGInterfacePrivKeyInput() {
  1935. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1936. if (!privKey) return;
  1937. try {
  1938. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1939. method: 'POST',
  1940. headers: { 'Content-Type': 'application/json' },
  1941. body: JSON.stringify({ private_key: privKey })
  1942. });
  1943. if (res.ok) {
  1944. const data = await res.json();
  1945. if (data.public_key) {
  1946. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1947. }
  1948. }
  1949. } catch (err) {
  1950. // Ignore while typing
  1951. }
  1952. }
  1953. function toggleWGPrivKeyVisibility() {
  1954. const el = document.getElementById('wg-iface-modal-privkey');
  1955. const btn = document.getElementById('btn-toggle-wg-privkey');
  1956. if (el.type === 'password') {
  1957. el.type = 'text';
  1958. btn.innerText = '🙈 Hide';
  1959. } else {
  1960. el.type = 'password';
  1961. btn.innerText = '👁️ Show';
  1962. }
  1963. }
  1964. function copyWGInterfacePubKey() {
  1965. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1966. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1967. }
  1968. async function submitSaveWGInterface(e) {
  1969. e.preventDefault();
  1970. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1971. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1972. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1973. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1974. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1975. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1976. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1977. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1978. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1979. try {
  1980. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1981. method: 'POST',
  1982. headers: { 'Content-Type': 'application/json' },
  1983. body: JSON.stringify({
  1984. orig_name: origName,
  1985. name,
  1986. listen_port: port,
  1987. address: addr,
  1988. mtu,
  1989. comment,
  1990. public_key: pub,
  1991. private_key: priv,
  1992. disabled
  1993. })
  1994. });
  1995. const data = await res.json();
  1996. if (res.ok) {
  1997. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1998. closeAddWGInterfaceModal();
  1999. loadWireGuard(false);
  2000. fetchData(false);
  2001. } else {
  2002. showToast('Error', data.error || 'Failed to save interface', 'error');
  2003. }
  2004. } catch (err) {
  2005. showToast('Error', err.message, 'error');
  2006. }
  2007. }
  2008. async function startWGInterface(name) {
  2009. try {
  2010. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2011. if (res.ok) {
  2012. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2013. loadWireGuard(false);
  2014. fetchData(false);
  2015. }
  2016. } catch (err) {
  2017. showToast('Error', err.message, 'error');
  2018. }
  2019. }
  2020. async function stopWGInterface(name) {
  2021. try {
  2022. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2023. if (res.ok) {
  2024. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2025. loadWireGuard(false);
  2026. fetchData(false);
  2027. }
  2028. } catch (err) {
  2029. showToast('Error', err.message, 'error');
  2030. }
  2031. }
  2032. async function toggleWGInterfaceState(name, enable) {
  2033. try {
  2034. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2035. method: 'POST',
  2036. headers: { 'Content-Type': 'application/json' },
  2037. body: JSON.stringify({ enabled: enable })
  2038. });
  2039. if (res.ok) {
  2040. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2041. loadWireGuard(false);
  2042. fetchData(false);
  2043. }
  2044. } catch (err) {
  2045. showToast('Error', err.message, 'error');
  2046. }
  2047. }
  2048. async function deleteWGInterface(name) {
  2049. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2050. try {
  2051. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2052. if (res.ok) {
  2053. showToast('Deleted', `Interface ${name} removed`, 'success');
  2054. loadWireGuard(false);
  2055. fetchData(false);
  2056. }
  2057. } catch (err) {
  2058. showToast('Error', err.message, 'error');
  2059. }
  2060. }
  2061. function populateWGPeerIfaceSelect(selectedIface = '') {
  2062. const sel = document.getElementById('wg-peer-modal-iface');
  2063. if (!sel) return;
  2064. sel.innerHTML = '';
  2065. (state.wgInterfaces || []).forEach(i => {
  2066. const opt = document.createElement('option');
  2067. opt.value = i.name;
  2068. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2069. if (i.name === selectedIface) opt.selected = true;
  2070. sel.appendChild(opt);
  2071. });
  2072. }
  2073. function openAddWGPeerModal() {
  2074. if ((state.wgInterfaces || []).length === 0) {
  2075. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2076. openAddWGInterfaceModal();
  2077. return;
  2078. }
  2079. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2080. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2081. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2082. populateWGPeerIfaceSelect();
  2083. document.getElementById('wg-peer-modal-name').value = '';
  2084. document.getElementById('wg-peer-modal-pubkey').value = '';
  2085. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2086. document.getElementById('wg-peer-modal-endpoint').value = '';
  2087. document.getElementById('wg-peer-modal-port').value = '';
  2088. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2089. document.getElementById('wg-peer-modal-preshared').value = '';
  2090. document.getElementById('wg-peer-modal-disabled').checked = false;
  2091. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2092. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2093. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2094. }
  2095. function openEditWGPeerModal(ifaceName, pubKey) {
  2096. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2097. if (!peer) {
  2098. showToast('Not Found', 'Peer not found', 'warning');
  2099. return;
  2100. }
  2101. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2102. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2103. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2104. populateWGPeerIfaceSelect(peer.interface);
  2105. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2106. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2107. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2108. let epHost = (peer.endpoint_address || '').trim();
  2109. let epPort = peer.endpoint_port || '';
  2110. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2111. const lastColon = epHost.lastIndexOf(':');
  2112. const maybePort = epHost.substring(lastColon + 1);
  2113. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2114. if (!epPort) epPort = parseInt(maybePort, 10);
  2115. epHost = epHost.substring(0, lastColon);
  2116. } else {
  2117. break;
  2118. }
  2119. }
  2120. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2121. document.getElementById('wg-peer-modal-port').value = epPort;
  2122. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2123. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2124. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2125. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2126. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2127. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2128. }
  2129. function closeAddWGPeerModal() {
  2130. document.getElementById('wg-peer-modal').classList.add('hidden');
  2131. }
  2132. async function generatePeerKeypairHelper() {
  2133. try {
  2134. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2135. const keys = await res.json();
  2136. if (res.ok) {
  2137. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2138. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2139. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2140. checkWGPeerKeyValidity();
  2141. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2142. }
  2143. } catch (err) {
  2144. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2145. }
  2146. }
  2147. function copyGeneratedPeerPrivKey() {
  2148. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2149. if (priv) copyToClipboard(priv, 'Client Private Key');
  2150. }
  2151. async function generatePeerPSK() {
  2152. try {
  2153. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2154. const keys = await res.json();
  2155. if (res.ok && keys.private_key) {
  2156. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2157. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2158. }
  2159. } catch (err) {
  2160. showToast('Error', err.message, 'error');
  2161. }
  2162. }
  2163. function checkWGPeerKeyValidity() {
  2164. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2165. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2166. const warningEl = document.getElementById('wg-peer-key-warning');
  2167. if (!warningEl) return;
  2168. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2169. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2170. warningEl.classList.remove('hidden');
  2171. } else {
  2172. warningEl.classList.add('hidden');
  2173. }
  2174. }
  2175. async function submitSaveWGPeer(e) {
  2176. e.preventDefault();
  2177. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2178. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2179. const iface = document.getElementById('wg-peer-modal-iface').value;
  2180. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2181. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2182. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2183. .split(',')
  2184. .map(s => s.trim())
  2185. .filter(s => s.length > 0);
  2186. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2187. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2188. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2189. const lastColon = epHost.lastIndexOf(':');
  2190. const maybePort = epHost.substring(lastColon + 1);
  2191. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2192. if (!epPort) epPort = parseInt(maybePort, 10);
  2193. epHost = epHost.substring(0, lastColon);
  2194. } else {
  2195. break;
  2196. }
  2197. }
  2198. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2199. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2200. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2201. // Validation
  2202. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2203. if (targetIface && targetIface.public_key === pub) {
  2204. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2205. return;
  2206. }
  2207. try {
  2208. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2209. method: 'POST',
  2210. headers: { 'Content-Type': 'application/json' },
  2211. body: JSON.stringify({
  2212. orig_interface: origIface,
  2213. orig_public_key: origPubKey,
  2214. interface: iface,
  2215. name,
  2216. public_key: pub,
  2217. allowed_ips: allowed,
  2218. endpoint_address: epHost,
  2219. endpoint_port: epPort,
  2220. persistent_keepalive: keepalive,
  2221. preshared_key: psk,
  2222. disabled
  2223. })
  2224. });
  2225. const data = await res.json();
  2226. if (res.ok) {
  2227. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2228. closeAddWGPeerModal();
  2229. loadWireGuard(false);
  2230. } else {
  2231. showToast('Error', data.error || 'Failed to save peer', 'error');
  2232. }
  2233. } catch (err) {
  2234. showToast('Error', err.message, 'error');
  2235. }
  2236. }
  2237. async function toggleWGPeerState(iface, pubkey, enable) {
  2238. try {
  2239. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2240. method: 'POST',
  2241. headers: { 'Content-Type': 'application/json' },
  2242. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2243. });
  2244. const data = await res.json();
  2245. if (res.ok) {
  2246. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2247. loadWireGuard(false);
  2248. } else {
  2249. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2250. }
  2251. } catch (err) {
  2252. showToast('Error', err.message, 'error');
  2253. }
  2254. }
  2255. async function deleteWGPeer(iface, pubkey) {
  2256. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2257. try {
  2258. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2259. method: 'POST',
  2260. headers: { 'Content-Type': 'application/json' },
  2261. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2262. });
  2263. const data = await res.json();
  2264. if (res.ok) {
  2265. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2266. loadWireGuard(false);
  2267. } else {
  2268. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2269. }
  2270. } catch (err) {
  2271. showToast('Error', err.message, 'error');
  2272. }
  2273. }
  2274. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2275. function switchIpsecModalTab(tab) {
  2276. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2277. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2278. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2279. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2280. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2281. if (tab === 'p1') {
  2282. if (p1Tab) {
  2283. 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';
  2284. }
  2285. if (p2Tab) {
  2286. 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';
  2287. }
  2288. if (p1Content) p1Content.classList.remove('hidden');
  2289. if (p2Content) p2Content.classList.add('hidden');
  2290. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2291. } else {
  2292. if (p1Tab) {
  2293. 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';
  2294. }
  2295. if (p2Tab) {
  2296. 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';
  2297. }
  2298. if (p1Content) p1Content.classList.add('hidden');
  2299. if (p2Content) p2Content.classList.remove('hidden');
  2300. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2301. }
  2302. }
  2303. function toggleIpsecPhaseStep() {
  2304. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2305. if (p1Content && !p1Content.classList.contains('hidden')) {
  2306. switchIpsecModalTab('p2');
  2307. } else {
  2308. switchIpsecModalTab('p1');
  2309. }
  2310. }
  2311. function toggleIpsecPskVisibility() {
  2312. const pskInput = document.getElementById('ipsec-modal-psk');
  2313. if (!pskInput) return;
  2314. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2315. }
  2316. function addIpsecLocalSubnet(val = '') {
  2317. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2318. if (!container) return;
  2319. const row = document.createElement('div');
  2320. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2321. row.innerHTML = `
  2322. <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">
  2323. <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>
  2324. `;
  2325. container.appendChild(row);
  2326. }
  2327. function addIpsecRemoteSubnet(val = '') {
  2328. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2329. if (!container) return;
  2330. const row = document.createElement('div');
  2331. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2332. row.innerHTML = `
  2333. <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">
  2334. <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>
  2335. `;
  2336. container.appendChild(row);
  2337. }
  2338. function updateIpsecEspProposalFromPFS(val) {
  2339. const prop = document.getElementById('ipsec-modal-espprop');
  2340. if (!prop) return;
  2341. if (val === 'none') {
  2342. prop.value = 'aes256-sha256,aes128-sha256,default';
  2343. } else {
  2344. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2345. }
  2346. }
  2347. function updateIpsecIkeProposalFromDH(dh) {
  2348. const el = document.getElementById('ipsec-modal-ikeprop');
  2349. if (el) {
  2350. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2351. }
  2352. }
  2353. function safeSetVal(id, val) {
  2354. const el = document.getElementById(id);
  2355. if (el) el.value = val;
  2356. }
  2357. function safeSetChecked(id, val) {
  2358. const el = document.getElementById(id);
  2359. if (el) el.checked = !!val;
  2360. }
  2361. function safeGetVal(id, def = '') {
  2362. const el = document.getElementById(id);
  2363. return el ? el.value : def;
  2364. }
  2365. async function loadIPSec(populateInputs = true) {
  2366. try {
  2367. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2368. const list = await res.json();
  2369. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2370. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2371. const badge = document.getElementById('ipsec-sas-badge');
  2372. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2373. const tbody = document.getElementById('ipsec-table-body');
  2374. const empty = document.getElementById('ipsec-empty');
  2375. if (!tbody) return;
  2376. tbody.innerHTML = '';
  2377. if (state.ipsecTunnels.length === 0) {
  2378. if (empty) empty.classList.remove('hidden');
  2379. } else {
  2380. if (empty) empty.classList.add('hidden');
  2381. state.ipsecTunnels.forEach(c => {
  2382. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2383. const tr = document.createElement('tr');
  2384. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2385. // Local subnets tags
  2386. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2387. 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('');
  2388. // Remote subnets tags
  2389. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2390. 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('');
  2391. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2392. const p2Name = c.phase2_name || `${c.name}_p2`;
  2393. tr.innerHTML = `
  2394. <td class="py-2.5 px-3 text-center">
  2395. ${isEstablished ? `
  2396. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2397. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2398. <span>UP</span>
  2399. </span>
  2400. ` : (c.disabled ? `
  2401. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2402. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2403. <span>DOWN</span>
  2404. </span>
  2405. ` : `
  2406. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2407. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2408. <span>IDLE</span>
  2409. </span>
  2410. `)}
  2411. </td>
  2412. <td class="py-2.5 px-4 font-bold text-white">
  2413. <div class="flex items-center gap-2">
  2414. <span class="text-amber-400">🛡</span>
  2415. <div>
  2416. <div>${escapeHtml(c.name)}</div>
  2417. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2418. </div>
  2419. </div>
  2420. </td>
  2421. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2422. <td class="py-2.5 px-4 font-sans">
  2423. <div class="flex items-center gap-1.5">
  2424. <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>
  2425. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2426. </div>
  2427. </td>
  2428. <td class="py-2.5 px-4">
  2429. <div class="space-y-1">
  2430. <div class="flex items-center flex-wrap gap-1">
  2431. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2432. ${localBadges}
  2433. </div>
  2434. <div class="flex items-center flex-wrap gap-1">
  2435. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2436. ${remoteBadges}
  2437. </div>
  2438. </div>
  2439. </td>
  2440. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2441. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2442. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2443. </div>
  2444. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2445. </td>
  2446. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2447. ${isEstablished ? `
  2448. <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>
  2449. ` : `
  2450. <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>
  2451. `}
  2452. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2453. ${c.disabled ? 'Enable' : 'Disable'}
  2454. </button>
  2455. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2456. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2457. </td>
  2458. `;
  2459. tbody.appendChild(tr);
  2460. });
  2461. }
  2462. } catch (err) {
  2463. console.error('Failed to load IPSec:', err);
  2464. }
  2465. }
  2466. function openAddIPSecModal() {
  2467. const modal = document.getElementById('ipsec-modal');
  2468. if (!modal) return;
  2469. const title = document.getElementById('ipsec-modal-title');
  2470. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2471. // Phase 1 Fields
  2472. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2473. const nameEl = document.getElementById('ipsec-modal-name');
  2474. if (nameEl) nameEl.readOnly = false;
  2475. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2476. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2477. safeSetVal('ipsec-modal-remotegw', '');
  2478. safeSetVal('ipsec-modal-localaddrs', '');
  2479. safeSetVal('ipsec-modal-comments', '');
  2480. safeSetVal('ipsec-modal-psk', '');
  2481. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2482. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2483. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2484. safeSetVal('ipsec-modal-localid', '');
  2485. safeSetVal('ipsec-modal-remoteid', '');
  2486. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2487. // Phase 2 Fields
  2488. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2489. safeSetVal('ipsec-modal-espkeylife', '28800');
  2490. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2491. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2492. safeSetChecked('ipsec-modal-autostart', true);
  2493. safeSetChecked('ipsec-modal-disabled', false);
  2494. // Clear & Populate default dynamic subnets
  2495. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2496. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2497. if (localContainer) {
  2498. localContainer.innerHTML = '';
  2499. addIpsecLocalSubnet('192.168.10.0/24');
  2500. }
  2501. if (remoteContainer) {
  2502. remoteContainer.innerHTML = '';
  2503. addIpsecRemoteSubnet('192.168.20.0/24');
  2504. }
  2505. switchIpsecModalTab('p1');
  2506. modal.classList.remove('hidden');
  2507. }
  2508. function openEditIPSecModal(name) {
  2509. const modal = document.getElementById('ipsec-modal');
  2510. if (!modal) return;
  2511. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2512. if (!conn) return;
  2513. const title = document.getElementById('ipsec-modal-title');
  2514. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2515. // Phase 1 Fields
  2516. safeSetVal('ipsec-modal-name', conn.name);
  2517. const nameEl = document.getElementById('ipsec-modal-name');
  2518. if (nameEl) nameEl.readOnly = true;
  2519. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2520. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2521. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2522. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2523. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2524. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2525. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2526. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2527. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2528. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2529. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2530. // Phase 2 Fields
  2531. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2532. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2533. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2534. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2535. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2536. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2537. // Populate dynamic subnets
  2538. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2539. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2540. if (localContainer) {
  2541. localContainer.innerHTML = '';
  2542. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2543. locals.forEach(s => addIpsecLocalSubnet(s));
  2544. }
  2545. if (remoteContainer) {
  2546. remoteContainer.innerHTML = '';
  2547. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2548. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2549. }
  2550. switchIpsecModalTab('p1');
  2551. modal.classList.remove('hidden');
  2552. }
  2553. function closeAddIPSecModal() {
  2554. const modal = document.getElementById('ipsec-modal');
  2555. if (modal) modal.classList.add('hidden');
  2556. }
  2557. async function submitSaveIPSec(e) {
  2558. if (e) e.preventDefault();
  2559. const name = safeGetVal('ipsec-modal-name').trim();
  2560. if (!name) {
  2561. showToast('Error', 'Tunnel name is required', 'error');
  2562. return;
  2563. }
  2564. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2565. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2566. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2567. const comments = safeGetVal('ipsec-modal-comments').trim();
  2568. const psk = safeGetVal('ipsec-modal-psk');
  2569. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2570. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2571. const localId = safeGetVal('ipsec-modal-localid').trim();
  2572. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2573. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2574. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2575. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2576. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2577. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2578. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2579. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2580. // Scrape dynamic local and remote subnets
  2581. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2582. const localSubnets = [];
  2583. localInputs.forEach(inp => {
  2584. const v = inp.value.trim();
  2585. if (v) localSubnets.push(v);
  2586. });
  2587. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2588. const remoteSubnets = [];
  2589. remoteInputs.forEach(inp => {
  2590. const v = inp.value.trim();
  2591. if (v) remoteSubnets.push(v);
  2592. });
  2593. try {
  2594. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2595. method: 'POST',
  2596. headers: { 'Content-Type': 'application/json' },
  2597. body: JSON.stringify({
  2598. name,
  2599. comment: comments,
  2600. ike_version: ikeVersion,
  2601. local_addrs: localAddrs,
  2602. remote_addrs: remotegw,
  2603. preshared_key: psk,
  2604. ike_proposals: ikeProposals,
  2605. ike_keylife: ikeKeylife,
  2606. local_id: localId,
  2607. remote_id: remoteId,
  2608. dpd: dpd,
  2609. phase2_name: phase2Name,
  2610. esp_proposals: espProposals,
  2611. esp_keylife: espKeylife,
  2612. pfs_group: pfsGroup,
  2613. pfs: pfsGroup !== 'none',
  2614. local_subnets: localSubnets,
  2615. remote_subnets: remoteSubnets,
  2616. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2617. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2618. auto_start: autostart,
  2619. disabled
  2620. })
  2621. });
  2622. if (res.ok) {
  2623. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2624. closeAddIPSecModal();
  2625. loadIPSec(false);
  2626. } else {
  2627. const err = await res.json();
  2628. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2629. }
  2630. } catch (err) {
  2631. showToast('Error', err.message, 'error');
  2632. }
  2633. }
  2634. async function startIPSecTunnel(name) {
  2635. try {
  2636. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2637. if (res.ok) {
  2638. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2639. setTimeout(() => loadIPSec(false), 2000);
  2640. }
  2641. } catch (err) {
  2642. showToast('Error', err.message, 'error');
  2643. }
  2644. }
  2645. async function stopIPSecTunnel(name) {
  2646. try {
  2647. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2648. if (res.ok) {
  2649. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2650. loadIPSec(false);
  2651. }
  2652. } catch (err) {
  2653. showToast('Error', err.message, 'error');
  2654. }
  2655. }
  2656. async function toggleIPSecState(name, enable) {
  2657. try {
  2658. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2659. method: 'POST',
  2660. headers: { 'Content-Type': 'application/json' },
  2661. body: JSON.stringify({ enabled: enable })
  2662. });
  2663. if (res.ok) {
  2664. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2665. loadIPSec(false);
  2666. }
  2667. } catch (err) {
  2668. showToast('Error', err.message, 'error');
  2669. }
  2670. }
  2671. async function deleteIPSecConn(name) {
  2672. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2673. try {
  2674. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2675. if (res.ok) {
  2676. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2677. loadIPSec(false);
  2678. fetchData(false);
  2679. }
  2680. } catch (err) {
  2681. showToast('Error', err.message, 'error');
  2682. }
  2683. }
  2684. // ======================== L2TP Multi-Instance ========================
  2685. async function loadL2TP(populateInputs = true) {
  2686. try {
  2687. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2688. await fetchPPPProfilesList();
  2689. }
  2690. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2691. const list = await res.json();
  2692. state.l2tpList = Array.isArray(list) ? list : [];
  2693. const badge = document.getElementById('l2tp-count-badge');
  2694. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2695. const tbody = document.getElementById('l2tp-table-body');
  2696. const empty = document.getElementById('l2tp-empty');
  2697. if (!tbody) return;
  2698. tbody.innerHTML = '';
  2699. if (state.l2tpList.length === 0) {
  2700. if (empty) empty.classList.remove('hidden');
  2701. } else {
  2702. if (empty) empty.classList.add('hidden');
  2703. state.l2tpList.forEach(inst => {
  2704. const tr = document.createElement('tr');
  2705. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2706. tr.innerHTML = `
  2707. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2708. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2709. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2710. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2711. <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>
  2712. <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>
  2713. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2714. <td class="py-2.5 px-3 text-center">
  2715. <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'}">
  2716. ${inst.default_route ? 'Yes' : 'No'}
  2717. </span>
  2718. </td>
  2719. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2720. ${inst.running ? `
  2721. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2722. ` : `
  2723. <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>
  2724. `}
  2725. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2726. ${inst.disabled ? 'Enable' : 'Disable'}
  2727. </button>
  2728. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2729. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2730. </td>
  2731. `;
  2732. tbody.appendChild(tr);
  2733. });
  2734. }
  2735. } catch (err) {
  2736. console.error('Failed to load L2TP:', err);
  2737. }
  2738. }
  2739. async function openAddL2TPModal() {
  2740. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2741. await fetchPPPProfilesList();
  2742. }
  2743. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2744. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2745. document.getElementById('l2tp-modal-name').readOnly = false;
  2746. document.getElementById('l2tp-modal-server').value = '';
  2747. document.getElementById('l2tp-modal-user').value = '';
  2748. document.getElementById('l2tp-modal-pass').value = '';
  2749. document.getElementById('l2tp-modal-ipsec').value = '';
  2750. document.getElementById('l2tp-modal-defroute').checked = true;
  2751. document.getElementById('l2tp-modal-disabled').checked = false;
  2752. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2753. document.getElementById('l2tp-modal').classList.remove('hidden');
  2754. }
  2755. async function openEditL2TPModal(name) {
  2756. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2757. await fetchPPPProfilesList();
  2758. }
  2759. const inst = (state.l2tpList || []).find(i => i.name === name);
  2760. if (!inst) return;
  2761. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2762. document.getElementById('l2tp-modal-name').value = inst.name;
  2763. document.getElementById('l2tp-modal-name').readOnly = true;
  2764. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2765. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2766. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2767. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2768. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2769. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2770. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2771. document.getElementById('l2tp-modal').classList.remove('hidden');
  2772. }
  2773. function closeL2TPModal() {
  2774. document.getElementById('l2tp-modal').classList.add('hidden');
  2775. }
  2776. async function submitSaveL2TP(e) {
  2777. e.preventDefault();
  2778. const name = document.getElementById('l2tp-modal-name').value.trim();
  2779. const server = document.getElementById('l2tp-modal-server').value.trim();
  2780. const user = document.getElementById('l2tp-modal-user').value.trim();
  2781. const pass = document.getElementById('l2tp-modal-pass').value;
  2782. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2783. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2784. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2785. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2786. try {
  2787. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2788. method: 'POST',
  2789. headers: { 'Content-Type': 'application/json' },
  2790. body: JSON.stringify({
  2791. name,
  2792. connect_to: server,
  2793. username: user,
  2794. password: pass,
  2795. profile: profile,
  2796. ipsec_secret: ipsec,
  2797. default_route: defRoute,
  2798. disabled
  2799. })
  2800. });
  2801. if (res.ok) {
  2802. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2803. closeL2TPModal();
  2804. loadL2TP(false);
  2805. fetchData(false);
  2806. }
  2807. } catch (err) {
  2808. showToast('Error', err.message, 'error');
  2809. }
  2810. }
  2811. async function connectL2TPInstance(name) {
  2812. try {
  2813. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2814. if (res.ok) {
  2815. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2816. setTimeout(() => loadL2TP(false), 2000);
  2817. }
  2818. } catch (err) {
  2819. showToast('Error', err.message, 'error');
  2820. }
  2821. }
  2822. async function disconnectL2TPInstance(name) {
  2823. try {
  2824. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2825. if (res.ok) {
  2826. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2827. loadL2TP(false);
  2828. }
  2829. } catch (err) {
  2830. showToast('Error', err.message, 'error');
  2831. }
  2832. }
  2833. async function toggleL2TPState(name, enable) {
  2834. try {
  2835. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2836. method: 'POST',
  2837. headers: { 'Content-Type': 'application/json' },
  2838. body: JSON.stringify({ enabled: enable })
  2839. });
  2840. if (res.ok) {
  2841. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2842. loadL2TP(false);
  2843. }
  2844. } catch (err) {
  2845. showToast('Error', err.message, 'error');
  2846. }
  2847. }
  2848. async function deleteL2TPInstance(name) {
  2849. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2850. try {
  2851. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2852. if (res.ok) {
  2853. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2854. loadL2TP(false);
  2855. fetchData(false);
  2856. }
  2857. } catch (err) {
  2858. showToast('Error', err.message, 'error');
  2859. }
  2860. }
  2861. // ======================== PPTP Multi-Instance ========================
  2862. async function loadPPTP(populateInputs = true) {
  2863. try {
  2864. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2865. await fetchPPPProfilesList();
  2866. }
  2867. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2868. const list = await res.json();
  2869. state.pptpList = Array.isArray(list) ? list : [];
  2870. const badge = document.getElementById('pptp-count-badge');
  2871. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2872. const tbody = document.getElementById('pptp-table-body');
  2873. const empty = document.getElementById('pptp-empty');
  2874. if (!tbody) return;
  2875. tbody.innerHTML = '';
  2876. if (state.pptpList.length === 0) {
  2877. if (empty) empty.classList.remove('hidden');
  2878. } else {
  2879. if (empty) empty.classList.add('hidden');
  2880. state.pptpList.forEach(inst => {
  2881. const tr = document.createElement('tr');
  2882. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2883. tr.innerHTML = `
  2884. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2885. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2886. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2887. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2888. <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>
  2889. <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>
  2890. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2891. <td class="py-2.5 px-3 text-center">
  2892. <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'}">
  2893. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2894. </span>
  2895. </td>
  2896. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2897. ${inst.running ? `
  2898. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2899. ` : `
  2900. <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>
  2901. `}
  2902. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2903. ${inst.disabled ? 'Enable' : 'Disable'}
  2904. </button>
  2905. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2906. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2907. </td>
  2908. `;
  2909. tbody.appendChild(tr);
  2910. });
  2911. }
  2912. } catch (err) {
  2913. console.error('Failed to load PPTP:', err);
  2914. }
  2915. }
  2916. async function openAddPPTPModal() {
  2917. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2918. await fetchPPPProfilesList();
  2919. }
  2920. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2921. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2922. document.getElementById('pptp-modal-name').readOnly = false;
  2923. document.getElementById('pptp-modal-server').value = '';
  2924. document.getElementById('pptp-modal-user').value = '';
  2925. document.getElementById('pptp-modal-pass').value = '';
  2926. document.getElementById('pptp-modal-mppe').checked = true;
  2927. document.getElementById('pptp-modal-defroute').checked = true;
  2928. document.getElementById('pptp-modal-disabled').checked = false;
  2929. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2930. document.getElementById('pptp-modal').classList.remove('hidden');
  2931. }
  2932. async function openEditPPTPModal(name) {
  2933. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2934. await fetchPPPProfilesList();
  2935. }
  2936. const inst = (state.pptpList || []).find(i => i.name === name);
  2937. if (!inst) return;
  2938. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2939. document.getElementById('pptp-modal-name').value = inst.name;
  2940. document.getElementById('pptp-modal-name').readOnly = true;
  2941. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2942. document.getElementById('pptp-modal-user').value = inst.username || '';
  2943. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2944. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2945. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2946. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2947. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2948. document.getElementById('pptp-modal').classList.remove('hidden');
  2949. }
  2950. function closePPTPModal() {
  2951. document.getElementById('pptp-modal').classList.add('hidden');
  2952. }
  2953. async function submitSavePPTP(e) {
  2954. e.preventDefault();
  2955. const name = document.getElementById('pptp-modal-name').value.trim();
  2956. const server = document.getElementById('pptp-modal-server').value.trim();
  2957. const user = document.getElementById('pptp-modal-user').value.trim();
  2958. const pass = document.getElementById('pptp-modal-pass').value;
  2959. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2960. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2961. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2962. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2963. try {
  2964. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2965. method: 'POST',
  2966. headers: { 'Content-Type': 'application/json' },
  2967. body: JSON.stringify({
  2968. name,
  2969. connect_to: server,
  2970. username: user,
  2971. password: pass,
  2972. profile: profile,
  2973. require_mppe: mppe,
  2974. default_route: defRoute,
  2975. auto_reconnect: true,
  2976. disabled
  2977. })
  2978. });
  2979. if (res.ok) {
  2980. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2981. closePPTPModal();
  2982. loadPPTP(false);
  2983. fetchData(false);
  2984. }
  2985. } catch (err) {
  2986. showToast('Error', err.message, 'error');
  2987. }
  2988. }
  2989. async function connectPPTPInstance(name) {
  2990. try {
  2991. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2992. if (res.ok) {
  2993. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2994. setTimeout(() => loadPPTP(false), 2000);
  2995. }
  2996. } catch (err) {
  2997. showToast('Error', err.message, 'error');
  2998. }
  2999. }
  3000. async function disconnectPPTPInstance(name) {
  3001. try {
  3002. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3003. if (res.ok) {
  3004. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3005. loadPPTP(false);
  3006. }
  3007. } catch (err) {
  3008. showToast('Error', err.message, 'error');
  3009. }
  3010. }
  3011. async function togglePPTPState(name, enable) {
  3012. try {
  3013. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3014. method: 'POST',
  3015. headers: { 'Content-Type': 'application/json' },
  3016. body: JSON.stringify({ enabled: enable })
  3017. });
  3018. if (res.ok) {
  3019. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3020. loadPPTP(false);
  3021. }
  3022. } catch (err) {
  3023. showToast('Error', err.message, 'error');
  3024. }
  3025. }
  3026. async function deletePPTPInstance(name) {
  3027. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3028. try {
  3029. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3030. if (res.ok) {
  3031. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3032. loadPPTP(false);
  3033. fetchData(false);
  3034. }
  3035. } catch (err) {
  3036. showToast('Error', err.message, 'error');
  3037. }
  3038. }
  3039. // ---------------- Modal & Helper Functions ----------------
  3040. function openVlanModal(defaultParent = '') {
  3041. const select = document.getElementById('vlan-parent');
  3042. select.innerHTML = '';
  3043. const allIfaces = state.interfaces || [];
  3044. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3045. if (eligible.length === 0) {
  3046. const opt = document.createElement('option');
  3047. opt.value = '';
  3048. opt.innerText = 'No VLAN-capable interfaces available';
  3049. select.appendChild(opt);
  3050. } else {
  3051. eligible.forEach(i => {
  3052. const opt = document.createElement('option');
  3053. opt.value = i.name;
  3054. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3055. if (i.name === defaultParent) opt.selected = true;
  3056. select.appendChild(opt);
  3057. });
  3058. }
  3059. document.getElementById('vlan-id').value = '';
  3060. document.getElementById('vlan-name').value = '';
  3061. document.getElementById('vlan-ip').value = '';
  3062. document.getElementById('vlan-desc').value = '';
  3063. populateRoleSelects('LAN');
  3064. autoSuggestVlanName();
  3065. document.getElementById('vlan-modal').classList.remove('hidden');
  3066. }
  3067. function closeVlanModal() {
  3068. document.getElementById('vlan-modal').classList.add('hidden');
  3069. }
  3070. function autoSuggestVlanName() {
  3071. const parent = document.getElementById('vlan-parent').value;
  3072. if (!parent) return;
  3073. const id = document.getElementById('vlan-id').value;
  3074. const nameInput = document.getElementById('vlan-name');
  3075. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3076. }
  3077. function setSubnetPreset(cidr) {
  3078. const ipInput = document.getElementById('vlan-ip');
  3079. const id = document.getElementById('vlan-id').value || '10';
  3080. ipInput.value = `192.168.${id}.1${cidr}`;
  3081. }
  3082. async function submitCreateVlan(e) {
  3083. e.preventDefault();
  3084. const btn = document.getElementById('vlan-submit-btn');
  3085. btn.disabled = true;
  3086. btn.innerText = 'Creating...';
  3087. const parent = document.getElementById('vlan-parent').value;
  3088. if (!parent) {
  3089. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3090. btn.disabled = false;
  3091. btn.innerText = 'Create VLAN';
  3092. return;
  3093. }
  3094. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3095. const name = document.getElementById('vlan-name').value.trim();
  3096. const ip = document.getElementById('vlan-ip').value.trim();
  3097. const role = document.getElementById('vlan-role').value;
  3098. const desc = document.getElementById('vlan-desc').value.trim();
  3099. try {
  3100. const res = await fetch(`${API_BASE}/vlans`, {
  3101. method: 'POST',
  3102. headers: { 'Content-Type': 'application/json' },
  3103. body: JSON.stringify({
  3104. parent_name: parent,
  3105. vlan_id: id,
  3106. name: name,
  3107. ip_address: ip,
  3108. role: role,
  3109. description: desc,
  3110. mtu: 1500,
  3111. auto_up: true
  3112. })
  3113. });
  3114. const data = await res.json();
  3115. if (res.ok) {
  3116. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3117. state.expandedParents.add(parent);
  3118. closeVlanModal();
  3119. await fetchData(true);
  3120. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3121. } else {
  3122. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3123. }
  3124. } catch (err) {
  3125. showToast('Error', err.message, 'error');
  3126. } finally {
  3127. btn.disabled = false;
  3128. btn.innerText = 'Create VLAN';
  3129. }
  3130. }
  3131. async function confirmDeleteVlan(name) {
  3132. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3133. try {
  3134. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3135. if (res.ok) {
  3136. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3137. closeIfaceModal();
  3138. fetchData(true);
  3139. }
  3140. } catch (err) {
  3141. showToast('Error', err.message, 'error');
  3142. }
  3143. }
  3144. function openIfaceModal(name) {
  3145. const iface = (state.interfaces || []).find(i => i.name === name);
  3146. if (!iface) return;
  3147. state.currentModalIface = iface.name;
  3148. document.getElementById('modal-iface-name').innerText = iface.name;
  3149. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3150. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3151. populateRoleSelects(iface.role || 'LAN');
  3152. document.getElementById('modal-iface-desc').value = iface.description || '';
  3153. const nameInput = document.getElementById('modal-iface-new-name');
  3154. const renameBtn = document.getElementById('modal-btn-rename');
  3155. const renameHelp = document.getElementById('modal-iface-rename-help');
  3156. if (nameInput) {
  3157. nameInput.value = iface.name;
  3158. if (iface.name === 'lo' || iface.type === 'loopback') {
  3159. nameInput.disabled = true;
  3160. if (renameBtn) renameBtn.disabled = true;
  3161. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3162. } else {
  3163. nameInput.disabled = false;
  3164. if (renameBtn) renameBtn.disabled = false;
  3165. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3166. }
  3167. }
  3168. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3169. if (iface.is_vlan) {
  3170. delBtn.classList.remove('hidden');
  3171. } else {
  3172. delBtn.classList.add('hidden');
  3173. }
  3174. renderModalIPs(iface);
  3175. document.getElementById('iface-modal').classList.remove('hidden');
  3176. }
  3177. function renderModalIPs(iface) {
  3178. const container = document.getElementById('modal-ip-list');
  3179. container.innerHTML = '';
  3180. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3181. if (addrs.length === 0) {
  3182. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3183. return;
  3184. }
  3185. addrs.forEach(addr => {
  3186. const row = document.createElement('div');
  3187. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3188. row.innerHTML = `
  3189. <span class="text-white">${addr}</span>
  3190. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3191. `;
  3192. container.appendChild(row);
  3193. });
  3194. }
  3195. function closeIfaceModal() {
  3196. document.getElementById('iface-modal').classList.add('hidden');
  3197. state.currentModalIface = null;
  3198. }
  3199. async function setIfaceState(name, newState) {
  3200. const target = name || state.currentModalIface;
  3201. if (!target) return;
  3202. await toggleInterfaceState(target, newState);
  3203. const updated = (state.interfaces || []).find(i => i.name === target);
  3204. if (updated) openIfaceModal(target);
  3205. }
  3206. async function applyMTU() {
  3207. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3208. try {
  3209. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3210. method: 'POST',
  3211. headers: { 'Content-Type': 'application/json' },
  3212. body: JSON.stringify({ mtu })
  3213. });
  3214. if (res.ok) {
  3215. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3216. fetchData(false);
  3217. }
  3218. } catch (err) {
  3219. showToast('Error', err.message, 'error');
  3220. }
  3221. }
  3222. async function addInterfaceIP() {
  3223. const ip = document.getElementById('modal-new-ip').value.trim();
  3224. if (!ip) return;
  3225. try {
  3226. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3227. method: 'POST',
  3228. headers: { 'Content-Type': 'application/json' },
  3229. body: JSON.stringify({ ip })
  3230. });
  3231. if (res.ok) {
  3232. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3233. document.getElementById('modal-new-ip').value = '';
  3234. await fetchData(false);
  3235. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3236. if (iface) renderModalIPs(iface);
  3237. } else {
  3238. const err = await res.json();
  3239. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3240. }
  3241. } catch (err) {
  3242. showToast('Error', err.message, 'error');
  3243. }
  3244. }
  3245. async function removeInterfaceIP(ip) {
  3246. if (!confirm(`Remove IP ${ip}?`)) return;
  3247. try {
  3248. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3249. method: 'DELETE',
  3250. headers: { 'Content-Type': 'application/json' },
  3251. body: JSON.stringify({ ip })
  3252. });
  3253. if (res.ok) {
  3254. showToast('IP Removed', `Removed ${ip}`, 'success');
  3255. await fetchData(false);
  3256. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3257. if (iface) renderModalIPs(iface);
  3258. }
  3259. } catch (err) {
  3260. showToast('Error', err.message, 'error');
  3261. }
  3262. }
  3263. async function renameInterface() {
  3264. const oldName = state.currentModalIface;
  3265. const newNameInput = document.getElementById('modal-iface-new-name');
  3266. const newName = (newNameInput?.value || '').trim();
  3267. if (!oldName) return;
  3268. if (!newName) {
  3269. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3270. return;
  3271. }
  3272. if (newName === oldName) {
  3273. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3274. return;
  3275. }
  3276. if (newName.length > 15) {
  3277. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3278. return;
  3279. }
  3280. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3281. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3282. return;
  3283. }
  3284. const renameBtn = document.getElementById('modal-btn-rename');
  3285. if (renameBtn) {
  3286. renameBtn.disabled = true;
  3287. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3288. }
  3289. try {
  3290. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3291. method: 'POST',
  3292. headers: { 'Content-Type': 'application/json' },
  3293. body: JSON.stringify({ new_name: newName })
  3294. });
  3295. const data = await res.json();
  3296. if (!res.ok) {
  3297. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3298. return;
  3299. }
  3300. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3301. state.currentModalIface = newName;
  3302. document.getElementById('modal-iface-name').innerText = newName;
  3303. // Refresh application state
  3304. await fetchData(false);
  3305. const updated = (state.interfaces || []).find(i => i.name === newName);
  3306. if (updated) {
  3307. openIfaceModal(newName);
  3308. } else {
  3309. closeIfaceModal();
  3310. }
  3311. } catch (err) {
  3312. showToast('Error', err.message, 'error');
  3313. } finally {
  3314. if (renameBtn) {
  3315. renameBtn.disabled = false;
  3316. renameBtn.innerHTML = `
  3317. <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>
  3318. <span>Rename</span>
  3319. `;
  3320. }
  3321. }
  3322. }
  3323. async function saveInterfaceMetadata() {
  3324. const oldName = state.currentModalIface;
  3325. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3326. const role = document.getElementById('modal-iface-role').value;
  3327. const desc = document.getElementById('modal-iface-desc').value.trim();
  3328. let targetName = oldName;
  3329. // If user changed the name before clicking Save Changes, execute rename first
  3330. if (newName && newName !== oldName && oldName !== 'lo') {
  3331. try {
  3332. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3333. method: 'POST',
  3334. headers: { 'Content-Type': 'application/json' },
  3335. body: JSON.stringify({ new_name: newName })
  3336. });
  3337. const data = await renameRes.json();
  3338. if (!renameRes.ok) {
  3339. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3340. return;
  3341. }
  3342. targetName = newName;
  3343. state.currentModalIface = newName;
  3344. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3345. } catch (err) {
  3346. showToast('Error', err.message, 'error');
  3347. return;
  3348. }
  3349. }
  3350. try {
  3351. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3352. method: 'POST',
  3353. headers: { 'Content-Type': 'application/json' },
  3354. body: JSON.stringify({ role, description: desc })
  3355. });
  3356. if (res.ok) {
  3357. showToast('Saved', 'Interface configuration updated', 'success');
  3358. closeIfaceModal();
  3359. fetchData(false);
  3360. } else {
  3361. const err = await res.json();
  3362. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3363. }
  3364. } catch (err) {
  3365. showToast('Error', err.message, 'error');
  3366. }
  3367. }
  3368. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3369. state.fwSubTab = 'filter';
  3370. state.routesSubTab = 'routes';
  3371. function renderRuleFlag(disabled, hasComment) {
  3372. let flags = '';
  3373. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3374. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3375. return flags || '<span class="text-slate-600">-</span>';
  3376. }
  3377. function renderActionBadge(action) {
  3378. const act = (action || '').toLowerCase();
  3379. let color = 'bg-slate-800 text-slate-300';
  3380. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3381. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3382. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3383. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3384. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3385. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3386. }
  3387. function switchFWSubTab(tab) {
  3388. state.fwSubTab = tab;
  3389. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3390. tabs.forEach(t => {
  3391. const panel = document.getElementById(`fw-subtab-${t}`);
  3392. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3393. if (panel) {
  3394. if (t === tab) panel.classList.remove('hidden');
  3395. else panel.classList.add('hidden');
  3396. }
  3397. if (btn) {
  3398. if (t === tab) {
  3399. 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';
  3400. } else {
  3401. 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';
  3402. }
  3403. }
  3404. });
  3405. const addBtn = document.getElementById('fw-primary-add-btn');
  3406. if (addBtn) {
  3407. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3408. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3409. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3410. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3411. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3412. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3413. }
  3414. if (tab === 'filter') renderFilterRules();
  3415. else if (tab === 'nat') renderNATRules();
  3416. else if (tab === 'mangle') renderMangleRules();
  3417. else if (tab === 'addrlist') renderAddressLists();
  3418. else if (tab === 'geo') loadGeoIP();
  3419. else if (tab === 'connections') loadConnections();
  3420. setTimeout(initTableSorting, 50);
  3421. }
  3422. function openCurrentFWModal() {
  3423. if (state.fwSubTab === 'filter') openAddFilterModal();
  3424. else if (state.fwSubTab === 'nat') openAddNATModal();
  3425. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3426. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3427. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3428. else if (state.fwSubTab === 'connections') loadConnections();
  3429. }
  3430. async function loadFirewall(populateDropdowns = true) {
  3431. try {
  3432. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3433. fetch(`${API_BASE}/firewall/summary`),
  3434. fetch(`${API_BASE}/firewall/filter`),
  3435. fetch(`${API_BASE}/firewall/nat`),
  3436. fetch(`${API_BASE}/firewall/mangle`),
  3437. fetch(`${API_BASE}/firewall/address-lists`),
  3438. fetch(`${API_BASE}/firewall/geoip/status`),
  3439. fetch(`${API_BASE}/firewall/geoip/countries`)
  3440. ]);
  3441. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3442. const applyError = document.getElementById('fw-apply-error');
  3443. if (applyError) {
  3444. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3445. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3446. }
  3447. if (filterRes.ok) state.filterRules = await filterRes.json();
  3448. if (natRes.ok) state.natRules = await natRes.json();
  3449. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3450. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3451. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3452. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3453. 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); }
  3454. // Badges
  3455. const bFilter = document.getElementById('fw-badge-filter');
  3456. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3457. const bNat = document.getElementById('fw-badge-nat');
  3458. if (bNat) bNat.innerText = (state.natRules || []).length;
  3459. const bMangle = document.getElementById('fw-badge-mangle');
  3460. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3461. const bAddr = document.getElementById('fw-badge-addrlist');
  3462. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3463. const bGeo = document.getElementById('fw-badge-geo');
  3464. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3465. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3466. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3467. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3468. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3469. const tbodyFilter = document.getElementById('filter-table-body');
  3470. if (tbodyFilter) {
  3471. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3472. tbodyFilter.dataset.sig = sigFilter;
  3473. renderFilterRules();
  3474. } else {
  3475. // In-place live stats update (ZERO flicker)
  3476. (state.filterRules || []).forEach(r => {
  3477. const p = document.getElementById(`filter-pkts-${r.id}`);
  3478. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3479. const b = document.getElementById(`filter-bytes-${r.id}`);
  3480. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3481. });
  3482. }
  3483. }
  3484. const tbodyNat = document.getElementById('nat-table-body');
  3485. if (tbodyNat) {
  3486. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3487. tbodyNat.dataset.sig = sigNat;
  3488. renderNATRules();
  3489. } else {
  3490. (state.natRules || []).forEach(r => {
  3491. const p = document.getElementById(`nat-pkts-${r.id}`);
  3492. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3493. const b = document.getElementById(`nat-bytes-${r.id}`);
  3494. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3495. });
  3496. }
  3497. }
  3498. const tbodyMangle = document.getElementById('mangle-table-body');
  3499. if (tbodyMangle) {
  3500. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3501. tbodyMangle.dataset.sig = sigMangle;
  3502. renderMangleRules();
  3503. } else {
  3504. (state.mangleRules || []).forEach(r => {
  3505. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3506. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3507. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3508. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3509. });
  3510. }
  3511. }
  3512. const tbodyAddr = document.getElementById('addrlist-table-body');
  3513. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3514. tbodyAddr.dataset.sig = sigAddr;
  3515. renderAddressLists();
  3516. }
  3517. renderGeoCountries();
  3518. if (state.fwSubTab === 'connections') {
  3519. loadConnections();
  3520. }
  3521. } catch (err) {
  3522. console.error('Failed to load firewall:', err);
  3523. }
  3524. }
  3525. // ----------------- Filter Rules -----------------
  3526. function renderFilterRules() {
  3527. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3528. const tbody = document.getElementById('filter-table-body');
  3529. const empty = document.getElementById('filter-empty');
  3530. if (!tbody) return;
  3531. tbody.innerHTML = '';
  3532. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3533. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3534. if (rules.length === 0) {
  3535. empty?.classList.remove('hidden');
  3536. return;
  3537. }
  3538. empty?.classList.add('hidden');
  3539. rules.forEach((raw, idx) => {
  3540. const r = safeFirewallRow(raw);
  3541. const tr = document.createElement('tr');
  3542. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3543. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3544. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3545. let actionExtra = '';
  3546. if (r.action === 'reject') {
  3547. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3548. } else if (r.action === 'jump') {
  3549. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3550. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3551. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3552. } else if (r.action === 'log' && r.log_prefix) {
  3553. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3554. }
  3555. tr.innerHTML = `
  3556. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3557. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3558. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3559. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3560. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3561. <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>
  3562. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3563. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3564. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3565. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3566. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3567. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3568. </td>
  3569. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3570. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3571. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3572. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3573. <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>
  3574. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3575. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3576. </td>
  3577. `;
  3578. tbody.appendChild(tr);
  3579. });
  3580. }
  3581. function formatTarget(addr, list, geo) {
  3582. const parts = [];
  3583. if (addr) parts.push(`<span>${addr}</span>`);
  3584. if (list) {
  3585. const inv = list.startsWith('!') ? '!' : '';
  3586. const clean = list.replace(/^!/, '');
  3587. 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>`);
  3588. }
  3589. if (geo) {
  3590. const inv = geo.startsWith('!') ? '!' : '';
  3591. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3592. 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>`);
  3593. }
  3594. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3595. return parts.join(' ');
  3596. }
  3597. function populateInterfaceSelect(selectId, currentVal = '') {
  3598. const sel = document.getElementById(selectId);
  3599. if (!sel) return;
  3600. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3601. (state.interfaces || []).forEach(i => {
  3602. const opt = document.createElement('option');
  3603. opt.value = i.name;
  3604. opt.innerText = `${i.name} (${i.role || i.type})`;
  3605. if (i.name === currentVal) opt.selected = true;
  3606. sel.appendChild(opt);
  3607. });
  3608. }
  3609. function populateAddressListSelect(selectId, currentVal = '') {
  3610. const sel = document.getElementById(selectId);
  3611. if (!sel) return;
  3612. sel.innerHTML = '<option value="">(None)</option>';
  3613. const cleanVal = (currentVal || '').replace(/^!/, '');
  3614. 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_'));
  3615. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3616. customNames.forEach(name => {
  3617. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3618. const opt = document.createElement('option');
  3619. opt.value = name;
  3620. opt.innerText = `${name} (${count} entries)`;
  3621. if (name === cleanVal) opt.selected = true;
  3622. sel.appendChild(opt);
  3623. });
  3624. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3625. const opt = document.createElement('option');
  3626. opt.value = cleanVal;
  3627. opt.innerText = cleanVal;
  3628. opt.selected = true;
  3629. sel.appendChild(opt);
  3630. }
  3631. populateCommonAddrListDatalist();
  3632. }
  3633. function populateCommonAddrListDatalist() {
  3634. const dl = document.getElementById('fw-addrlist-datalist');
  3635. if (!dl) return;
  3636. dl.innerHTML = '';
  3637. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3638. names.forEach(name => {
  3639. const opt = document.createElement('option');
  3640. opt.value = name;
  3641. dl.appendChild(opt);
  3642. });
  3643. }
  3644. function populateGeoIPSelect(selectId, currentVal = '') {
  3645. const sel = document.getElementById(selectId);
  3646. if (!sel) return;
  3647. sel.innerHTML = '<option value="">(None)</option>';
  3648. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3649. // Presets optgroup
  3650. const grpPresets = document.createElement('optgroup');
  3651. grpPresets.label = '⚡ Regional Presets';
  3652. const presets = [
  3653. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3654. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3655. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3656. ];
  3657. presets.forEach(p => {
  3658. const opt = document.createElement('option');
  3659. opt.value = p.code;
  3660. opt.innerText = p.label;
  3661. if (p.code === cleanVal) opt.selected = true;
  3662. grpPresets.appendChild(opt);
  3663. });
  3664. sel.appendChild(grpPresets);
  3665. // All Countries optgroup
  3666. const grpCountries = document.createElement('optgroup');
  3667. grpCountries.label = '🌍 All Countries';
  3668. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3669. countries.forEach(c => {
  3670. const opt = document.createElement('option');
  3671. opt.value = c.code;
  3672. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3673. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3674. if (c.code === cleanVal) opt.selected = true;
  3675. grpCountries.appendChild(opt);
  3676. });
  3677. sel.appendChild(grpCountries);
  3678. }
  3679. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3680. function switchFwRuleTab(tab) {
  3681. state.activeFwRuleTab = tab;
  3682. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3683. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3684. btn.classList.add('text-slate-400', 'border-transparent');
  3685. });
  3686. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3687. if (activeBtn) {
  3688. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3689. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3690. }
  3691. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3692. const activePane = document.getElementById(`fw-pane-${tab}`);
  3693. if (activePane) activePane.classList.remove('hidden');
  3694. if (tab === 'statistics') {
  3695. startFwStatPolling();
  3696. } else {
  3697. stopFwStatPolling();
  3698. }
  3699. }
  3700. function toggleFwField(fieldKey, expand) {
  3701. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3702. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3703. if (!plusBtn || !fieldBox) return;
  3704. if (expand) {
  3705. plusBtn.classList.add('hidden');
  3706. fieldBox.classList.remove('hidden');
  3707. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3708. if (valInput) valInput.focus();
  3709. } else {
  3710. fieldBox.classList.add('hidden');
  3711. plusBtn.classList.remove('hidden');
  3712. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3713. if (valInput) {
  3714. if (valInput.tagName === 'SELECT') {
  3715. valInput.selectedIndex = 0;
  3716. } else {
  3717. valInput.value = '';
  3718. }
  3719. }
  3720. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3721. if (invInput) invInput.checked = false;
  3722. if (fieldKey === 'cs') {
  3723. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3724. const el = document.getElementById(id);
  3725. if (el) el.checked = false;
  3726. });
  3727. }
  3728. if (fieldKey === 'natstate') {
  3729. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3730. const el = document.getElementById(id);
  3731. if (el) el.checked = false;
  3732. });
  3733. }
  3734. if (fieldKey === 'days') {
  3735. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3736. const el = document.getElementById(`fw-day-${d}`);
  3737. if (el) el.checked = true;
  3738. });
  3739. }
  3740. }
  3741. }
  3742. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3743. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3744. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3745. toggleFwField(fieldKey, true);
  3746. let strVal = String(value);
  3747. if (hasInvert) {
  3748. const inv = strVal.startsWith('!');
  3749. if (inv) strVal = strVal.slice(1);
  3750. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3751. if (invEl) invEl.checked = inv;
  3752. else if (inv) strVal = '!'+strVal;
  3753. }
  3754. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3755. 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; }
  3756. } else {
  3757. toggleFwField(fieldKey, false);
  3758. }
  3759. }
  3760. function getFwFieldVal(fieldKey, hasInvert = false) {
  3761. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3762. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3763. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3764. let v = valEl ? valEl.value.trim() : '';
  3765. if (!v) return '';
  3766. if (hasInvert) {
  3767. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3768. if (invEl && invEl.checked) {
  3769. v = '!' + v.replace(/^!/, '');
  3770. }
  3771. }
  3772. return v;
  3773. }
  3774. function toggleMaximizeFilterModal() {
  3775. const win = document.getElementById('filter-modal-window');
  3776. if (!win) return;
  3777. if (win.classList.contains('max-w-[720px]')) {
  3778. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3779. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3780. } else {
  3781. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3782. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3783. }
  3784. }
  3785. function openAddFilterModal() {
  3786. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  3787. switchFwRuleTab('general');
  3788. setFirewallDays('fw', '');
  3789. const badge = document.getElementById('fw-modal-badge');
  3790. if (badge) badge.innerText = 'New...';
  3791. document.getElementById('filter-modal-id').value = '';
  3792. document.getElementById('filter-modal-family').value = '4';
  3793. document.getElementById('filter-modal-enabled').checked = true;
  3794. document.getElementById('filter-modal-comment').value = '';
  3795. document.getElementById('filter-modal-chain').value = 'forward';
  3796. document.getElementById('filter-modal-action').value = 'accept';
  3797. document.getElementById('filter-modal-log').checked = false;
  3798. populateInterfaceSelect('fw-val-iniface');
  3799. populateInterfaceSelect('fw-val-outiface');
  3800. populateAddressListSelect('fw-val-srclist');
  3801. populateAddressListSelect('fw-val-dstlist');
  3802. populateGeoIPSelect('fw-val-srcgeo');
  3803. populateGeoIPSelect('fw-val-dstgeo');
  3804. const allFieldKeys = [
  3805. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3806. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3807. 'routingmark', 'conntype', 'cs', 'natstate',
  3808. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3809. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3810. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3811. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3812. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3813. ];
  3814. allFieldKeys.forEach(k => toggleFwField(k, false));
  3815. resetRuleCounterDisplay();
  3816. toggleFilterActionFields();
  3817. refreshFirewallRejectTypes();
  3818. document.getElementById('filter-modal').classList.remove('hidden');
  3819. }
  3820. function openEditFilterModal(id) {
  3821. id = decodeURIComponent(id);
  3822. const r = (state.filterRules || []).find(rule => rule.id === id);
  3823. if (!r) return;
  3824. switchFwRuleTab('general');
  3825. const badge = document.getElementById('fw-modal-badge');
  3826. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3827. document.getElementById('filter-modal-id').value = r.id;
  3828. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  3829. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3830. document.getElementById('filter-modal-comment').value = r.comment || '';
  3831. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3832. setFirewallActionSelection('filter', r.action || 'accept');
  3833. document.getElementById('filter-modal-log').checked = !!r.log;
  3834. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3835. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3836. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3837. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3838. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3839. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3840. setFwFieldVal('src', r.src_address, true);
  3841. setFwFieldVal('dst', r.dst_address, true);
  3842. setFwFieldVal('srclist', r.src_address_list, true);
  3843. setFwFieldVal('dstlist', r.dst_address_list, true);
  3844. setFwFieldVal('srcgeo', r.src_geoip, true);
  3845. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3846. if (r.protocol && r.protocol !== 'all') {
  3847. setFwFieldVal('proto', r.protocol, true);
  3848. } else {
  3849. toggleFwField('proto', false);
  3850. }
  3851. setFwFieldVal('sport', r.src_port, true);
  3852. setFwFieldVal('dport', r.dst_port, true);
  3853. setFwFieldVal('anyport', r.any_port, true);
  3854. setFwFieldVal('iniface', r.in_interface, true);
  3855. setFwFieldVal('outiface', r.out_interface, true);
  3856. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3857. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3858. setFwFieldVal('pktmark', r.packet_mark, true);
  3859. setFwFieldVal('connmark', r.connection_mark, true);
  3860. setFwFieldVal('routingmark', r.routing_mark, true);
  3861. setFwFieldVal('conntype', r.connection_type, false);
  3862. const states = r.connection_state || [];
  3863. if (states.length > 0) {
  3864. toggleFwField('cs', true);
  3865. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3866. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3867. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3868. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3869. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3870. } else {
  3871. toggleFwField('cs', false);
  3872. }
  3873. const natStates = r.connection_nat_state || [];
  3874. if (natStates.length > 0) {
  3875. toggleFwField('natstate', true);
  3876. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3877. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3878. } else {
  3879. toggleFwField('natstate', false);
  3880. }
  3881. // Advanced tab fields
  3882. setFwFieldVal('layer7', r.layer7_protocol, false);
  3883. setFwFieldVal('content', r.content, false);
  3884. setFwFieldVal('connbytes', r.connection_bytes, false);
  3885. setFwFieldVal('connrate', r.connection_rate, false);
  3886. setFwFieldVal('pcc', r.pcc, false);
  3887. setFwFieldVal('srcmac', r.src_mac_address, true);
  3888. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3889. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3890. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3891. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3892. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3893. setFwFieldVal('tlshost', r.tls_host, false);
  3894. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3895. setFwFieldVal('priority', r.priority, false);
  3896. setFwFieldVal('dscp', r.dscp, false);
  3897. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3898. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  3899. setFwFieldVal('pktsize', r.packet_size, false);
  3900. setFwFieldVal('random', r.random, false);
  3901. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3902. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3903. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3904. setFwFieldVal('ttl', r.ttl, false);
  3905. // Extra tab fields
  3906. setFwFieldVal('time', r.time, false);
  3907. if (r.days) {
  3908. toggleFwField('days', true);
  3909. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3910. const chk = document.getElementById(`fw-day-${d}`);
  3911. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  3912. });
  3913. } else {
  3914. toggleFwField('days', false);
  3915. }
  3916. setFwFieldVal('limit', r.limit, false);
  3917. setFwFieldVal('dstlimit', r.dst_limit, false);
  3918. setFwFieldVal('psd', r.psd, false);
  3919. // Action fields
  3920. if (r.reject_with) {
  3921. const rwEl = document.getElementById('filter-modal-rejectwith');
  3922. if (rwEl) rwEl.value = r.reject_with;
  3923. }
  3924. if (r.jump_target) {
  3925. const jtEl = document.getElementById('filter-modal-jumptarget');
  3926. if (jtEl) jtEl.value = r.jump_target;
  3927. }
  3928. if (r.address_list) {
  3929. const alEl = document.getElementById('filter-modal-action-addrlist');
  3930. if (alEl) alEl.value = r.address_list;
  3931. }
  3932. if (r.address_list_timeout) {
  3933. const toEl = document.getElementById('filter-modal-action-timeout');
  3934. if (toEl) toEl.value = r.address_list_timeout;
  3935. }
  3936. setFwFieldVal('logprefix', r.log_prefix, false);
  3937. // Statistics
  3938. const bEl = document.getElementById('fw-stat-bytes');
  3939. const pEl = document.getElementById('fw-stat-packets');
  3940. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3941. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3942. state.fwLastBytes = r.bytes || 0;
  3943. state.fwLastPackets = r.packets || 0;
  3944. state.fwLastTimestamp = Date.now();
  3945. state.fwStatRateHistory = new Array(30).fill(0);
  3946. state.fwStatPktHistory = new Array(30).fill(0);
  3947. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3948. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3949. toggleFilterActionFields();
  3950. refreshFirewallRejectTypes();
  3951. document.getElementById('filter-modal').classList.remove('hidden');
  3952. }
  3953. function closeFilterModal() {
  3954. stopFwStatPolling();
  3955. document.getElementById('filter-modal').classList.add('hidden');
  3956. }
  3957. function toggleFilterActionFields() {
  3958. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3959. const rejectBox = document.getElementById('filter-action-reject-box');
  3960. const jumpBox = document.getElementById('filter-action-jump-box');
  3961. const addrBox = document.getElementById('filter-action-addrlist-box');
  3962. if (rejectBox) {
  3963. if (act === 'reject') rejectBox.classList.remove('hidden');
  3964. else rejectBox.classList.add('hidden');
  3965. }
  3966. if (jumpBox) {
  3967. if (act === 'jump') jumpBox.classList.remove('hidden');
  3968. else jumpBox.classList.add('hidden');
  3969. }
  3970. if (addrBox) {
  3971. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3972. addrBox.classList.remove('hidden');
  3973. } else {
  3974. addrBox.classList.add('hidden');
  3975. }
  3976. }
  3977. if (act === 'log') {
  3978. const logEl = document.getElementById('filter-modal-log');
  3979. if (logEl) logEl.checked = true;
  3980. toggleFwField('logprefix', true);
  3981. }
  3982. }
  3983. function toggleFwLogPrefix() {
  3984. const isLog = document.getElementById('filter-modal-log')?.checked;
  3985. toggleFwField('logprefix', !!isLog);
  3986. }
  3987. function copyFilterRule() {
  3988. document.getElementById('filter-modal-id').value = '';
  3989. const badge = document.getElementById('fw-modal-badge');
  3990. if (badge) badge.innerText = 'New...';
  3991. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3992. }
  3993. function resetRuleCounterDisplay() {
  3994. state.fwStatRateHistory = new Array(30).fill(0);
  3995. state.fwStatPktHistory = new Array(30).fill(0);
  3996. state.fwLastBytes = 0;
  3997. state.fwLastPackets = 0;
  3998. state.fwLastTimestamp = Date.now();
  3999. const bEl = document.getElementById('fw-stat-bytes');
  4000. const pEl = document.getElementById('fw-stat-packets');
  4001. const rEl = document.getElementById('fw-stat-rate');
  4002. const prEl = document.getElementById('fw-stat-pktrate');
  4003. if (bEl) bEl.value = '0 B';
  4004. if (pEl) pEl.value = '0';
  4005. if (rEl) rEl.value = '0 bps';
  4006. if (prEl) prEl.value = '0 p/s';
  4007. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4008. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4009. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4010. }
  4011. async function resetAllFwCounters() {
  4012. try {
  4013. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4014. if (res.ok) {
  4015. resetRuleCounterDisplay();
  4016. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4017. loadFirewall(false);
  4018. }
  4019. } catch (err) {
  4020. showToast('Error', err.message, 'error');
  4021. }
  4022. }
  4023. async function applyFilterRule(closeAfter = false) {
  4024. const id = document.getElementById('filter-modal-id').value;
  4025. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4026. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4027. const chain = document.getElementById('filter-modal-chain').value;
  4028. const action = document.getElementById('filter-modal-action').value;
  4029. const comment = document.getElementById('filter-modal-comment').value.trim();
  4030. const enabled = document.getElementById('filter-modal-enabled').checked;
  4031. const src = getFwFieldVal('src', true);
  4032. const dst = getFwFieldVal('dst', true);
  4033. const srclist = getFwFieldVal('srclist', true);
  4034. const dstlist = getFwFieldVal('dstlist', true);
  4035. const srcgeo = getFwFieldVal('srcgeo', true);
  4036. const dstgeo = getFwFieldVal('dstgeo', true);
  4037. const proto = getFwFieldVal('proto', true);
  4038. const sport = getFwFieldVal('sport', true);
  4039. const dport = getFwFieldVal('dport', true);
  4040. const anyport = getFwFieldVal('anyport', true);
  4041. const iniface = getFwFieldVal('iniface', true);
  4042. const outiface = getFwFieldVal('outiface', true);
  4043. const inifacelist = getFwFieldVal('inifacelist', true);
  4044. const outifacelist = getFwFieldVal('outifacelist', true);
  4045. const pktmark = getFwFieldVal('pktmark', true);
  4046. const connmark = getFwFieldVal('connmark', true);
  4047. const routingmark = getFwFieldVal('routingmark', true);
  4048. const conntype = getFwFieldVal('conntype', false);
  4049. const states = [];
  4050. const csBox = document.getElementById('fw-field-cs');
  4051. if (csBox && !csBox.classList.contains('hidden')) {
  4052. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4053. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4054. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4055. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4056. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4057. }
  4058. const natStates = [];
  4059. const natBox = document.getElementById('fw-field-natstate');
  4060. if (natBox && !natBox.classList.contains('hidden')) {
  4061. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4062. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4063. }
  4064. const payload = {
  4065. ip_version: Number(document.getElementById('filter-modal-family').value),
  4066. id,
  4067. chain,
  4068. action,
  4069. protocol: proto || 'all',
  4070. src_address: src,
  4071. dst_address: dst,
  4072. src_port: sport,
  4073. dst_port: dport,
  4074. any_port: anyport,
  4075. in_interface: iniface,
  4076. out_interface: outiface,
  4077. in_interface_list: inifacelist,
  4078. out_interface_list: outifacelist,
  4079. packet_mark: pktmark,
  4080. connection_mark: connmark,
  4081. routing_mark: routingmark,
  4082. connection_type: conntype,
  4083. connection_state: states,
  4084. connection_nat_state: natStates,
  4085. src_address_list: srclist,
  4086. dst_address_list: dstlist,
  4087. src_geoip: srcgeo,
  4088. dst_geoip: dstgeo,
  4089. comment,
  4090. disabled: !enabled,
  4091. // Advanced tab
  4092. content: getFwFieldVal('content', false),
  4093. src_mac_address: getFwFieldVal('srcmac', true),
  4094. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4095. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4096. ipsec_policy: getFwFieldVal('ipsec', false),
  4097. dscp: getFwFieldVal('dscp', false),
  4098. tcp_mss: getFwFieldVal('tcpmss', false),
  4099. tos: document.getElementById('fw-val-tos')?.value || '',
  4100. packet_size: getFwFieldVal('pktsize', false),
  4101. random: getFwFieldVal('random', false),
  4102. tcp_flags: getFwFieldVal('tcpflags', false),
  4103. icmp_options: getFwFieldVal('icmpoptions', false),
  4104. ttl: getFwFieldVal('ttl', false),
  4105. days: selectedDays,
  4106. // Extra tab
  4107. time: getFwFieldVal('time', false),
  4108. limit: getFwFieldVal('limit', false),
  4109. // Action tab
  4110. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4111. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4112. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4113. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4114. log: document.getElementById('filter-modal-log')?.checked || false,
  4115. log_prefix: getFwFieldVal('logprefix', false)
  4116. };
  4117. try {
  4118. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4119. method: 'POST',
  4120. headers: { 'Content-Type': 'application/json' },
  4121. body: JSON.stringify(payload)
  4122. });
  4123. if (res.ok) {
  4124. const data = await res.json();
  4125. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4126. loadFirewall(false);
  4127. if (closeAfter) {
  4128. closeFilterModal();
  4129. } else {
  4130. if (data.id) {
  4131. document.getElementById('filter-modal-id').value = data.id;
  4132. const badge = document.getElementById('fw-modal-badge');
  4133. if (badge) badge.innerText = `#${data.id}`;
  4134. }
  4135. }
  4136. } else {
  4137. const err = await res.json();
  4138. showToast('Error', err.message || 'Failed to save rule', 'error');
  4139. }
  4140. } catch (err) {
  4141. showToast('Error', err.message, 'error');
  4142. }
  4143. }
  4144. function submitSaveFilterRule(e) {
  4145. if (e && e.preventDefault) e.preventDefault();
  4146. return applyFilterRule(true);
  4147. }
  4148. function startFwStatPolling() {
  4149. stopFwStatPolling();
  4150. pollRuleStats();
  4151. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4152. }
  4153. function stopFwStatPolling() {
  4154. if (state.fwStatInterval) {
  4155. clearInterval(state.fwStatInterval);
  4156. state.fwStatInterval = null;
  4157. }
  4158. }
  4159. async function pollRuleStats() {
  4160. const id = document.getElementById('filter-modal-id')?.value;
  4161. if (!id) {
  4162. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4163. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4164. return;
  4165. }
  4166. try {
  4167. const res = await fetch(`${API_BASE}/firewall/filter`);
  4168. if (!res.ok) return;
  4169. const rules = await res.json();
  4170. const r = rules.find(x => x.id === id);
  4171. if (!r) return;
  4172. const now = Date.now();
  4173. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4174. state.fwLastTimestamp = now;
  4175. const curBytes = r.bytes || 0;
  4176. const curPackets = r.packets || 0;
  4177. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4178. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4179. state.fwLastBytes = curBytes;
  4180. state.fwLastPackets = curPackets;
  4181. const rateBps = Math.round((deltaBytes * 8) / dt);
  4182. const ratePkt = Math.round(deltaPkts / dt);
  4183. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4184. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4185. state.fwStatRateHistory.push(rateBps);
  4186. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4187. state.fwStatPktHistory.push(ratePkt);
  4188. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4189. const bEl = document.getElementById('fw-stat-bytes');
  4190. const pEl = document.getElementById('fw-stat-packets');
  4191. const rEl = document.getElementById('fw-stat-rate');
  4192. const prEl = document.getElementById('fw-stat-pktrate');
  4193. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4194. if (pEl) pEl.value = curPackets.toLocaleString();
  4195. if (rEl) rEl.value = formatBps(rateBps);
  4196. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4197. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4198. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4199. } catch (e) {
  4200. console.error('Error polling rule stats', e);
  4201. }
  4202. }
  4203. function formatBps(bps) {
  4204. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4205. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4206. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4207. return bps + ' bps';
  4208. }
  4209. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4210. const svg = document.getElementById(svgId);
  4211. if (!svg) return;
  4212. const w = 500;
  4213. const h = 100;
  4214. const paddingRight = 45;
  4215. const graphWidth = w - paddingRight;
  4216. const maxVal = Math.max(5, ...dataArray);
  4217. const currentVal = dataArray[dataArray.length - 1] || 0;
  4218. const leg = document.getElementById(legendId);
  4219. if (leg) {
  4220. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4221. }
  4222. let gridLines = '';
  4223. for (let i = 0; i <= 5; i++) {
  4224. const y = 8 + (i * (h - 18) / 5);
  4225. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4226. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4227. gridLines += `
  4228. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4229. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4230. `;
  4231. }
  4232. const step = graphWidth / (dataArray.length - 1);
  4233. const points = dataArray.map((val, idx) => {
  4234. const x = idx * step;
  4235. const y = (h - 10) - (val / maxVal) * (h - 20);
  4236. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4237. });
  4238. const polylineStr = points.join(' ');
  4239. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4240. svg.innerHTML = `
  4241. ${gridLines}
  4242. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4243. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4244. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4245. `;
  4246. }
  4247. async function moveFilterRule(id, dir) {
  4248. id = decodeURIComponent(id);
  4249. try {
  4250. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4251. method: 'POST',
  4252. headers: { 'Content-Type': 'application/json' },
  4253. body: JSON.stringify({ direction: dir })
  4254. });
  4255. if (res.ok) loadFirewall(false);
  4256. } catch (err) {
  4257. showToast('Error', err.message, 'error');
  4258. }
  4259. }
  4260. async function toggleFilterRuleState(id, disabled) {
  4261. id = decodeURIComponent(id);
  4262. try {
  4263. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4264. method: 'POST',
  4265. headers: { 'Content-Type': 'application/json' },
  4266. body: JSON.stringify({ disabled })
  4267. });
  4268. if (res.ok) loadFirewall(false);
  4269. } catch (err) {
  4270. showToast('Error', err.message, 'error');
  4271. }
  4272. }
  4273. async function deleteFilterRule(id) {
  4274. id = decodeURIComponent(id);
  4275. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4276. try {
  4277. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4278. if (res.ok) {
  4279. showToast('Deleted', 'Filter rule removed', 'success');
  4280. loadFirewall(false);
  4281. }
  4282. } catch (err) {
  4283. showToast('Error', err.message, 'error');
  4284. }
  4285. }
  4286. // ----------------- NAT Rules -----------------
  4287. function renderNATRules() {
  4288. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4289. const tbody = document.getElementById('nat-table-body');
  4290. const empty = document.getElementById('nat-empty');
  4291. if (!tbody) return;
  4292. tbody.innerHTML = '';
  4293. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4294. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4295. if (rules.length === 0) {
  4296. empty?.classList.remove('hidden');
  4297. return;
  4298. }
  4299. empty?.classList.add('hidden');
  4300. rules.forEach((raw, idx) => {
  4301. const r = safeFirewallRow(raw);
  4302. const tr = document.createElement('tr');
  4303. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4304. let toTarget = '-';
  4305. if (r.action === 'jump') {
  4306. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4307. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4308. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4309. } else if (r.action === 'redirect') {
  4310. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4311. } else if (r.action === 'masquerade') {
  4312. 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>`;
  4313. } else if (r.action === 'log') {
  4314. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4315. } else {
  4316. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4317. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4318. }
  4319. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4320. tr.innerHTML = `
  4321. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4322. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4323. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4324. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4325. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4326. <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>
  4327. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4328. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4329. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4330. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4331. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4332. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4333. </td>
  4334. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4335. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4336. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4337. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4338. <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>
  4339. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4340. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4341. </td>
  4342. `;
  4343. tbody.appendChild(tr);
  4344. });
  4345. }
  4346. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4347. function switchNATRuleTab(tab) {
  4348. state.activeNATRuleTab = tab;
  4349. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4350. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4351. btn.classList.add('text-slate-400', 'border-transparent');
  4352. });
  4353. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4354. if (activeBtn) {
  4355. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4356. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4357. }
  4358. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4359. const activePane = document.getElementById(`nat-pane-${tab}`);
  4360. if (activePane) activePane.classList.remove('hidden');
  4361. if (tab === 'statistics') {
  4362. startNATStatPolling();
  4363. } else {
  4364. stopNATStatPolling();
  4365. }
  4366. }
  4367. function toggleNATField(fieldKey, expand) {
  4368. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4369. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4370. if (!plusBtn || !fieldBox) return;
  4371. if (expand) {
  4372. plusBtn.classList.add('hidden');
  4373. fieldBox.classList.remove('hidden');
  4374. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4375. if (valInput) valInput.focus();
  4376. } else {
  4377. fieldBox.classList.add('hidden');
  4378. plusBtn.classList.remove('hidden');
  4379. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4380. if (valInput) {
  4381. if (valInput.tagName === 'SELECT') {
  4382. valInput.selectedIndex = 0;
  4383. } else {
  4384. valInput.value = '';
  4385. }
  4386. }
  4387. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4388. if (invInput) invInput.checked = false;
  4389. if (fieldKey === 'days') {
  4390. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4391. const el = document.getElementById(`nat-day-${d}`);
  4392. if (el) el.checked = true;
  4393. });
  4394. }
  4395. }
  4396. }
  4397. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4398. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4399. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4400. toggleNATField(fieldKey, true);
  4401. let strVal = String(value);
  4402. if (hasInvert) {
  4403. const inv = strVal.startsWith('!');
  4404. if (inv) strVal = strVal.slice(1);
  4405. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4406. if (invEl) invEl.checked = inv;
  4407. else if (inv) strVal = '!'+strVal;
  4408. }
  4409. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4410. 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; }
  4411. } else {
  4412. toggleNATField(fieldKey, false);
  4413. }
  4414. }
  4415. function getNATFieldVal(fieldKey, hasInvert = false) {
  4416. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4417. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4418. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4419. let v = valEl ? valEl.value.trim() : '';
  4420. if (!v) return '';
  4421. if (hasInvert) {
  4422. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4423. if (invEl && invEl.checked) {
  4424. v = '!' + v.replace(/^!/, '');
  4425. }
  4426. }
  4427. return v;
  4428. }
  4429. function toggleMaximizeNATModal() {
  4430. const win = document.getElementById('nat-modal-window');
  4431. if (!win) return;
  4432. if (win.classList.contains('max-w-[720px]')) {
  4433. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4434. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4435. } else {
  4436. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4437. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4438. }
  4439. }
  4440. function handleNATChainChange() {
  4441. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4442. const actSel = document.getElementById('nat-modal-action');
  4443. if (actSel) {
  4444. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4445. actSel.value = 'masquerade';
  4446. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4447. actSel.value = 'dst-nat';
  4448. }
  4449. }
  4450. toggleNATActionFields();
  4451. }
  4452. function toggleNATActionFields() {
  4453. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4454. const rowAddr = document.getElementById('nat-row-toaddr');
  4455. const rowPort = document.getElementById('nat-row-toport');
  4456. const jumpBox = document.getElementById('nat-action-jump-box');
  4457. const addrBox = document.getElementById('nat-action-addrlist-box');
  4458. // Hide all dynamic rows first
  4459. if (rowAddr) rowAddr.classList.add('hidden');
  4460. if (rowPort) rowPort.classList.add('hidden');
  4461. if (jumpBox) jumpBox.classList.add('hidden');
  4462. if (addrBox) addrBox.classList.add('hidden');
  4463. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4464. if (rowAddr) rowAddr.classList.remove('hidden');
  4465. if (rowPort) rowPort.classList.remove('hidden');
  4466. } else if (act === 'redirect' || act === 'masquerade') {
  4467. if (rowPort) rowPort.classList.remove('hidden');
  4468. } else if (act === 'jump') {
  4469. if (jumpBox) jumpBox.classList.remove('hidden');
  4470. } else if (act.includes('address-list') || act.includes('address list')) {
  4471. if (addrBox) addrBox.classList.remove('hidden');
  4472. }
  4473. if (act === 'log') {
  4474. const logEl = document.getElementById('nat-modal-log');
  4475. if (logEl) logEl.checked = true;
  4476. toggleNATField('logprefix', true);
  4477. }
  4478. }
  4479. function toggleNATLogPrefix() {
  4480. const isLog = document.getElementById('nat-modal-log')?.checked;
  4481. toggleNATField('logprefix', !!isLog);
  4482. }
  4483. function openAddNATModal() {
  4484. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4485. switchNATRuleTab('general');
  4486. setFirewallDays('nat', '');
  4487. const badge = document.getElementById('nat-modal-badge');
  4488. if (badge) badge.innerText = 'New...';
  4489. document.getElementById('nat-modal-id').value = '';
  4490. document.getElementById('nat-modal-family').value = '4';
  4491. document.getElementById('nat-modal-enabled').checked = true;
  4492. document.getElementById('nat-modal-comment').value = '';
  4493. document.getElementById('nat-modal-chain').value = 'srcnat';
  4494. document.getElementById('nat-modal-action').value = 'masquerade';
  4495. document.getElementById('nat-modal-toaddr').value = '';
  4496. document.getElementById('nat-modal-toport').value = '';
  4497. document.getElementById('nat-modal-log').checked = false;
  4498. populateInterfaceSelect('nat-val-iniface');
  4499. populateInterfaceSelect('nat-val-outiface');
  4500. populateAddressListSelect('nat-val-srclist');
  4501. populateAddressListSelect('nat-val-dstlist');
  4502. populateGeoIPSelect('nat-val-srcgeo');
  4503. populateGeoIPSelect('nat-val-dstgeo');
  4504. const allFieldKeys = [
  4505. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4506. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4507. 'routingmark', 'conntype',
  4508. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4509. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4510. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4511. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4512. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4513. ];
  4514. allFieldKeys.forEach(k => toggleNATField(k, false));
  4515. resetNATCounterDisplay();
  4516. toggleNATActionFields();
  4517. document.getElementById('nat-modal').classList.remove('hidden');
  4518. }
  4519. function openEditNATModal(id) {
  4520. id = decodeURIComponent(id);
  4521. const r = (state.natRules || []).find(rule => rule.id === id);
  4522. if (!r) return;
  4523. setFirewallDays('nat', r.days || '');
  4524. switchNATRuleTab('general');
  4525. const badge = document.getElementById('nat-modal-badge');
  4526. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4527. document.getElementById('nat-modal-id').value = r.id;
  4528. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4529. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4530. document.getElementById('nat-modal-comment').value = r.comment || '';
  4531. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4532. setFirewallActionSelection('nat', r.action || 'accept');
  4533. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4534. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4535. document.getElementById('nat-modal-log').checked = !!r.log;
  4536. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4537. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4538. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4539. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4540. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4541. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4542. setNATFieldVal('src', r.src_address, true);
  4543. setNATFieldVal('dst', r.dst_address, true);
  4544. setNATFieldVal('srclist', r.src_address_list, true);
  4545. setNATFieldVal('dstlist', r.dst_address_list, true);
  4546. setNATFieldVal('srcgeo', r.src_geoip, true);
  4547. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4548. if (r.protocol && r.protocol !== 'all') {
  4549. setNATFieldVal('proto', r.protocol, true);
  4550. } else {
  4551. toggleNATField('proto', false);
  4552. }
  4553. setNATFieldVal('sport', r.src_port, true);
  4554. setNATFieldVal('dport', r.dst_port, true);
  4555. setNATFieldVal('anyport', r.any_port, true);
  4556. setNATFieldVal('iniface', r.in_interface, true);
  4557. setNATFieldVal('outiface', r.out_interface, true);
  4558. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4559. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4560. setNATFieldVal('pktmark', r.packet_mark, true);
  4561. setNATFieldVal('connmark', r.connection_mark, true);
  4562. setNATFieldVal('routingmark', r.routing_mark, true);
  4563. setNATFieldVal('conntype', r.connection_type, false);
  4564. // Advanced tab fields
  4565. setNATFieldVal('layer7', r.layer7_protocol, false);
  4566. setNATFieldVal('content', r.content, false);
  4567. setNATFieldVal('connbytes', r.connection_bytes, false);
  4568. setNATFieldVal('connrate', r.connection_rate, false);
  4569. setNATFieldVal('pcc', r.pcc, false);
  4570. setNATFieldVal('srcmac', r.src_mac_address, true);
  4571. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4572. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4573. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4574. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4575. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4576. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4577. setNATFieldVal('priority', r.priority, false);
  4578. setNATFieldVal('dscp', r.dscp, false);
  4579. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4580. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4581. setNATFieldVal('pktsize', r.packet_size, false);
  4582. setNATFieldVal('random', r.random, false);
  4583. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4584. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4585. setNATFieldVal('ttl', r.ttl, false);
  4586. // Extra tab fields
  4587. setNATFieldVal('time', r.time, false);
  4588. if (r.days) {
  4589. toggleNATField('days', true);
  4590. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4591. const chk = document.getElementById(`nat-day-${d}`);
  4592. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4593. });
  4594. } else {
  4595. toggleNATField('days', false);
  4596. }
  4597. setNATFieldVal('limit', r.limit, false);
  4598. setNATFieldVal('dstlimit', r.dst_limit, false);
  4599. setNATFieldVal('psd', r.psd, false);
  4600. // Action fields
  4601. if (r.jump_target) {
  4602. const jtEl = document.getElementById('nat-modal-jumptarget');
  4603. if (jtEl) jtEl.value = r.jump_target;
  4604. }
  4605. if (r.address_list) {
  4606. const alEl = document.getElementById('nat-modal-action-addrlist');
  4607. if (alEl) alEl.value = r.address_list;
  4608. }
  4609. if (r.address_list_timeout) {
  4610. const toEl = document.getElementById('nat-modal-action-timeout');
  4611. if (toEl) toEl.value = r.address_list_timeout;
  4612. }
  4613. setNATFieldVal('logprefix', r.log_prefix, false);
  4614. // Statistics
  4615. const bEl = document.getElementById('nat-stat-bytes');
  4616. const pEl = document.getElementById('nat-stat-packets');
  4617. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4618. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4619. state.natLastBytes = r.bytes || 0;
  4620. state.natLastPackets = r.packets || 0;
  4621. state.natLastTimestamp = Date.now();
  4622. state.natStatRateHistory = new Array(30).fill(0);
  4623. state.natStatPktHistory = new Array(30).fill(0);
  4624. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4625. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4626. toggleNATActionFields();
  4627. document.getElementById('nat-modal').classList.remove('hidden');
  4628. }
  4629. function closeNATModal() {
  4630. stopNATStatPolling();
  4631. document.getElementById('nat-modal').classList.add('hidden');
  4632. }
  4633. function copyNATRule() {
  4634. document.getElementById('nat-modal-id').value = '';
  4635. const badge = document.getElementById('nat-modal-badge');
  4636. if (badge) badge.innerText = 'New...';
  4637. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4638. }
  4639. function resetNATCounterDisplay() {
  4640. state.natStatRateHistory = new Array(30).fill(0);
  4641. state.natStatPktHistory = new Array(30).fill(0);
  4642. state.natLastBytes = 0;
  4643. state.natLastPackets = 0;
  4644. state.natLastTimestamp = Date.now();
  4645. const bEl = document.getElementById('nat-stat-bytes');
  4646. const pEl = document.getElementById('nat-stat-packets');
  4647. const rEl = document.getElementById('nat-stat-rate');
  4648. const prEl = document.getElementById('nat-stat-pktrate');
  4649. if (bEl) bEl.value = '0 B';
  4650. if (pEl) pEl.value = '0';
  4651. if (rEl) rEl.value = '0 bps';
  4652. if (prEl) prEl.value = '0 p/s';
  4653. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4654. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4655. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4656. }
  4657. async function applyNATRule(closeAfter = false) {
  4658. const id = document.getElementById('nat-modal-id').value;
  4659. if (!reviewLegacyFirewallSettings('nat', id)) return;
  4660. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4661. const chain = document.getElementById('nat-modal-chain').value;
  4662. const action = document.getElementById('nat-modal-action').value;
  4663. const comment = document.getElementById('nat-modal-comment').value.trim();
  4664. const enabled = document.getElementById('nat-modal-enabled').checked;
  4665. const src = getNATFieldVal('src', true);
  4666. const dst = getNATFieldVal('dst', true);
  4667. const srclist = getNATFieldVal('srclist', true);
  4668. const dstlist = getNATFieldVal('dstlist', true);
  4669. const srcgeo = getNATFieldVal('srcgeo', true);
  4670. const dstgeo = getNATFieldVal('dstgeo', true);
  4671. const proto = getNATFieldVal('proto', true);
  4672. const sport = getNATFieldVal('sport', true);
  4673. const dport = getNATFieldVal('dport', true);
  4674. const anyport = getNATFieldVal('anyport', true);
  4675. const iniface = getNATFieldVal('iniface', true);
  4676. const outiface = getNATFieldVal('outiface', true);
  4677. const inifacelist = getNATFieldVal('inifacelist', true);
  4678. const outifacelist = getNATFieldVal('outifacelist', true);
  4679. const pktmark = getNATFieldVal('pktmark', true);
  4680. const connmark = getNATFieldVal('connmark', true);
  4681. const routingmark = getNATFieldVal('routingmark', true);
  4682. const conntype = getNATFieldVal('conntype', false);
  4683. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  4684. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  4685. const payload = {
  4686. ip_version: Number(document.getElementById('nat-modal-family').value),
  4687. id,
  4688. chain,
  4689. action,
  4690. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4691. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4692. protocol: proto || 'all',
  4693. src_address: src,
  4694. dst_address: dst,
  4695. src_port: sport,
  4696. dst_port: dport,
  4697. any_port: anyport,
  4698. in_interface: iniface,
  4699. out_interface: outiface,
  4700. in_interface_list: inifacelist,
  4701. out_interface_list: outifacelist,
  4702. packet_mark: pktmark,
  4703. connection_mark: connmark,
  4704. routing_mark: routingmark,
  4705. connection_type: conntype,
  4706. src_address_list: srclist,
  4707. dst_address_list: dstlist,
  4708. src_geoip: srcgeo,
  4709. dst_geoip: dstgeo,
  4710. comment,
  4711. disabled: !enabled,
  4712. // Advanced tab
  4713. content: getNATFieldVal('content', false),
  4714. src_mac_address: getNATFieldVal('srcmac', true),
  4715. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4716. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4717. ipsec_policy: getNATFieldVal('ipsec', false),
  4718. dscp: getNATFieldVal('dscp', false),
  4719. tcp_mss: getNATFieldVal('tcpmss', false),
  4720. tos: document.getElementById('nat-val-tos')?.value || '',
  4721. packet_size: getNATFieldVal('pktsize', false),
  4722. random: getNATFieldVal('random', false),
  4723. icmp_options: getNATFieldVal('icmpoptions', false),
  4724. ttl: getNATFieldVal('ttl', false),
  4725. days: selectedDays,
  4726. // Extra tab
  4727. time: getNATFieldVal('time', false),
  4728. limit: getNATFieldVal('limit', false),
  4729. // Action tab
  4730. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4731. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4732. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4733. log: document.getElementById('nat-modal-log')?.checked || false,
  4734. log_prefix: getNATFieldVal('logprefix', false)
  4735. };
  4736. try {
  4737. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4738. method: 'POST',
  4739. headers: { 'Content-Type': 'application/json' },
  4740. body: JSON.stringify(payload)
  4741. });
  4742. if (res.ok) {
  4743. const data = await res.json();
  4744. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4745. loadFirewall(false);
  4746. if (closeAfter) {
  4747. closeNATModal();
  4748. } else {
  4749. if (data.id) {
  4750. document.getElementById('nat-modal-id').value = data.id;
  4751. const badge = document.getElementById('nat-modal-badge');
  4752. if (badge) badge.innerText = `#${data.id}`;
  4753. }
  4754. }
  4755. } else {
  4756. const err = await res.json();
  4757. showToast('Error', err.message || 'Failed to save rule', 'error');
  4758. }
  4759. } catch (err) {
  4760. showToast('Error', err.message, 'error');
  4761. }
  4762. }
  4763. function submitSaveNATRule(e) {
  4764. if (e && e.preventDefault) e.preventDefault();
  4765. return applyNATRule(true);
  4766. }
  4767. function startNATStatPolling() {
  4768. stopNATStatPolling();
  4769. pollNATRuleStats();
  4770. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4771. }
  4772. function stopNATStatPolling() {
  4773. if (state.natStatInterval) {
  4774. clearInterval(state.natStatInterval);
  4775. state.natStatInterval = null;
  4776. }
  4777. }
  4778. async function pollNATRuleStats() {
  4779. const id = document.getElementById('nat-modal-id')?.value;
  4780. if (!id) {
  4781. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4782. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4783. return;
  4784. }
  4785. try {
  4786. const res = await fetch(`${API_BASE}/firewall/nat`);
  4787. if (!res.ok) return;
  4788. const rules = await res.json();
  4789. const r = rules.find(x => x.id === id);
  4790. if (!r) return;
  4791. const now = Date.now();
  4792. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4793. state.natLastTimestamp = now;
  4794. const curBytes = r.bytes || 0;
  4795. const curPackets = r.packets || 0;
  4796. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  4797. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  4798. state.natLastBytes = curBytes;
  4799. state.natLastPackets = curPackets;
  4800. const rateBps = Math.round((deltaBytes * 8) / dt);
  4801. const ratePkt = Math.round(deltaPkts / dt);
  4802. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4803. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4804. state.natStatRateHistory.push(rateBps);
  4805. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4806. state.natStatPktHistory.push(ratePkt);
  4807. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4808. const bEl = document.getElementById('nat-stat-bytes');
  4809. const pEl = document.getElementById('nat-stat-packets');
  4810. const rEl = document.getElementById('nat-stat-rate');
  4811. const prEl = document.getElementById('nat-stat-pktrate');
  4812. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4813. if (pEl) pEl.value = curPackets.toLocaleString();
  4814. if (rEl) rEl.value = formatBps(rateBps);
  4815. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4816. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4817. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4818. } catch (e) {
  4819. console.error('Error polling NAT rule stats', e);
  4820. }
  4821. }
  4822. async function moveNATRule(id, dir) {
  4823. id = decodeURIComponent(id);
  4824. try {
  4825. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4826. method: 'POST',
  4827. headers: { 'Content-Type': 'application/json' },
  4828. body: JSON.stringify({ direction: dir })
  4829. });
  4830. if (res.ok) loadFirewall(false);
  4831. } catch (err) {
  4832. showToast('Error', err.message, 'error');
  4833. }
  4834. }
  4835. async function toggleNATRuleState(id, disabled) {
  4836. id = decodeURIComponent(id);
  4837. try {
  4838. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4839. method: 'POST',
  4840. headers: { 'Content-Type': 'application/json' },
  4841. body: JSON.stringify({ disabled })
  4842. });
  4843. if (res.ok) loadFirewall(false);
  4844. } catch (err) {
  4845. showToast('Error', err.message, 'error');
  4846. }
  4847. }
  4848. async function deleteNATRule(id) {
  4849. id = decodeURIComponent(id);
  4850. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4851. try {
  4852. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4853. if (res.ok) {
  4854. showToast('Deleted', 'NAT rule removed', 'success');
  4855. loadFirewall(false);
  4856. }
  4857. } catch (err) {
  4858. showToast('Error', err.message, 'error');
  4859. }
  4860. }
  4861. // ----------------- Mangle Rules -----------------
  4862. function renderMangleRules() {
  4863. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4864. const tbody = document.getElementById('mangle-table-body');
  4865. const empty = document.getElementById('mangle-empty');
  4866. if (!tbody) return;
  4867. tbody.innerHTML = '';
  4868. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4869. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4870. if (rules.length === 0) {
  4871. empty?.classList.remove('hidden');
  4872. return;
  4873. }
  4874. empty?.classList.add('hidden');
  4875. rules.forEach((raw, idx) => {
  4876. const r = safeFirewallRow(raw);
  4877. const tr = document.createElement('tr');
  4878. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4879. let markVal = '<span class="text-slate-500">-</span>';
  4880. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4881. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4882. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4883. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4884. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4885. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4886. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4887. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4888. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4889. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4890. 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>`;
  4891. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4892. tr.innerHTML = `
  4893. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4894. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4895. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4896. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4897. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4898. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4899. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4900. <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>
  4901. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4902. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4903. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4904. </td>
  4905. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4906. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4907. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4908. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4909. <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>
  4910. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4911. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4912. </td>
  4913. `;
  4914. tbody.appendChild(tr);
  4915. });
  4916. }
  4917. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4918. function switchMangleRuleTab(tab) {
  4919. state.activeMangleRuleTab = tab;
  4920. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4921. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4922. btn.classList.add('text-slate-400', 'border-transparent');
  4923. });
  4924. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4925. if (activeBtn) {
  4926. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4927. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4928. }
  4929. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4930. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4931. if (activePane) activePane.classList.remove('hidden');
  4932. if (tab === 'statistics') {
  4933. startMangleStatPolling();
  4934. } else {
  4935. stopMangleStatPolling();
  4936. }
  4937. }
  4938. function toggleMangleField(fieldKey, expand) {
  4939. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4940. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4941. if (!plusBtn || !fieldBox) return;
  4942. if (expand) {
  4943. plusBtn.classList.add('hidden');
  4944. fieldBox.classList.remove('hidden');
  4945. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4946. if (valInput) valInput.focus();
  4947. } else {
  4948. fieldBox.classList.add('hidden');
  4949. plusBtn.classList.remove('hidden');
  4950. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4951. if (valInput) {
  4952. if (valInput.tagName === 'SELECT') {
  4953. valInput.selectedIndex = 0;
  4954. } else {
  4955. valInput.value = '';
  4956. }
  4957. }
  4958. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4959. if (invInput) invInput.checked = false;
  4960. if (fieldKey === 'cs') {
  4961. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4962. const el = document.getElementById(id);
  4963. if (el) el.checked = false;
  4964. });
  4965. }
  4966. if (fieldKey === 'natstate') {
  4967. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4968. const el = document.getElementById(id);
  4969. if (el) el.checked = false;
  4970. });
  4971. }
  4972. }
  4973. }
  4974. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4975. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4976. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4977. toggleMangleField(fieldKey, true);
  4978. let strVal = String(value);
  4979. if (hasInvert) {
  4980. const inv = strVal.startsWith('!');
  4981. if (inv) strVal = strVal.slice(1);
  4982. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4983. if (invEl) invEl.checked = inv;
  4984. else if (inv) strVal = '!'+strVal;
  4985. }
  4986. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4987. 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; }
  4988. } else {
  4989. toggleMangleField(fieldKey, false);
  4990. }
  4991. }
  4992. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4993. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4994. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4995. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4996. let v = valEl ? valEl.value.trim() : '';
  4997. if (!v) return '';
  4998. if (hasInvert) {
  4999. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5000. if (invEl && invEl.checked) {
  5001. v = '!' + v.replace(/^!/, '');
  5002. }
  5003. }
  5004. return v;
  5005. }
  5006. function toggleMaximizeMangleModal() {
  5007. const win = document.getElementById('mangle-modal-window');
  5008. if (!win) return;
  5009. if (win.classList.contains('max-w-[720px]')) {
  5010. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5011. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5012. } else {
  5013. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5014. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5015. }
  5016. }
  5017. function toggleMangleActionFields() {
  5018. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5019. // Hide all dynamic rows first
  5020. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5021. const el = document.getElementById(`mangle-row-${id}`);
  5022. if (el) el.classList.add('hidden');
  5023. });
  5024. const jumpBox = document.getElementById('mangle-action-jump-box');
  5025. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5026. if (jumpBox) jumpBox.classList.add('hidden');
  5027. if (addrBox) addrBox.classList.add('hidden');
  5028. // Activate matching rows
  5029. if (act === 'mark-connection') {
  5030. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5031. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5032. } else if (act === 'mark-routing') {
  5033. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5034. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5035. } else if (act === 'mark-packet') {
  5036. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5037. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5038. } else if (act === 'change-mss') {
  5039. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5040. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5041. } else if (act === 'change-dscp') {
  5042. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5043. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5044. } else if (act === 'change-ttl') {
  5045. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5046. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5047. } else if (act === 'set-priority') {
  5048. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5049. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5050. } else if (act === 'route') {
  5051. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5052. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5053. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5054. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5055. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5056. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5057. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5058. } else if (act === 'jump') {
  5059. if (jumpBox) jumpBox.classList.remove('hidden');
  5060. } else if (act.includes('address-list') || act.includes('address list')) {
  5061. if (addrBox) addrBox.classList.remove('hidden');
  5062. }
  5063. if (act === 'log') {
  5064. const logEl = document.getElementById('mangle-modal-log');
  5065. if (logEl) logEl.checked = true;
  5066. toggleMangleField('logprefix', true);
  5067. }
  5068. }
  5069. function toggleMangleLogPrefix() {
  5070. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5071. toggleMangleField('logprefix', !!isLog);
  5072. }
  5073. const allMangleFieldKeys = [
  5074. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5075. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5076. 'routingmark', 'conntype', 'cs', 'natstate',
  5077. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5078. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5079. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5080. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5081. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5082. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5083. ];
  5084. function openAddMangleModal() {
  5085. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5086. switchMangleRuleTab('general');
  5087. const badge = document.getElementById('mangle-modal-badge');
  5088. if (badge) badge.innerText = 'New...';
  5089. document.getElementById('mangle-modal-id').value = '';
  5090. document.getElementById('mangle-modal-family').value = '4';
  5091. document.getElementById('mangle-modal-enabled').checked = true;
  5092. document.getElementById('mangle-modal-comment').value = '';
  5093. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5094. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5095. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5096. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5097. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5098. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5099. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5100. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5101. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5102. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5103. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5104. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5105. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5106. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5107. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5108. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5109. populateInterfaceSelect('mangle-val-iniface');
  5110. populateInterfaceSelect('mangle-val-outiface');
  5111. populateAddressListSelect('mangle-val-srclist');
  5112. populateAddressListSelect('mangle-val-dstlist');
  5113. populateGeoIPSelect('mangle-val-srcgeo');
  5114. populateGeoIPSelect('mangle-val-dstgeo');
  5115. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5116. resetMangleCounterDisplay();
  5117. toggleMangleActionFields();
  5118. document.getElementById('mangle-modal').classList.remove('hidden');
  5119. }
  5120. function openEditMangleModal(id) {
  5121. id = decodeURIComponent(id);
  5122. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5123. if (!r) return;
  5124. switchMangleRuleTab('general');
  5125. const badge = document.getElementById('mangle-modal-badge');
  5126. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5127. document.getElementById('mangle-modal-id').value = r.id;
  5128. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5129. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5130. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5131. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5132. setFirewallActionSelection('mangle', r.action || 'accept');
  5133. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5134. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5135. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5136. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5137. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5138. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5139. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5140. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5141. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5142. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5143. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5144. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5145. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5146. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5147. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5148. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5149. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5150. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5151. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5152. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5153. setMangleFieldVal('src', r.src_address, true);
  5154. setMangleFieldVal('dst', r.dst_address, true);
  5155. setMangleFieldVal('srclist', r.src_address_list, true);
  5156. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5157. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5158. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5159. if (r.protocol && r.protocol !== 'all') {
  5160. setMangleFieldVal('proto', r.protocol, true);
  5161. } else {
  5162. toggleMangleField('proto', false);
  5163. }
  5164. setMangleFieldVal('sport', r.src_port, true);
  5165. setMangleFieldVal('dport', r.dst_port, true);
  5166. setMangleFieldVal('anyport', r.any_port, true);
  5167. setMangleFieldVal('iniface', r.in_interface, true);
  5168. setMangleFieldVal('outiface', r.out_interface, true);
  5169. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5170. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5171. setMangleFieldVal('pktmark', r.packet_mark, true);
  5172. setMangleFieldVal('connmark', r.connection_mark, true);
  5173. setMangleFieldVal('routingmark', r.routing_mark, true);
  5174. setMangleFieldVal('conntype', r.connection_type, false);
  5175. // Connection State
  5176. const states = r.connection_state || [];
  5177. if (states.length > 0) {
  5178. toggleMangleField('cs', true);
  5179. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5180. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5181. if (el) el.checked = states.includes(s);
  5182. });
  5183. } else {
  5184. toggleMangleField('cs', false);
  5185. }
  5186. // Connection NAT State
  5187. const natStates = r.connection_nat_state || [];
  5188. if (natStates.length > 0) {
  5189. toggleMangleField('natstate', true);
  5190. ['srcnat', 'dstnat'].forEach(s => {
  5191. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5192. if (el) el.checked = natStates.includes(s);
  5193. });
  5194. } else {
  5195. toggleMangleField('natstate', false);
  5196. }
  5197. // Advanced tab fields
  5198. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5199. setMangleFieldVal('content', r.content, false);
  5200. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5201. setMangleFieldVal('connrate', r.connection_rate, false);
  5202. setMangleFieldVal('pcc', r.pcc, false);
  5203. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5204. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5205. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5206. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5207. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5208. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5209. setMangleFieldVal('tlshost', r.tls_host, false);
  5210. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5211. setMangleFieldVal('priority', r.priority, false);
  5212. setMangleFieldVal('dscp', r.dscp, false);
  5213. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5214. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5215. setMangleFieldVal('pktsize', r.packet_size, false);
  5216. setMangleFieldVal('random', r.random, false);
  5217. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5218. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5219. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5220. setMangleFieldVal('ttl', r.ttl, false);
  5221. // Extra tab fields
  5222. setMangleFieldVal('nth', r.nth, false);
  5223. setMangleFieldVal('connlimit', r.connection_limit, false);
  5224. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5225. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5226. setMangleFieldVal('hotspot', r.hotspot, false);
  5227. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5228. setMangleFieldVal('limit', r.limit, false);
  5229. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5230. setMangleFieldVal('time', r.time, false);
  5231. setMangleFieldVal('psd', r.psd, false);
  5232. // Action fields
  5233. if (r.jump_target) {
  5234. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5235. if (jtEl) jtEl.value = r.jump_target;
  5236. }
  5237. if (r.address_list) {
  5238. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5239. if (alEl) alEl.value = r.address_list;
  5240. }
  5241. if (r.address_list_timeout) {
  5242. const toEl = document.getElementById('mangle-modal-action-timeout');
  5243. if (toEl) toEl.value = r.address_list_timeout;
  5244. }
  5245. setMangleFieldVal('logprefix', r.log_prefix, false);
  5246. // Statistics
  5247. const bEl = document.getElementById('mangle-stat-bytes');
  5248. const pEl = document.getElementById('mangle-stat-packets');
  5249. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5250. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5251. state.mangleLastBytes = r.bytes || 0;
  5252. state.mangleLastPackets = r.packets || 0;
  5253. state.mangleLastTimestamp = Date.now();
  5254. state.mangleStatRateHistory = new Array(30).fill(0);
  5255. state.mangleStatPktHistory = new Array(30).fill(0);
  5256. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5257. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5258. toggleMangleActionFields();
  5259. document.getElementById('mangle-modal').classList.remove('hidden');
  5260. }
  5261. function closeMangleModal() {
  5262. stopMangleStatPolling();
  5263. document.getElementById('mangle-modal').classList.add('hidden');
  5264. }
  5265. function copyMangleRule() {
  5266. document.getElementById('mangle-modal-id').value = '';
  5267. const badge = document.getElementById('mangle-modal-badge');
  5268. if (badge) badge.innerText = 'New...';
  5269. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5270. }
  5271. function resetMangleCounterDisplay() {
  5272. state.mangleStatRateHistory = new Array(30).fill(0);
  5273. state.mangleStatPktHistory = new Array(30).fill(0);
  5274. state.mangleLastBytes = 0;
  5275. state.mangleLastPackets = 0;
  5276. state.mangleLastTimestamp = Date.now();
  5277. const bEl = document.getElementById('mangle-stat-bytes');
  5278. const pEl = document.getElementById('mangle-stat-packets');
  5279. const rEl = document.getElementById('mangle-stat-rate');
  5280. const prEl = document.getElementById('mangle-stat-pktrate');
  5281. if (bEl) bEl.value = '0 B';
  5282. if (pEl) pEl.value = '0';
  5283. if (rEl) rEl.value = '0 bps';
  5284. if (prEl) prEl.value = '0 p/s';
  5285. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5286. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5287. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5288. }
  5289. async function applyMangleRule(closeAfter = false) {
  5290. const id = document.getElementById('mangle-modal-id').value;
  5291. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5292. const chain = document.getElementById('mangle-modal-chain').value;
  5293. const action = document.getElementById('mangle-modal-action').value;
  5294. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5295. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5296. const src = getMangleFieldVal('src', true);
  5297. const dst = getMangleFieldVal('dst', true);
  5298. const srclist = getMangleFieldVal('srclist', true);
  5299. const dstlist = getMangleFieldVal('dstlist', true);
  5300. const srcgeo = getMangleFieldVal('srcgeo', true);
  5301. const dstgeo = getMangleFieldVal('dstgeo', true);
  5302. const proto = getMangleFieldVal('proto', true);
  5303. const sport = getMangleFieldVal('sport', true);
  5304. const dport = getMangleFieldVal('dport', true);
  5305. const anyport = getMangleFieldVal('anyport', true);
  5306. const iniface = getMangleFieldVal('iniface', true);
  5307. const outiface = getMangleFieldVal('outiface', true);
  5308. const inifacelist = getMangleFieldVal('inifacelist', true);
  5309. const outifacelist = getMangleFieldVal('outifacelist', true);
  5310. const pktmark = getMangleFieldVal('pktmark', true);
  5311. const connmark = getMangleFieldVal('connmark', true);
  5312. const routingmark = getMangleFieldVal('routingmark', true);
  5313. const conntype = getMangleFieldVal('conntype', false);
  5314. const states = [];
  5315. const csBox = document.getElementById('mangle-field-cs');
  5316. if (csBox && !csBox.classList.contains('hidden')) {
  5317. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5318. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5319. });
  5320. }
  5321. const natStates = [];
  5322. const natBox = document.getElementById('mangle-field-natstate');
  5323. if (natBox && !natBox.classList.contains('hidden')) {
  5324. ['srcnat', 'dstnat'].forEach(s => {
  5325. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5326. });
  5327. }
  5328. const payload = {
  5329. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5330. id,
  5331. chain,
  5332. action,
  5333. protocol: proto || 'all',
  5334. src_address: src,
  5335. dst_address: dst,
  5336. src_port: sport,
  5337. dst_port: dport,
  5338. any_port: anyport,
  5339. in_interface: iniface,
  5340. out_interface: outiface,
  5341. in_interface_list: inifacelist,
  5342. out_interface_list: outifacelist,
  5343. packet_mark: pktmark,
  5344. connection_mark: connmark,
  5345. routing_mark: routingmark,
  5346. connection_type: conntype,
  5347. connection_state: states,
  5348. connection_nat_state: natStates,
  5349. src_address_list: srclist,
  5350. dst_address_list: dstlist,
  5351. src_geoip: srcgeo,
  5352. dst_geoip: dstgeo,
  5353. comment,
  5354. disabled: !enabled,
  5355. // Advanced tab
  5356. content: getMangleFieldVal('content', false),
  5357. src_mac_address: getMangleFieldVal('srcmac', true),
  5358. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5359. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5360. ipsec_policy: getMangleFieldVal('ipsec', false),
  5361. dscp: getMangleFieldVal('dscp', false),
  5362. tcp_mss: getMangleFieldVal('tcpmss', false),
  5363. tos: document.getElementById('mangle-val-tos')?.value || '',
  5364. packet_size: getMangleFieldVal('pktsize', false),
  5365. random: getMangleFieldVal('random', false),
  5366. tcp_flags: getMangleFieldVal('tcpflags', false),
  5367. icmp_options: getMangleFieldVal('icmpoptions', false),
  5368. ttl: getMangleFieldVal('ttl', false),
  5369. // Extra tab
  5370. nth: getMangleFieldVal('nth', false),
  5371. connection_limit: getMangleFieldVal('connlimit', false),
  5372. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5373. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5374. ip_fragment: getMangleFieldVal('ipfragment', false),
  5375. limit: getMangleFieldVal('limit', false),
  5376. time: getMangleFieldVal('time', false),
  5377. // Action tab
  5378. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5379. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5380. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5381. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5382. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5383. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5384. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5385. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5386. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5387. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5388. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5389. log: document.getElementById('mangle-modal-log')?.checked || false,
  5390. log_prefix: getMangleFieldVal('logprefix', false)
  5391. };
  5392. try {
  5393. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5394. method: 'POST',
  5395. headers: { 'Content-Type': 'application/json' },
  5396. body: JSON.stringify(payload)
  5397. });
  5398. if (res.ok) {
  5399. const data = await res.json();
  5400. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5401. loadFirewall(false);
  5402. if (closeAfter) {
  5403. closeMangleModal();
  5404. } else {
  5405. if (data.id) {
  5406. document.getElementById('mangle-modal-id').value = data.id;
  5407. const badge = document.getElementById('mangle-modal-badge');
  5408. if (badge) badge.innerText = `#${data.id}`;
  5409. }
  5410. }
  5411. } else {
  5412. const err = await res.json();
  5413. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5414. }
  5415. } catch (err) {
  5416. showToast('Error', err.message, 'error');
  5417. }
  5418. }
  5419. function submitSaveMangleRule(e) {
  5420. if (e && e.preventDefault) e.preventDefault();
  5421. return applyMangleRule(true);
  5422. }
  5423. function startMangleStatPolling() {
  5424. stopMangleStatPolling();
  5425. pollMangleRuleStats();
  5426. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5427. }
  5428. function stopMangleStatPolling() {
  5429. if (state.mangleStatInterval) {
  5430. clearInterval(state.mangleStatInterval);
  5431. state.mangleStatInterval = null;
  5432. }
  5433. }
  5434. async function pollMangleRuleStats() {
  5435. const id = document.getElementById('mangle-modal-id')?.value;
  5436. if (!id) {
  5437. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5438. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5439. return;
  5440. }
  5441. try {
  5442. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5443. if (!res.ok) return;
  5444. const rules = await res.json();
  5445. const r = rules.find(x => x.id === id);
  5446. if (!r) return;
  5447. const now = Date.now();
  5448. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5449. state.mangleLastTimestamp = now;
  5450. const curBytes = r.bytes || 0;
  5451. const curPackets = r.packets || 0;
  5452. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  5453. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  5454. state.mangleLastBytes = curBytes;
  5455. state.mangleLastPackets = curPackets;
  5456. const rateBps = Math.round((deltaBytes * 8) / dt);
  5457. const ratePkt = Math.round(deltaPkts / dt);
  5458. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5459. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5460. state.mangleStatRateHistory.push(rateBps);
  5461. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5462. state.mangleStatPktHistory.push(ratePkt);
  5463. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5464. const bEl = document.getElementById('mangle-stat-bytes');
  5465. const pEl = document.getElementById('mangle-stat-packets');
  5466. const rEl = document.getElementById('mangle-stat-rate');
  5467. const prEl = document.getElementById('mangle-stat-pktrate');
  5468. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5469. if (pEl) pEl.value = curPackets.toLocaleString();
  5470. if (rEl) rEl.value = formatBps(rateBps);
  5471. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5472. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5473. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5474. } catch (e) {
  5475. console.error('Error polling Mangle rule stats', e);
  5476. }
  5477. }
  5478. async function moveMangleRule(id, dir) {
  5479. id = decodeURIComponent(id);
  5480. try {
  5481. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5482. method: 'POST',
  5483. headers: { 'Content-Type': 'application/json' },
  5484. body: JSON.stringify({ direction: dir })
  5485. });
  5486. if (res.ok) loadFirewall(false);
  5487. } catch (err) {
  5488. showToast('Error', err.message, 'error');
  5489. }
  5490. }
  5491. async function toggleMangleRuleState(id, disabled) {
  5492. id = decodeURIComponent(id);
  5493. try {
  5494. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5495. method: 'POST',
  5496. headers: { 'Content-Type': 'application/json' },
  5497. body: JSON.stringify({ disabled })
  5498. });
  5499. if (res.ok) loadFirewall(false);
  5500. } catch (err) {
  5501. showToast('Error', err.message, 'error');
  5502. }
  5503. }
  5504. async function deleteMangleRule(id) {
  5505. id = decodeURIComponent(id);
  5506. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5507. try {
  5508. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5509. if (res.ok) {
  5510. showToast('Deleted', 'Mangle rule removed', 'success');
  5511. loadFirewall(false);
  5512. }
  5513. } catch (err) {
  5514. showToast('Error', err.message, 'error');
  5515. }
  5516. }
  5517. // ----------------- Address Lists -----------------
  5518. function renderAddressLists() {
  5519. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5520. const tbody = document.getElementById('addrlist-table-body');
  5521. const empty = document.getElementById('addrlist-empty');
  5522. if (!tbody) return;
  5523. tbody.innerHTML = '';
  5524. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5525. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  5526. // Update filter select
  5527. const sel = document.getElementById('addrlist-filter-name');
  5528. if (sel) {
  5529. const cur = sel.value;
  5530. sel.innerHTML = '<option value="">All Lists</option>';
  5531. const set = new Set((state.addressLists || []).map(a => a.name));
  5532. set.forEach(n => {
  5533. const opt = document.createElement('option');
  5534. opt.value = n;
  5535. opt.innerText = n;
  5536. if (n === cur) opt.selected = true;
  5537. sel.appendChild(opt);
  5538. });
  5539. }
  5540. if (entries.length === 0) {
  5541. empty?.classList.remove('hidden');
  5542. return;
  5543. }
  5544. empty?.classList.add('hidden');
  5545. entries.forEach((raw, idx) => {
  5546. const e = safeFirewallRow(raw);
  5547. const tr = document.createElement('tr');
  5548. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5549. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5550. tr.innerHTML = `
  5551. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5552. <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>
  5553. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5554. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5555. <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>
  5556. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5557. ${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>
  5558. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5559. `}
  5560. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5561. </td>
  5562. `;
  5563. tbody.appendChild(tr);
  5564. });
  5565. populateCommonAddrListDatalist();
  5566. }
  5567. function openAddAddrListModal() {
  5568. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5569. document.getElementById('addrlist-modal-id').value = '';
  5570. document.getElementById('addrlist-modal-name').value = '';
  5571. document.getElementById('addrlist-modal-addr').value = '';
  5572. document.getElementById('addrlist-modal-comment').value = '';
  5573. document.getElementById('addrlist-modal-disabled').checked = false;
  5574. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5575. if (submitBtn) submitBtn.innerText = 'Add to List';
  5576. document.getElementById('addrlist-modal').classList.remove('hidden');
  5577. }
  5578. function openEditAddrListModal(id) {
  5579. id = decodeURIComponent(id);
  5580. const e = (state.addressLists || []).find(item => item.id === id);
  5581. if (!e) return;
  5582. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5583. document.getElementById('addrlist-modal-id').value = e.id;
  5584. document.getElementById('addrlist-modal-name').value = e.name;
  5585. document.getElementById('addrlist-modal-addr').value = e.address;
  5586. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5587. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5588. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5589. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5590. document.getElementById('addrlist-modal').classList.remove('hidden');
  5591. }
  5592. function closeAddrListModal() {
  5593. document.getElementById('addrlist-modal').classList.add('hidden');
  5594. }
  5595. async function submitSaveAddrList(e) {
  5596. e.preventDefault();
  5597. const id = document.getElementById('addrlist-modal-id').value;
  5598. const name = document.getElementById('addrlist-modal-name').value.trim();
  5599. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5600. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5601. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5602. try {
  5603. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5604. method: 'POST',
  5605. headers: { 'Content-Type': 'application/json' },
  5606. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5607. });
  5608. if (res.ok) {
  5609. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5610. closeAddrListModal();
  5611. loadFirewall(false);
  5612. } else {
  5613. const err = await res.json();
  5614. showToast('Error', err.message || 'Failed to save address list', 'error');
  5615. }
  5616. } catch (err) {
  5617. showToast('Error', err.message, 'error');
  5618. }
  5619. }
  5620. async function toggleAddrListState(id, disabled) {
  5621. id = decodeURIComponent(id);
  5622. try {
  5623. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5624. method: 'POST',
  5625. headers: { 'Content-Type': 'application/json' },
  5626. body: JSON.stringify({ disabled })
  5627. });
  5628. if (res.ok) {
  5629. loadFirewall(false);
  5630. }
  5631. } catch (err) {
  5632. showToast('Error', err.message, 'error');
  5633. }
  5634. }
  5635. async function deleteAddrList(id) {
  5636. id = decodeURIComponent(id);
  5637. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5638. try {
  5639. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5640. if (res.ok) {
  5641. showToast('Deleted', 'Address list item removed', 'info');
  5642. loadFirewall(false);
  5643. }
  5644. } catch (err) {
  5645. showToast('Error', err.message, 'error');
  5646. }
  5647. }
  5648. // ----------------- Geo-Location IP Management -----------------
  5649. async function loadGeoIP() {
  5650. try {
  5651. const [statusRes, countriesRes] = await Promise.all([
  5652. fetch(`${API_BASE}/firewall/geoip/status`),
  5653. fetch(`${API_BASE}/firewall/geoip/countries`)
  5654. ]);
  5655. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5656. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5657. updateGeoHeader();
  5658. renderGeoCountries();
  5659. } catch (err) {
  5660. console.error('Failed to load GeoIP:', err);
  5661. }
  5662. }
  5663. function getGeoUsageMap() {
  5664. const usage = {};
  5665. const checkRule = (r, type) => {
  5666. ['src_geoip', 'dst_geoip'].forEach(field => {
  5667. let val = (r && r[field]) || '';
  5668. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5669. if (code) {
  5670. if (!usage[code]) usage[code] = [];
  5671. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5672. if (!usage[code].includes(label)) usage[code].push(label);
  5673. }
  5674. });
  5675. };
  5676. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5677. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5678. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5679. return usage;
  5680. }
  5681. function updateGeoHeader() {
  5682. const s = state.geoStatus || {};
  5683. const statusBadge = document.getElementById('geo-status-badge');
  5684. if (statusBadge) {
  5685. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5686. statusBadge.className = s.auto_update
  5687. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5688. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5689. }
  5690. const intervalLabel = document.getElementById('geo-interval-label');
  5691. if (intervalLabel) {
  5692. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5693. }
  5694. const usageMap = getGeoUsageMap();
  5695. const inUseCount = Object.keys(usageMap).length;
  5696. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5697. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5698. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5699. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5700. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5701. if (lastSyncEl) {
  5702. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5703. const d = new Date(s.last_updated);
  5704. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5705. } else {
  5706. lastSyncEl.innerText = 'Never (Sync Pending)';
  5707. }
  5708. }
  5709. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5710. if (nextSyncEl) {
  5711. if (s.next_update && !s.next_update.startsWith('0001')) {
  5712. const d = new Date(s.next_update);
  5713. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5714. } else {
  5715. nextSyncEl.innerText = '-';
  5716. }
  5717. }
  5718. const badge = document.getElementById('fw-badge-geo');
  5719. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5720. }
  5721. function renderGeoCountries() {
  5722. const tbody = document.getElementById('geo-table-body');
  5723. const empty = document.getElementById('geo-empty');
  5724. if (!tbody) return;
  5725. tbody.innerHTML = '';
  5726. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5727. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5728. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5729. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5730. const usageMap = getGeoUsageMap();
  5731. const countries = (state.geoCountries || []).filter(c => {
  5732. const isUsed = !!usageMap[c.code];
  5733. if (inUseOnly && !isUsed) return false;
  5734. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5735. if (continent && c.continent !== continent) return false;
  5736. if (q) {
  5737. const matchCode = c.code.toLowerCase().includes(q);
  5738. const matchName = c.name.toLowerCase().includes(q);
  5739. if (!matchCode && !matchName) return false;
  5740. }
  5741. return true;
  5742. });
  5743. if (countries.length === 0) {
  5744. empty?.classList.remove('hidden');
  5745. return;
  5746. }
  5747. empty?.classList.add('hidden');
  5748. countries.forEach(c => {
  5749. const tr = document.createElement('tr');
  5750. const isUsed = !!usageMap[c.code];
  5751. const rulesUsing = usageMap[c.code] || [];
  5752. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5753. let statusHtml = '';
  5754. if (isUsed) {
  5755. 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>`;
  5756. } else if (c.subnet_count > 0) {
  5757. 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>';
  5758. } else {
  5759. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5760. }
  5761. tr.innerHTML = `
  5762. <td class="py-2.5 px-3 text-center">
  5763. <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'}">
  5764. ${c.code}
  5765. </span>
  5766. </td>
  5767. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5768. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5769. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5770. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5771. </td>
  5772. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5773. <td class="py-2.5 px-3">
  5774. ${statusHtml}
  5775. </td>
  5776. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5777. <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>
  5778. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5779. </td>
  5780. `;
  5781. tbody.appendChild(tr);
  5782. });
  5783. }
  5784. function quickFilterGeo(preset) {
  5785. const searchInput = document.getElementById('geo-search-input');
  5786. const continentSel = document.getElementById('geo-continent-filter');
  5787. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5788. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5789. if (searchInput) searchInput.value = '';
  5790. if (continentSel) continentSel.value = '';
  5791. if (inUseCheck) inUseCheck.checked = false;
  5792. if (cachedCheck) cachedCheck.checked = false;
  5793. if (preset === 'GR') {
  5794. if (searchInput) searchInput.value = 'Greece';
  5795. } else if (preset === 'Europe') {
  5796. if (continentSel) continentSel.value = 'Europe';
  5797. } else if (preset === 'HIGHRISK') {
  5798. if (searchInput) searchInput.value = 'China';
  5799. }
  5800. renderGeoCountries();
  5801. }
  5802. async function toggleGeoCountry(code, enabled) {
  5803. try {
  5804. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5805. method: 'POST',
  5806. headers: { 'Content-Type': 'application/json' },
  5807. body: JSON.stringify({ enabled })
  5808. });
  5809. if (res.ok) {
  5810. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5811. loadGeoIP();
  5812. } else {
  5813. const err = await res.json();
  5814. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5815. }
  5816. } catch (err) {
  5817. showToast('Error', err.message, 'error');
  5818. }
  5819. }
  5820. async function updateGeoCountry(code) {
  5821. try {
  5822. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5823. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5824. if (res.ok) {
  5825. const data = await res.json();
  5826. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5827. loadGeoIP();
  5828. } else {
  5829. const err = await res.json();
  5830. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5831. }
  5832. } catch (err) {
  5833. showToast('Error', err.message, 'error');
  5834. }
  5835. }
  5836. async function triggerGeoUpdateNow() {
  5837. const spinner = document.getElementById('geo-update-spinner');
  5838. if (spinner) spinner.classList.remove('hidden');
  5839. try {
  5840. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5841. if (res.ok) {
  5842. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5843. setTimeout(() => {
  5844. loadGeoIP();
  5845. if (spinner) spinner.classList.add('hidden');
  5846. }, 2500);
  5847. } else {
  5848. const err = await res.json();
  5849. showToast('Notice', err.message || 'Update in progress', 'info');
  5850. if (spinner) spinner.classList.add('hidden');
  5851. }
  5852. } catch (err) {
  5853. showToast('Error', err.message, 'error');
  5854. if (spinner) spinner.classList.add('hidden');
  5855. }
  5856. }
  5857. async function applyGeoPreset(preset) {
  5858. try {
  5859. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5860. method: 'POST',
  5861. headers: { 'Content-Type': 'application/json' },
  5862. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5863. });
  5864. if (res.ok) {
  5865. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5866. loadGeoIP();
  5867. }
  5868. } catch (err) {
  5869. showToast('Error', err.message, 'error');
  5870. }
  5871. }
  5872. function openGeoIntervalModal() {
  5873. const s = state.geoStatus || {};
  5874. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5875. const sel = document.getElementById('geo-cfg-interval');
  5876. const customBox = document.getElementById('geo-cfg-custom-box');
  5877. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5878. const curHours = s.interval_hours || 24;
  5879. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5880. if (matchOption) {
  5881. sel.value = String(curHours);
  5882. customBox.classList.add('hidden');
  5883. } else {
  5884. sel.value = 'custom';
  5885. customHoursInput.value = curHours;
  5886. customBox.classList.remove('hidden');
  5887. }
  5888. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5889. }
  5890. function closeGeoIntervalModal() {
  5891. document.getElementById('geo-interval-modal').classList.add('hidden');
  5892. }
  5893. function toggleCustomGeoInterval() {
  5894. const val = document.getElementById('geo-cfg-interval').value;
  5895. const customBox = document.getElementById('geo-cfg-custom-box');
  5896. if (val === 'custom') {
  5897. customBox.classList.remove('hidden');
  5898. } else {
  5899. customBox.classList.add('hidden');
  5900. }
  5901. }
  5902. async function submitGeoIntervalSettings(e) {
  5903. e.preventDefault();
  5904. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5905. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5906. let hours = 24;
  5907. if (intervalVal === 'custom') {
  5908. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5909. } else {
  5910. hours = parseInt(intervalVal, 10) || 24;
  5911. }
  5912. try {
  5913. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5914. method: 'POST',
  5915. headers: { 'Content-Type': 'application/json' },
  5916. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5917. });
  5918. if (res.ok) {
  5919. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5920. closeGeoIntervalModal();
  5921. loadGeoIP();
  5922. } else {
  5923. const err = await res.json();
  5924. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5925. }
  5926. } catch (err) {
  5927. showToast('Error', err.message, 'error');
  5928. }
  5929. }
  5930. async function viewGeoSubnets(code, name) {
  5931. if (!name) {
  5932. const found = (state.geoCountries || []).find(x => x.code === code);
  5933. name = found ? found.name : code;
  5934. }
  5935. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5936. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5937. const listEl = document.getElementById('geo-subnets-list');
  5938. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5939. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5940. try {
  5941. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5942. if (res.ok) {
  5943. const data = await res.json();
  5944. const subnets = data.subnets || [];
  5945. if (subnets.length === 0) {
  5946. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5947. } else {
  5948. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5949. }
  5950. } else {
  5951. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5952. }
  5953. } catch (err) {
  5954. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5955. }
  5956. }
  5957. function closeGeoSubnetsModal() {
  5958. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5959. }
  5960. // ----------------- Active Connections Tracking -----------------
  5961. async function loadConnections() {
  5962. try {
  5963. const res = await fetch(`${API_BASE}/firewall/connections`);
  5964. const data = await res.json();
  5965. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  5966. state.connections = Array.isArray(data) ? data : [];
  5967. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5968. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5969. renderConnections();
  5970. } catch (err) {
  5971. console.error('Failed to load connections:', err);
  5972. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  5973. }
  5974. }
  5975. function renderConnections() {
  5976. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5977. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5978. const tbody = document.getElementById('conns-table-body');
  5979. const empty = document.getElementById('conns-empty');
  5980. if (!tbody) return;
  5981. tbody.innerHTML = '';
  5982. const conns = (state.connections || []).filter(c => {
  5983. if (protoFilter && c.protocol !== protoFilter) return false;
  5984. if (search) {
  5985. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5986. if (!line.includes(search)) return false;
  5987. }
  5988. return true;
  5989. });
  5990. if (conns.length === 0) {
  5991. empty?.classList.remove('hidden');
  5992. return;
  5993. }
  5994. empty?.classList.add('hidden');
  5995. conns.slice(0, 150).forEach(c => {
  5996. const tr = document.createElement('tr');
  5997. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5998. let stateColor = 'text-slate-400';
  5999. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6000. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6001. tr.innerHTML = `
  6002. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6003. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6004. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6005. <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>
  6006. <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>
  6007. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6008. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6009. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6010. <td class="py-2.5 px-3 text-right font-sans">
  6011. ${['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>` : ''}
  6012. </td>
  6013. `;
  6014. tbody.appendChild(tr);
  6015. });
  6016. }
  6017. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6018. try {
  6019. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6020. method: 'POST',
  6021. headers: { 'Content-Type': 'application/json' },
  6022. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6023. });
  6024. if (res.ok) {
  6025. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6026. loadConnections();
  6027. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6028. } catch (err) {
  6029. showToast('Error', err.message, 'error');
  6030. }
  6031. }
  6032. async function resetFirewallCounters() {
  6033. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6034. try {
  6035. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6036. if (res.ok) {
  6037. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6038. loadFirewall(false);
  6039. }
  6040. } catch (err) {
  6041. showToast('Error', err.message, 'error');
  6042. }
  6043. }
  6044. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6045. function switchRoutesSubTab(tab) {
  6046. state.routesSubTab = tab;
  6047. const tabs = ['routes', 'rules', 'tables'];
  6048. tabs.forEach(t => {
  6049. const panel = document.getElementById(`routes-subtab-${t}`);
  6050. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6051. if (panel) {
  6052. if (t === tab) panel.classList.remove('hidden');
  6053. else panel.classList.add('hidden');
  6054. }
  6055. if (btn) {
  6056. if (t === tab) {
  6057. 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';
  6058. } else {
  6059. 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';
  6060. }
  6061. }
  6062. });
  6063. setTimeout(initTableSorting, 50);
  6064. }
  6065. async function loadRoutes() {
  6066. try {
  6067. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6068. fetch(`${API_BASE}/routes`),
  6069. fetch(`${API_BASE}/routing/rules`),
  6070. fetch(`${API_BASE}/routing/tables`)
  6071. ]);
  6072. if (routesRes.ok) state.routes = await routesRes.json();
  6073. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6074. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6075. const bRoutes = document.getElementById('routes-badge-routes');
  6076. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6077. const showSystem = document.getElementById('prule-show-system')?.checked;
  6078. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6079. const bRules = document.getElementById('routes-badge-rules');
  6080. if (bRules) bRules.innerText = userRules.length;
  6081. const bTables = document.getElementById('routes-badge-tables');
  6082. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6083. const bRoutesCount = document.getElementById('badge-routes-count');
  6084. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6085. renderRoutesList();
  6086. renderPolicyRules();
  6087. renderRoutingTables();
  6088. } catch (err) {
  6089. console.error('Failed to load routing:', err);
  6090. }
  6091. }
  6092. function getRouteProtocolBadge(proto) {
  6093. const p = (proto || 'static').toLowerCase();
  6094. switch (p) {
  6095. case 'bgp':
  6096. 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>`;
  6097. case 'ibgp':
  6098. 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>`;
  6099. case 'ospf':
  6100. 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>`;
  6101. case 'rip':
  6102. 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>`;
  6103. case 'static':
  6104. 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>`;
  6105. case 'connected':
  6106. 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>`;
  6107. case 'dhcp':
  6108. 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>`;
  6109. case 'multicast':
  6110. 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>`;
  6111. default:
  6112. 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>`;
  6113. }
  6114. }
  6115. function renderRoutesList() {
  6116. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6117. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6118. const tbody = document.getElementById('routes-table-body');
  6119. const empty = document.getElementById('routes-empty');
  6120. if (!tbody) return;
  6121. // Update table filter select
  6122. const sel = document.getElementById('routes-filter-table');
  6123. if (sel) {
  6124. const cur = sel.value;
  6125. sel.innerHTML = '<option value="">All Tables</option>';
  6126. (state.routingTables || []).forEach(t => {
  6127. const opt = document.createElement('option');
  6128. opt.value = t.name;
  6129. opt.innerText = t.name;
  6130. if (t.name === cur) opt.selected = true;
  6131. sel.appendChild(opt);
  6132. });
  6133. }
  6134. const routes = (state.routes || []).filter(r => {
  6135. if (tableFilter && r.routing_table !== tableFilter) return false;
  6136. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6137. if (typeFilter === 'multicast' && !r.multicast) return false;
  6138. if (typeFilter === 'static' && !r.static) return false;
  6139. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6140. if (typeFilter === 'connected' && !r.connect) return false;
  6141. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6142. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6143. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6144. return true;
  6145. });
  6146. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6147. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6148. let summaryText = `${routes.length} Routes`;
  6149. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6150. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6151. const badgeEl = document.getElementById('routes-count-badge');
  6152. if (badgeEl) badgeEl.innerText = summaryText;
  6153. if (routes.length === 0) {
  6154. empty?.classList.remove('hidden');
  6155. tbody.innerHTML = '';
  6156. return;
  6157. }
  6158. empty?.classList.add('hidden');
  6159. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6160. if (tbody.dataset.sig === sig) {
  6161. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6162. }
  6163. tbody.dataset.sig = sig;
  6164. tbody.innerHTML = '';
  6165. routes.forEach(r => {
  6166. const tr = document.createElement('tr');
  6167. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6168. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6169. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6170. let flags = '';
  6171. if (r.dynamic) flags += 'D';
  6172. if (r.active) flags += 'A';
  6173. if (r.connect) flags += 'C';
  6174. if (r.static) flags += 'S';
  6175. if (r.ecmp) flags += 'E';
  6176. if (r.multicast) flags += 'M';
  6177. if (r.disabled) flags += 'X';
  6178. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6179. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6180. if (r.check_gateway === 'internet') {
  6181. if (r.health_status === 'online') {
  6182. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6183. healthCell = `
  6184. <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)">
  6185. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6186. <span>Internet OK (${ms}ms)</span>
  6187. </span>
  6188. `;
  6189. } else if (r.health_status === 'offline') {
  6190. healthCell = `
  6191. <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.">
  6192. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6193. <span>Internet Down</span>
  6194. </span>
  6195. `;
  6196. } else {
  6197. healthCell = `
  6198. <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">
  6199. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6200. <span>Checking...</span>
  6201. </span>
  6202. `;
  6203. }
  6204. } else if (r.check_gateway === 'ping') {
  6205. if (r.health_status === 'online') {
  6206. healthCell = `
  6207. <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">
  6208. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6209. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6210. </span>
  6211. `;
  6212. } else if (r.health_status === 'offline') {
  6213. healthCell = `
  6214. <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">
  6215. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6216. <span>Gateway Dead</span>
  6217. </span>
  6218. `;
  6219. }
  6220. }
  6221. const flagDescriptions = [];
  6222. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6223. if (r.active) flagDescriptions.push('Active (A)');
  6224. if (r.connect) flagDescriptions.push('Connected (C)');
  6225. if (r.static) flagDescriptions.push('Static (S)');
  6226. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6227. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6228. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6229. tr.innerHTML = `
  6230. <td class="py-2.5 px-3 text-center">
  6231. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6232. 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')
  6233. }" title="Flags: ${flagDescriptions.join(', ')}">
  6234. ${flags || '-'}
  6235. </span>
  6236. </td>
  6237. <td class="py-2.5 px-3">
  6238. <div class="flex items-center gap-1.5 flex-wrap">
  6239. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6240. ${r.ecmp ? `
  6241. <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)">
  6242. <span>⚡ ECMP</span>
  6243. </span>
  6244. ` : ''}
  6245. ${r.multicast ? `
  6246. <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">
  6247. <span>IGMP</span>
  6248. </span>
  6249. ` : ''}
  6250. </div>
  6251. </td>
  6252. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6253. <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>
  6254. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6255. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6256. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6257. <td class="py-2.5 px-3">${healthCell}</td>
  6258. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6259. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6260. ${r.static ? `
  6261. <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>
  6262. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6263. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6264. ` : `
  6265. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6266. `}
  6267. </td>
  6268. `;
  6269. tbody.appendChild(tr);
  6270. });
  6271. }
  6272. function openAddRouteModal() {
  6273. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6274. document.getElementById('route-modal-id').value = '';
  6275. document.getElementById('route-modal-old-dst').value = '';
  6276. document.getElementById('route-modal-old-gw').value = '';
  6277. document.getElementById('route-modal-old-distance').value = '';
  6278. document.getElementById('route-modal-old-table').value = '';
  6279. document.getElementById('route-modal-old-iface').value = '';
  6280. const dstInput = document.getElementById('route-modal-dst');
  6281. const gwInput = document.getElementById('route-modal-gw');
  6282. const distInput = document.getElementById('route-modal-distance');
  6283. const ifaceSelect = document.getElementById('route-modal-iface');
  6284. const tableSelect = document.getElementById('route-modal-table');
  6285. const commentInput = document.getElementById('route-modal-comment');
  6286. const disCheck = document.getElementById('route-modal-disabled');
  6287. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6288. dstInput.disabled = false;
  6289. dstInput.value = '0.0.0.0/0';
  6290. gwInput.disabled = false;
  6291. gwInput.value = '';
  6292. distInput.disabled = false;
  6293. distInput.value = '1';
  6294. ifaceSelect.disabled = false;
  6295. tableSelect.disabled = false;
  6296. commentInput.disabled = false;
  6297. commentInput.value = '';
  6298. disCheck.disabled = false;
  6299. disCheck.checked = false;
  6300. if (saveBtn) saveBtn.classList.remove('hidden');
  6301. const checkGw = document.getElementById('route-modal-check-gw');
  6302. if (checkGw) checkGw.value = 'internet';
  6303. const checkTarget = document.getElementById('route-modal-check-target');
  6304. if (checkTarget) checkTarget.value = '1.1.1.1';
  6305. const checkInterval = document.getElementById('route-modal-check-interval');
  6306. if (checkInterval) checkInterval.value = '5';
  6307. const checkThresh = document.getElementById('route-modal-check-threshold');
  6308. if (checkThresh) checkThresh.value = '3';
  6309. toggleRouteCheckModeUI();
  6310. populateInterfaceSelect('route-modal-iface');
  6311. // Populate tables
  6312. tableSelect.innerHTML = '';
  6313. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6314. const opt = document.createElement('option');
  6315. opt.value = t.name;
  6316. opt.innerText = t.name;
  6317. if (t.name === 'main') opt.selected = true;
  6318. tableSelect.appendChild(opt);
  6319. });
  6320. document.getElementById('route-modal').classList.remove('hidden');
  6321. }
  6322. function openEditRouteModal(id) {
  6323. const r = (state.routes || []).find(route => route.id === id);
  6324. if (!r) return;
  6325. const isStatic = !!r.static;
  6326. document.getElementById('route-modal-title').innerText = isStatic
  6327. ? `Edit Route: ${r.dst_address}`
  6328. : `Route Properties (Read Only): ${r.dst_address}`;
  6329. document.getElementById('route-modal-id').value = r.id;
  6330. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6331. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6332. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6333. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6334. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6335. const dstInput = document.getElementById('route-modal-dst');
  6336. const gwInput = document.getElementById('route-modal-gw');
  6337. const distInput = document.getElementById('route-modal-distance');
  6338. const ifaceSelect = document.getElementById('route-modal-iface');
  6339. const tableSelect = document.getElementById('route-modal-table');
  6340. const commentInput = document.getElementById('route-modal-comment');
  6341. const disCheck = document.getElementById('route-modal-disabled');
  6342. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6343. dstInput.value = r.dst_address;
  6344. gwInput.value = r.gateway || '';
  6345. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6346. commentInput.value = r.comment || '';
  6347. disCheck.checked = !!r.disabled;
  6348. const checkGw = document.getElementById('route-modal-check-gw');
  6349. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6350. const checkTarget = document.getElementById('route-modal-check-target');
  6351. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6352. const checkInterval = document.getElementById('route-modal-check-interval');
  6353. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6354. const checkThresh = document.getElementById('route-modal-check-threshold');
  6355. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6356. toggleRouteCheckModeUI();
  6357. dstInput.disabled = !isStatic;
  6358. gwInput.disabled = !isStatic;
  6359. distInput.disabled = !isStatic;
  6360. ifaceSelect.disabled = !isStatic;
  6361. tableSelect.disabled = !isStatic;
  6362. commentInput.disabled = !isStatic;
  6363. disCheck.disabled = !isStatic;
  6364. if (checkGw) checkGw.disabled = !isStatic;
  6365. if (checkTarget) checkTarget.disabled = !isStatic;
  6366. if (checkInterval) checkInterval.disabled = !isStatic;
  6367. if (checkThresh) checkThresh.disabled = !isStatic;
  6368. if (saveBtn) {
  6369. if (isStatic) {
  6370. saveBtn.classList.remove('hidden');
  6371. } else {
  6372. saveBtn.classList.add('hidden');
  6373. }
  6374. }
  6375. populateInterfaceSelect('route-modal-iface', r.interface);
  6376. tableSelect.innerHTML = '';
  6377. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6378. const opt = document.createElement('option');
  6379. opt.value = t.name;
  6380. opt.innerText = t.name;
  6381. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6382. tableSelect.appendChild(opt);
  6383. });
  6384. document.getElementById('route-modal').classList.remove('hidden');
  6385. }
  6386. function closeRouteModal() {
  6387. document.getElementById('route-modal').classList.add('hidden');
  6388. }
  6389. function setRouteCheckTarget(ip) {
  6390. const inp = document.getElementById('route-modal-check-target');
  6391. if (inp) inp.value = ip;
  6392. }
  6393. function toggleRouteCheckModeUI() {
  6394. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6395. const targetRow = document.getElementById('route-row-check-target');
  6396. const paramsRow = document.getElementById('route-row-check-params');
  6397. if (mode === 'none') {
  6398. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6399. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6400. } else if (mode === 'ping') {
  6401. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6402. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6403. } else { // internet
  6404. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6405. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6406. }
  6407. }
  6408. async function submitSaveRoute(e) {
  6409. e.preventDefault();
  6410. const id = document.getElementById('route-modal-id').value;
  6411. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6412. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6413. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6414. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6415. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6416. const dst = document.getElementById('route-modal-dst').value.trim();
  6417. const gw = document.getElementById('route-modal-gw').value.trim();
  6418. const table = document.getElementById('route-modal-table').value;
  6419. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6420. const iface = document.getElementById('route-modal-iface').value;
  6421. const comment = document.getElementById('route-modal-comment').value.trim();
  6422. const disabled = document.getElementById('route-modal-disabled').checked;
  6423. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6424. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6425. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6426. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6427. if (!dst) {
  6428. showToast('Error', 'Destination address is required', 'error');
  6429. return;
  6430. }
  6431. if (!gw && !iface) {
  6432. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6433. return;
  6434. }
  6435. const payload = {
  6436. id,
  6437. old_dst_address: oldDst,
  6438. old_gateway: oldGw,
  6439. old_routing_table: oldTable,
  6440. old_interface: oldIface,
  6441. dst_address: dst,
  6442. gateway: gw || iface,
  6443. routing_table: table,
  6444. distance,
  6445. interface: iface,
  6446. comment,
  6447. disabled,
  6448. check_gateway,
  6449. check_target,
  6450. check_interval,
  6451. check_threshold
  6452. };
  6453. if (oldDistStr !== undefined && oldDistStr !== '') {
  6454. payload.old_distance = parseInt(oldDistStr, 10);
  6455. }
  6456. try {
  6457. const res = await fetch(`${API_BASE}/routes`, {
  6458. method: 'POST',
  6459. headers: { 'Content-Type': 'application/json' },
  6460. body: JSON.stringify(payload)
  6461. });
  6462. if (res.ok) {
  6463. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6464. closeRouteModal();
  6465. loadRoutes();
  6466. } else {
  6467. const err = await res.json();
  6468. showToast('Error', err.message || 'Failed to save route', 'error');
  6469. }
  6470. } catch (err) {
  6471. showToast('Error', err.message, 'error');
  6472. }
  6473. }
  6474. async function toggleRouteState(id, disabled) {
  6475. try {
  6476. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6477. method: 'POST',
  6478. headers: { 'Content-Type': 'application/json' },
  6479. body: JSON.stringify({ disabled })
  6480. });
  6481. if (res.ok) loadRoutes();
  6482. } catch (err) {
  6483. showToast('Error', err.message, 'error');
  6484. }
  6485. }
  6486. async function deleteRoute(id) {
  6487. if (!confirm('Are you sure you want to delete this route?')) return;
  6488. try {
  6489. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6490. if (res.ok) {
  6491. showToast('Deleted', 'Route removed', 'success');
  6492. loadRoutes();
  6493. }
  6494. } catch (err) {
  6495. showToast('Error', err.message, 'error');
  6496. }
  6497. }
  6498. // ----------------- Policy Rules (/ip route rule) -----------------
  6499. function renderPolicyRules() {
  6500. const tbody = document.getElementById('rules-table-body');
  6501. const empty = document.getElementById('rules-empty');
  6502. if (!tbody) return;
  6503. const showSystem = document.getElementById('prule-show-system')?.checked;
  6504. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6505. const countBadge = document.getElementById('rules-count-badge');
  6506. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6507. const bRules = document.getElementById('routes-badge-rules');
  6508. if (bRules) bRules.innerText = filtered.length;
  6509. if (filtered.length === 0) {
  6510. empty?.classList.remove('hidden');
  6511. tbody.innerHTML = '';
  6512. return;
  6513. }
  6514. empty?.classList.add('hidden');
  6515. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6516. if (tbody.dataset.sig === sig) return;
  6517. tbody.dataset.sig = sig;
  6518. tbody.innerHTML = '';
  6519. filtered.forEach(pr => {
  6520. const isSys = pr.is_default || pr.is_system;
  6521. const tr = document.createElement('tr');
  6522. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6523. tr.innerHTML = `
  6524. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6525. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6526. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6527. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6528. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6529. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6530. <td class="py-2.5 px-3 text-right font-sans">
  6531. ${!pr.is_default ? `
  6532. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6533. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6534. </td>
  6535. `;
  6536. tbody.appendChild(tr);
  6537. });
  6538. }
  6539. function openAddPolicyRuleModal() {
  6540. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6541. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6542. document.getElementById('prule-modal-mark').value = '';
  6543. document.getElementById('prule-modal-src').value = '';
  6544. document.getElementById('prule-modal-dst').value = '';
  6545. const sel = document.getElementById('prule-modal-table');
  6546. sel.innerHTML = '';
  6547. (state.routingTables || []).forEach(t => {
  6548. const opt = document.createElement('option');
  6549. opt.value = t.name;
  6550. opt.innerText = t.name;
  6551. sel.appendChild(opt);
  6552. });
  6553. document.getElementById('prule-modal').classList.remove('hidden');
  6554. }
  6555. function closePolicyRuleModal() {
  6556. document.getElementById('prule-modal').classList.add('hidden');
  6557. }
  6558. async function submitSavePolicyRule(e) {
  6559. e.preventDefault();
  6560. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6561. const mark = document.getElementById('prule-modal-mark').value.trim();
  6562. const src = document.getElementById('prule-modal-src').value.trim();
  6563. const dst = document.getElementById('prule-modal-dst').value.trim();
  6564. const table = document.getElementById('prule-modal-table').value;
  6565. const action = document.getElementById('prule-modal-action').value;
  6566. try {
  6567. const res = await fetch(`${API_BASE}/routing/rules`, {
  6568. method: 'POST',
  6569. headers: { 'Content-Type': 'application/json' },
  6570. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6571. });
  6572. if (res.ok) {
  6573. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6574. closePolicyRuleModal();
  6575. loadRoutes();
  6576. } else {
  6577. const err = await res.json();
  6578. showToast('Error', err.message, 'error');
  6579. }
  6580. } catch (err) {
  6581. showToast('Error', err.message, 'error');
  6582. }
  6583. }
  6584. async function deletePolicyRule(id) {
  6585. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6586. try {
  6587. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6588. if (res.ok) {
  6589. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6590. loadRoutes();
  6591. }
  6592. } catch (err) {
  6593. showToast('Error', err.message, 'error');
  6594. }
  6595. }
  6596. // ----------------- Routing Tables -----------------
  6597. function renderRoutingTables() {
  6598. const tbody = document.getElementById('tables-table-body');
  6599. if (!tbody) return;
  6600. const tables = state.routingTables || [];
  6601. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6602. if (tbody.dataset.sig === sig) return;
  6603. tbody.dataset.sig = sig;
  6604. tbody.innerHTML = '';
  6605. (state.routingTables || []).forEach(t => {
  6606. const tr = document.createElement('tr');
  6607. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6608. tr.innerHTML = `
  6609. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6610. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6611. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6612. `;
  6613. tbody.appendChild(tr);
  6614. });
  6615. }
  6616. function openAddTableModal() {
  6617. document.getElementById('table-modal-name').value = '';
  6618. document.getElementById('table-modal-id').value = '';
  6619. document.getElementById('table-modal-comment').value = '';
  6620. document.getElementById('table-modal').classList.remove('hidden');
  6621. }
  6622. function closeTableModal() {
  6623. document.getElementById('table-modal').classList.add('hidden');
  6624. }
  6625. async function submitSaveTable(e) {
  6626. e.preventDefault();
  6627. const name = document.getElementById('table-modal-name').value.trim();
  6628. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6629. const comment = document.getElementById('table-modal-comment').value.trim();
  6630. try {
  6631. const res = await fetch(`${API_BASE}/routing/tables`, {
  6632. method: 'POST',
  6633. headers: { 'Content-Type': 'application/json' },
  6634. body: JSON.stringify({ name, table_id: id, comment })
  6635. });
  6636. if (res.ok) {
  6637. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6638. closeTableModal();
  6639. loadRoutes();
  6640. } else {
  6641. const err = await res.json();
  6642. showToast('Error', err.message, 'error');
  6643. }
  6644. } catch (err) {
  6645. showToast('Error', err.message, 'error');
  6646. }
  6647. }
  6648. async function loadDebianConfig() {
  6649. const view = document.getElementById('debian-config-view');
  6650. view.innerText = 'Generating live configuration...';
  6651. try {
  6652. const res = await fetch(`${API_BASE}/debian/config`);
  6653. const data = await res.json();
  6654. view.innerText = data.content || '# Empty config';
  6655. } catch (err) {
  6656. view.innerText = 'Failed to generate Debian network config.';
  6657. }
  6658. }
  6659. async function saveDebianConfig() {
  6660. try {
  6661. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6662. const data = await res.json();
  6663. if (res.ok) {
  6664. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6665. loadDebianConfig();
  6666. }
  6667. } catch (err) {
  6668. showToast('Error', err.message, 'error');
  6669. }
  6670. }
  6671. function showToast(title, message, type = 'info') {
  6672. const container = document.getElementById('toast-container');
  6673. const toast = document.createElement('div');
  6674. const borderColors = {
  6675. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6676. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6677. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6678. };
  6679. 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}`;
  6680. toast.innerHTML = `
  6681. <div class="flex-1">
  6682. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  6683. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  6684. </div>
  6685. `;
  6686. container.appendChild(toast);
  6687. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6688. setTimeout(() => {
  6689. toast.classList.add('opacity-0', 'translate-y-2');
  6690. setTimeout(() => toast.remove(), 300);
  6691. }, 4000);
  6692. }
  6693. function formatTraffic(bytesPerSec) {
  6694. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6695. const kb = bytesPerSec / 1024;
  6696. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6697. const mb = kb / 1024;
  6698. return `${mb.toFixed(2)} MB/s`;
  6699. }
  6700. function toggleSidebar() {
  6701. const sb = document.getElementById('sidebar');
  6702. sb.classList.toggle('-translate-x-full');
  6703. }
  6704. // ======================== EoIP (Ethernet over IP) ========================
  6705. async function loadEoIP(populate = true) {
  6706. try {
  6707. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6708. const data = await res.json();
  6709. state.eoipTunnels = Array.isArray(data) ? data : [];
  6710. const badge = document.getElementById('eoip-count-badge');
  6711. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6712. const sideBadge = document.getElementById('badge-eoip-count');
  6713. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6714. renderEoIPTunnels();
  6715. } catch (err) {
  6716. console.error('Failed to load EoIP:', err);
  6717. }
  6718. }
  6719. function renderEoIPTunnels() {
  6720. const tbody = document.getElementById('eoip-table-body');
  6721. const empty = document.getElementById('eoip-empty');
  6722. if (!tbody) return;
  6723. tbody.innerHTML = '';
  6724. const tunnels = state.eoipTunnels || [];
  6725. if (tunnels.length === 0) {
  6726. empty?.classList.remove('hidden');
  6727. return;
  6728. }
  6729. empty?.classList.add('hidden');
  6730. tunnels.forEach(t => {
  6731. const tr = document.createElement('tr');
  6732. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6733. tr.innerHTML = `
  6734. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6735. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6736. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6737. <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>
  6738. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6739. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6740. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6741. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6742. <td class="py-2.5 px-3 font-mono text-[11px]">
  6743. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6744. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6745. </td>
  6746. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6747. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6748. <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>
  6749. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6750. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6751. </td>
  6752. `;
  6753. tbody.appendChild(tr);
  6754. });
  6755. }
  6756. function openAddEoIPModal() {
  6757. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6758. document.getElementById('eoip-modal-id').value = '';
  6759. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6760. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6761. document.getElementById('eoip-modal-remote').value = '';
  6762. document.getElementById('eoip-modal-ip').value = '';
  6763. document.getElementById('eoip-modal-local').value = '';
  6764. document.getElementById('eoip-modal-mac').value = '';
  6765. document.getElementById('eoip-modal-mtu').value = '1500';
  6766. document.getElementById('eoip-modal-comment').value = '';
  6767. document.getElementById('eoip-modal-clampmss').checked = true;
  6768. document.getElementById('eoip-modal-disabled').checked = false;
  6769. document.getElementById('eoip-modal').classList.remove('hidden');
  6770. }
  6771. function openEditEoIPModal(id) {
  6772. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6773. if (!t) return;
  6774. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6775. document.getElementById('eoip-modal-id').value = t.id;
  6776. document.getElementById('eoip-modal-name').value = t.name;
  6777. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6778. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6779. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6780. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6781. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6782. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6783. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6784. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6785. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6786. document.getElementById('eoip-modal').classList.remove('hidden');
  6787. }
  6788. function closeEoIPModal() {
  6789. document.getElementById('eoip-modal').classList.add('hidden');
  6790. }
  6791. async function submitSaveEoIP(e) {
  6792. e.preventDefault();
  6793. const id = document.getElementById('eoip-modal-id').value;
  6794. const name = document.getElementById('eoip-modal-name').value.trim();
  6795. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6796. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6797. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6798. const local = document.getElementById('eoip-modal-local').value.trim();
  6799. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6800. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6801. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6802. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6803. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6804. try {
  6805. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6806. method: 'POST',
  6807. headers: { 'Content-Type': 'application/json' },
  6808. body: JSON.stringify({
  6809. id,
  6810. name,
  6811. tunnel_id: tunnelId,
  6812. remote_address: remote,
  6813. ip_address: ipAddress,
  6814. local_address: local,
  6815. mac_address: mac,
  6816. mtu,
  6817. clamp_mss: clampMss,
  6818. comment,
  6819. disabled
  6820. })
  6821. });
  6822. if (res.ok) {
  6823. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6824. closeEoIPModal();
  6825. loadEoIP(false);
  6826. fetchData(false);
  6827. } else {
  6828. const err = await res.json();
  6829. showToast('Error', err.message, 'error');
  6830. }
  6831. } catch (err) {
  6832. showToast('Error', err.message, 'error');
  6833. }
  6834. }
  6835. async function toggleEoIPState(id, disabled) {
  6836. try {
  6837. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6838. method: 'POST',
  6839. headers: { 'Content-Type': 'application/json' },
  6840. body: JSON.stringify({ disabled })
  6841. });
  6842. if (res.ok) {
  6843. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6844. loadEoIP(false);
  6845. fetchData(false);
  6846. }
  6847. } catch (err) {
  6848. showToast('Error', err.message, 'error');
  6849. }
  6850. }
  6851. async function deleteEoIP(id) {
  6852. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6853. try {
  6854. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6855. if (res.ok) {
  6856. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6857. loadEoIP(false);
  6858. fetchData(false);
  6859. }
  6860. } catch (err) {
  6861. showToast('Error', err.message, 'error');
  6862. }
  6863. }
  6864. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6865. async function loadAeroTUN(populate = true) {
  6866. try {
  6867. const [tunnelsRes, statsRes] = await Promise.all([
  6868. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6869. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6870. ]);
  6871. if (tunnelsRes.ok) {
  6872. const data = await tunnelsRes.json();
  6873. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6874. }
  6875. if (statsRes.ok) {
  6876. state.aerotunStats = await statsRes.json();
  6877. }
  6878. const countBadge = document.getElementById('aerotun-count-badge');
  6879. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6880. const sideBadge = document.getElementById('badge-aerotun-count');
  6881. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6882. renderAeroTUN();
  6883. } catch (err) {
  6884. console.error('Failed to load AeroTUN:', err);
  6885. }
  6886. }
  6887. function renderAeroTUN() {
  6888. const tbody = document.getElementById('aerotun-table-body');
  6889. const empty = document.getElementById('aerotun-empty');
  6890. // Update summary cards
  6891. const stats = state.aerotunStats || {};
  6892. const tunnels = state.aerotunTunnels || [];
  6893. const statActive = document.getElementById('aerotun-stat-active');
  6894. if (statActive) {
  6895. const activeCount = tunnels.filter(t => t.connected).length;
  6896. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6897. }
  6898. const statSaved = document.getElementById('aerotun-stat-saved');
  6899. if (statSaved) {
  6900. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6901. }
  6902. const statRatio = document.getElementById('aerotun-stat-ratio');
  6903. if (statRatio) {
  6904. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6905. }
  6906. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6907. if (statTraffic) {
  6908. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6909. }
  6910. if (!tbody) return;
  6911. tbody.innerHTML = '';
  6912. if (tunnels.length === 0) {
  6913. empty?.classList.remove('hidden');
  6914. return;
  6915. }
  6916. empty?.classList.add('hidden');
  6917. tunnels.forEach(t => {
  6918. const tr = document.createElement('tr');
  6919. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6920. const modeBadge = t.mode === 'server'
  6921. ? `<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>`
  6922. : `<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>`;
  6923. const endpointInfo = t.mode === 'server'
  6924. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6925. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6926. const compBadge = t.compression
  6927. ? `<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>`
  6928. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6929. const activePeer = t.connected && t.active_peer_endpoint
  6930. ? `<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>`
  6931. : `<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>`;
  6932. const rawRx = formatBytes(t.rx_bytes || 0);
  6933. const rawTx = formatBytes(t.tx_bytes || 0);
  6934. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6935. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6936. tr.innerHTML = `
  6937. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  6938. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6939. <span>${escapeHtml(t.name)}</span>
  6940. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6941. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  6942. </td>
  6943. <td class="py-2.5 px-3">${modeBadge}</td>
  6944. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6945. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6946. <td class="py-2.5 px-3">${compBadge}</td>
  6947. <td class="py-2.5 px-3">${activePeer}</td>
  6948. <td class="py-2.5 px-3 font-mono text-[11px]">
  6949. <span class="text-emerald-400">↓ ${rawRx}</span>
  6950. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6951. </td>
  6952. <td class="py-2.5 px-3 font-mono text-[11px]">
  6953. <span class="text-slate-400">↓ ${wireRx}</span>
  6954. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6955. </td>
  6956. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6957. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6958. ${t.running
  6959. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6960. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6961. }
  6962. <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>
  6963. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6964. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6965. </td>
  6966. `;
  6967. tbody.appendChild(tr);
  6968. });
  6969. }
  6970. function onAeroTUNModeChange() {
  6971. const mode = document.getElementById('aerotun-modal-mode').value;
  6972. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6973. const portInput = document.getElementById('aerotun-modal-port');
  6974. if (mode === 'server') {
  6975. if (!portInput.value) portInput.value = '51830';
  6976. endpointInput.placeholder = 'Optional / learned roaming peer';
  6977. } else {
  6978. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6979. if (!portInput.value) portInput.value = '';
  6980. }
  6981. }
  6982. async function generateAeroTUNKey() {
  6983. try {
  6984. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6985. if (!res.ok) throw new Error(await responseError(res));
  6986. const data = await res.json();
  6987. document.getElementById('aerotun-modal-psk').value = data.key;
  6988. showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  6989. } catch (err) {
  6990. showToast('Key Generation Failed', err.message, 'error');
  6991. }
  6992. }
  6993. function updateAeroTUNSetupHint() {
  6994. const version = document.getElementById('aerotun-modal-protocol').value;
  6995. const key = document.getElementById('aerotun-modal-public').value;
  6996. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  6997. const hint = document.getElementById('aerotun-setup-hint');
  6998. if (!hint) return;
  6999. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? '1. Save disabled to create the local identity. 2. Exchange public keys and share the same PSK. 3. Set allowed peer prefixes, then enable.' : !peer ? 'Local identity saved. Copy the public key to the peer and paste its public key here. Use the same PSK on both endpoints.' : 'Peer identity configured. Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7000. }
  7001. async function copyAeroTUNPublicKey() {
  7002. const input = document.getElementById('aerotun-modal-public');
  7003. if (!input.value) { showToast('Save First', 'Save the disabled tunnel to create its public key', 'info'); return; }
  7004. try {
  7005. await navigator.clipboard.writeText(input.value);
  7006. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7007. } catch {
  7008. input.focus(); input.select();
  7009. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7010. }
  7011. }
  7012. function openAddAeroTUNModal() {
  7013. const tunnels = state.aerotunTunnels || [];
  7014. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7015. document.getElementById('aerotun-modal-id').value = '';
  7016. document.getElementById('aerotun-modal-protocol').value='3';
  7017. document.getElementById('aerotun-modal-public').value='';
  7018. document.getElementById('aerotun-modal-peerkey').value='';
  7019. document.getElementById('aerotun-modal-allowed').value=`10.99.${tunnels.length}.2/32`;
  7020. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  7021. document.getElementById('aerotun-modal-mode').value = 'server';
  7022. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  7023. document.getElementById('aerotun-modal-endpoint').value = '';
  7024. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  7025. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  7026. document.getElementById('aerotun-modal-psk').value = '';
  7027. document.getElementById('aerotun-modal-mtu').value = '1420';
  7028. document.getElementById('aerotun-modal-comment').value = '';
  7029. document.getElementById('aerotun-modal-compression').checked = false;
  7030. document.getElementById('aerotun-modal-defroute').checked = false;
  7031. document.getElementById('aerotun-modal-disabled').checked = true;
  7032. generateAeroTUNKey();
  7033. onAeroTUNModeChange();
  7034. updateAeroTUNSetupHint();
  7035. document.getElementById('aerotun-modal').classList.remove('hidden');
  7036. }
  7037. function openEditAeroTUNModal(id) {
  7038. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  7039. if (!t) return;
  7040. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  7041. document.getElementById('aerotun-modal-id').value = t.id;
  7042. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  7043. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  7044. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  7045. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  7046. document.getElementById('aerotun-modal-name').value = t.name;
  7047. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  7048. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  7049. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  7050. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  7051. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  7052. document.getElementById('aerotun-modal-psk').value = '';
  7053. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  7054. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  7055. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  7056. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  7057. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  7058. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  7059. onAeroTUNModeChange();
  7060. updateAeroTUNSetupHint();
  7061. document.getElementById('aerotun-modal').classList.remove('hidden');
  7062. }
  7063. function closeAeroTUNModal() {
  7064. document.getElementById('aerotun-modal').classList.add('hidden');
  7065. }
  7066. async function submitSaveAeroTUN(e) {
  7067. e.preventDefault();
  7068. const id = document.getElementById('aerotun-modal-id').value;
  7069. const name = document.getElementById('aerotun-modal-name').value.trim();
  7070. const mode = document.getElementById('aerotun-modal-mode').value;
  7071. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  7072. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  7073. const local = document.getElementById('aerotun-modal-local').value.trim();
  7074. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  7075. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  7076. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  7077. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  7078. const compression = document.getElementById('aerotun-modal-compression').checked;
  7079. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  7080. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  7081. if (mode === 'client' && !endpoint) {
  7082. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  7083. return;
  7084. }
  7085. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  7086. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  7087. showToast('Peer Key Required', 'Save disabled first, exchange public keys, then enable', 'error');
  7088. return;
  7089. }
  7090. if (!psk && !id) {
  7091. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  7092. return;
  7093. }
  7094. try {
  7095. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  7096. method: 'POST',
  7097. headers: { 'Content-Type': 'application/json' },
  7098. body: JSON.stringify({
  7099. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  7100. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  7101. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  7102. id,
  7103. name,
  7104. mode,
  7105. listen_port: port,
  7106. remote_endpoint: endpoint,
  7107. local_address: local,
  7108. peer_address: peer,
  7109. psk,
  7110. mtu,
  7111. compression,
  7112. default_route: defaultRoute,
  7113. comment,
  7114. disabled
  7115. })
  7116. });
  7117. if (res.ok) {
  7118. const saved = await res.json();
  7119. await loadAeroTUN(false);
  7120. if (!id && version === 3) {
  7121. openEditAeroTUNModal(saved.id);
  7122. showToast('Identity Saved', 'Copy the local public key and exchange keys with the peer', 'success');
  7123. } else {
  7124. closeAeroTUNModal();
  7125. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  7126. }
  7127. fetchData(false);
  7128. } else {
  7129. const err = await res.text();
  7130. showToast('Error Saving Tunnel', err, 'error');
  7131. }
  7132. } catch (err) {
  7133. showToast('Network Error', err.message, 'error');
  7134. }
  7135. }
  7136. async function startAeroTUNTunnel(id) {
  7137. try {
  7138. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7139. if (res.ok) {
  7140. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  7141. loadAeroTUN(false);
  7142. fetchData(false);
  7143. } else {
  7144. const err = await res.text();
  7145. showToast('Failed to Start', err, 'error');
  7146. }
  7147. } catch (err) {
  7148. showToast('Error', err.message, 'error');
  7149. }
  7150. }
  7151. async function stopAeroTUNTunnel(id) {
  7152. try {
  7153. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7154. if (res.ok) {
  7155. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7156. loadAeroTUN(false);
  7157. fetchData(false);
  7158. } else {
  7159. const err = await res.text();
  7160. showToast('Failed to Stop', err, 'error');
  7161. }
  7162. } catch (err) {
  7163. showToast('Error', err.message, 'error');
  7164. }
  7165. }
  7166. async function toggleAeroTUNState(id, disabled) {
  7167. try {
  7168. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7169. method: 'POST',
  7170. headers: { 'Content-Type': 'application/json' },
  7171. body: JSON.stringify({ disabled })
  7172. });
  7173. if (res.ok) {
  7174. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7175. loadAeroTUN(false);
  7176. fetchData(false);
  7177. }
  7178. } catch (err) {
  7179. showToast('Error', err.message, 'error');
  7180. }
  7181. }
  7182. async function deleteAeroTUN(id) {
  7183. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7184. try {
  7185. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7186. if (res.ok) {
  7187. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7188. loadAeroTUN(false);
  7189. fetchData(false);
  7190. }
  7191. } catch (err) {
  7192. showToast('Error', err.message, 'error');
  7193. }
  7194. }
  7195. // ======================== PPP Central Hub & Servers ========================
  7196. function switchPPPSubTab(tab) {
  7197. state.pppSubTab = tab;
  7198. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7199. tabs.forEach(t => {
  7200. const panel = document.getElementById(`ppp-subtab-${t}`);
  7201. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7202. if (panel) {
  7203. if (t === tab) panel.classList.remove('hidden');
  7204. else panel.classList.add('hidden');
  7205. }
  7206. if (btn) {
  7207. if (t === tab) {
  7208. 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';
  7209. } else {
  7210. 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';
  7211. }
  7212. }
  7213. });
  7214. const addBtn = document.getElementById('ppp-primary-add-btn');
  7215. if (addBtn) {
  7216. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7217. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7218. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7219. else addBtn.innerHTML = '<span>Save Config</span>';
  7220. }
  7221. if (tab === 'active') loadPPPSessions();
  7222. }
  7223. function openCurrentPPPModal() {
  7224. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7225. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7226. else if (state.pppSubTab === 'active') loadPPPSessions();
  7227. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7228. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7229. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7230. }
  7231. async function loadPPP(populateDropdowns = true) {
  7232. await Promise.all([
  7233. loadPPPSecrets(),
  7234. loadPPPProfiles(),
  7235. loadPPPServers(),
  7236. loadPPPSessions()
  7237. ]);
  7238. }
  7239. async function loadPPPSecrets() {
  7240. try {
  7241. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7242. const data = await res.json();
  7243. state.pppSecrets = Array.isArray(data) ? data : [];
  7244. const b = document.getElementById('ppp-badge-secrets');
  7245. if (b) b.innerText = state.pppSecrets.length;
  7246. const b2 = document.getElementById('secrets-count-badge');
  7247. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7248. renderPPPSecrets();
  7249. } catch (err) {
  7250. console.error('Failed to load PPP secrets:', err);
  7251. }
  7252. }
  7253. function renderPPPSecrets() {
  7254. const tbody = document.getElementById('secrets-table-body');
  7255. const empty = document.getElementById('secrets-empty');
  7256. if (!tbody) return;
  7257. tbody.innerHTML = '';
  7258. const secrets = state.pppSecrets || [];
  7259. if (secrets.length === 0) {
  7260. empty?.classList.remove('hidden');
  7261. return;
  7262. }
  7263. empty?.classList.add('hidden');
  7264. secrets.forEach(s => {
  7265. const tr = document.createElement('tr');
  7266. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7267. tr.innerHTML = `
  7268. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7269. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7270. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7271. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7272. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7273. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7274. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7275. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7276. <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>
  7277. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7278. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7279. </td>
  7280. `;
  7281. tbody.appendChild(tr);
  7282. });
  7283. }
  7284. async function loadPPPProfiles() {
  7285. try {
  7286. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7287. const data = await res.json();
  7288. state.pppProfiles = Array.isArray(data) ? data : [];
  7289. const b = document.getElementById('ppp-badge-profiles');
  7290. if (b) b.innerText = state.pppProfiles.length;
  7291. const b2 = document.getElementById('profiles-count-badge');
  7292. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7293. // Populate profile selects across modals
  7294. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7295. selects.forEach(sid => {
  7296. const el = document.getElementById(sid);
  7297. if (!el) return;
  7298. const cur = el.value;
  7299. el.innerHTML = '';
  7300. state.pppProfiles.forEach(p => {
  7301. const opt = document.createElement('option');
  7302. opt.value = p.name;
  7303. opt.innerText = `${p.name} (${p.remote_address})`;
  7304. if (p.name === cur) opt.selected = true;
  7305. el.appendChild(opt);
  7306. });
  7307. });
  7308. renderPPPProfiles();
  7309. } catch (err) {
  7310. console.error('Failed to load PPP profiles:', err);
  7311. }
  7312. }
  7313. function renderPPPProfiles() {
  7314. const tbody = document.getElementById('profiles-table-body');
  7315. if (!tbody) return;
  7316. tbody.innerHTML = '';
  7317. (state.pppProfiles || []).forEach(p => {
  7318. const isDefault = p.name.startsWith('default');
  7319. const tr = document.createElement('tr');
  7320. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7321. tr.innerHTML = `
  7322. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7323. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7324. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7325. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7326. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7327. <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>
  7328. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7329. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7330. ${!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>`}
  7331. </td>
  7332. `;
  7333. tbody.appendChild(tr);
  7334. });
  7335. }
  7336. async function loadPPPServers() {
  7337. try {
  7338. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7339. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7340. fetch(`${API_BASE}/vpn/servers/pptp`),
  7341. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7342. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7343. ]);
  7344. if (pppoeRes.ok) {
  7345. state.pppoeServer = await pppoeRes.json();
  7346. const s = state.pppoeServer;
  7347. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7348. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7349. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7350. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7351. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7352. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7353. const pill = document.getElementById('pppoe-server-status-pill');
  7354. if (pill) {
  7355. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7356. 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';
  7357. }
  7358. setDotBadge('ppp-badge-pppoe-state', s.running);
  7359. }
  7360. if (pptpRes.ok) {
  7361. state.pptpServer = await pptpRes.json();
  7362. const s = state.pptpServer;
  7363. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7364. document.getElementById('pptp-server-port').value = s.port || 1723;
  7365. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7366. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7367. const pill = document.getElementById('pptp-server-status-pill');
  7368. if (pill) {
  7369. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7370. 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';
  7371. }
  7372. setDotBadge('ppp-badge-pptp-state', s.running);
  7373. }
  7374. if (l2tpRes.ok) {
  7375. state.l2tpServer = await l2tpRes.json();
  7376. const s = state.l2tpServer;
  7377. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7378. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7379. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7380. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7381. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7382. const pill = document.getElementById('l2tp-server-status-pill');
  7383. if (pill) {
  7384. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7385. 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';
  7386. }
  7387. setDotBadge('ppp-badge-l2tp-state', s.running);
  7388. }
  7389. if (ipsecRes.ok) {
  7390. state.ipsecServer = await ipsecRes.json();
  7391. const s = state.ipsecServer;
  7392. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7393. if (modalEn) modalEn.checked = !!s.enabled;
  7394. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7395. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7396. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7397. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7398. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7399. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7400. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7401. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7402. const pill = document.getElementById('modal-ipsec-server-status');
  7403. if (pill) {
  7404. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7405. 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';
  7406. }
  7407. }
  7408. } catch (err) {
  7409. console.error('Failed to load VPN servers:', err);
  7410. }
  7411. }
  7412. async function loadPPPSessions() {
  7413. try {
  7414. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7415. const data = await res.json();
  7416. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7417. const b = document.getElementById('ppp-badge-active');
  7418. if (b) b.innerText = state.pppActiveSessions.length;
  7419. const sideB = document.getElementById('badge-ppp-sessions');
  7420. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7421. renderPPPSessions();
  7422. } catch (err) {
  7423. console.error('Failed to load active PPP sessions:', err);
  7424. }
  7425. }
  7426. function renderPPPSessions() {
  7427. const tbody = document.getElementById('active-ppp-table-body');
  7428. const empty = document.getElementById('active-ppp-empty');
  7429. if (!tbody) return;
  7430. tbody.innerHTML = '';
  7431. const list = state.pppActiveSessions || [];
  7432. if (list.length === 0) {
  7433. empty?.classList.remove('hidden');
  7434. return;
  7435. }
  7436. empty?.classList.add('hidden');
  7437. list.forEach(s => {
  7438. const tr = document.createElement('tr');
  7439. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7440. tr.innerHTML = `
  7441. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7442. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7443. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7444. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7445. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7446. <td class="py-2.5 px-3 text-[11px]">
  7447. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7448. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7449. </td>
  7450. <td class="py-2.5 px-3 text-right font-sans">
  7451. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7452. </td>
  7453. `;
  7454. tbody.appendChild(tr);
  7455. });
  7456. }
  7457. async function disconnectPPPSession(iface) {
  7458. if (!confirm(`Disconnect session ${iface}?`)) return;
  7459. try {
  7460. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7461. if (res.ok) {
  7462. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7463. loadPPPSessions();
  7464. }
  7465. } catch (err) {
  7466. showToast('Error', err.message, 'error');
  7467. }
  7468. }
  7469. // PPP Secret Modal handlers
  7470. function openAddPPPSecretModal() {
  7471. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7472. document.getElementById('secret-modal-id').value = '';
  7473. document.getElementById('secret-modal-name').value = '';
  7474. document.getElementById('secret-modal-password').value = '';
  7475. document.getElementById('secret-modal-service').value = 'any';
  7476. document.getElementById('secret-modal-profile').value = 'default';
  7477. document.getElementById('secret-modal-local').value = '';
  7478. document.getElementById('secret-modal-remote').value = '';
  7479. document.getElementById('secret-modal-comment').value = '';
  7480. document.getElementById('secret-modal-disabled').checked = false;
  7481. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7482. }
  7483. function openEditPPPSecretModal(id) {
  7484. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7485. if (!s) return;
  7486. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7487. document.getElementById('secret-modal-id').value = s.id;
  7488. document.getElementById('secret-modal-name').value = s.name;
  7489. document.getElementById('secret-modal-password').value = s.password;
  7490. document.getElementById('secret-modal-service').value = s.service || 'any';
  7491. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7492. document.getElementById('secret-modal-local').value = s.local_address || '';
  7493. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7494. document.getElementById('secret-modal-comment').value = s.comment || '';
  7495. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7496. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7497. }
  7498. function closePPPSecretModal() {
  7499. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7500. }
  7501. async function submitSavePPPSecret(e) {
  7502. e.preventDefault();
  7503. const id = document.getElementById('secret-modal-id').value;
  7504. const name = document.getElementById('secret-modal-name').value.trim();
  7505. const password = document.getElementById('secret-modal-password').value.trim();
  7506. const service = document.getElementById('secret-modal-service').value;
  7507. const profile = document.getElementById('secret-modal-profile').value;
  7508. const local = document.getElementById('secret-modal-local').value.trim();
  7509. const remote = document.getElementById('secret-modal-remote').value.trim();
  7510. const comment = document.getElementById('secret-modal-comment').value.trim();
  7511. const disabled = document.getElementById('secret-modal-disabled').checked;
  7512. try {
  7513. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7514. method: 'POST',
  7515. headers: { 'Content-Type': 'application/json' },
  7516. body: JSON.stringify({
  7517. id,
  7518. name,
  7519. password,
  7520. service,
  7521. profile,
  7522. local_address: local,
  7523. remote_address: remote,
  7524. comment,
  7525. disabled
  7526. })
  7527. });
  7528. if (res.ok) {
  7529. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7530. closePPPSecretModal();
  7531. loadPPPSecrets();
  7532. } else {
  7533. const err = await res.json();
  7534. showToast('Error', err.message, 'error');
  7535. }
  7536. } catch (err) {
  7537. showToast('Error', err.message, 'error');
  7538. }
  7539. }
  7540. async function togglePPPSecretState(id, disabled) {
  7541. try {
  7542. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7543. method: 'POST',
  7544. headers: { 'Content-Type': 'application/json' },
  7545. body: JSON.stringify({ disabled })
  7546. });
  7547. if (res.ok) {
  7548. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7549. loadPPPSecrets();
  7550. }
  7551. } catch (err) {
  7552. showToast('Error', err.message, 'error');
  7553. }
  7554. }
  7555. async function deletePPPSecret(id) {
  7556. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7557. try {
  7558. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7559. if (res.ok) {
  7560. showToast('Deleted', 'Secret account removed', 'success');
  7561. loadPPPSecrets();
  7562. }
  7563. } catch (err) {
  7564. showToast('Error', err.message, 'error');
  7565. }
  7566. }
  7567. // PPP Profile Modal handlers
  7568. function openAddPPPProfileModal() {
  7569. document.getElementById('profile-modal-name').value = '';
  7570. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7571. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7572. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7573. document.getElementById('profile-modal-encryption').value = 'required';
  7574. document.getElementById('profile-modal-onlyone').checked = true;
  7575. document.getElementById('profile-modal-comment').value = '';
  7576. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7577. }
  7578. function closePPPProfileModal() {
  7579. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7580. }
  7581. async function submitSavePPPProfile(e) {
  7582. e.preventDefault();
  7583. const name = document.getElementById('profile-modal-name').value.trim();
  7584. const local = document.getElementById('profile-modal-local').value.trim();
  7585. const remote = document.getElementById('profile-modal-remote').value.trim();
  7586. const dns = document.getElementById('profile-modal-dns').value.trim();
  7587. const enc = document.getElementById('profile-modal-encryption').value;
  7588. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7589. const comment = document.getElementById('profile-modal-comment').value.trim();
  7590. try {
  7591. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7592. method: 'POST',
  7593. headers: { 'Content-Type': 'application/json' },
  7594. body: JSON.stringify({
  7595. id: name,
  7596. name,
  7597. local_address: local,
  7598. remote_address: remote,
  7599. dns_servers: dns,
  7600. use_encryption: enc,
  7601. only_one: onlyone,
  7602. comment
  7603. })
  7604. });
  7605. if (res.ok) {
  7606. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7607. closePPPProfileModal();
  7608. loadPPPProfiles();
  7609. } else {
  7610. const err = await res.json();
  7611. showToast('Error', err.message, 'error');
  7612. }
  7613. } catch (err) {
  7614. showToast('Error', err.message, 'error');
  7615. }
  7616. }
  7617. async function deletePPPProfile(name) {
  7618. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7619. try {
  7620. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7621. if (res.ok) {
  7622. showToast('Deleted', 'Profile removed', 'success');
  7623. loadPPPProfiles();
  7624. } else {
  7625. const err = await res.json();
  7626. showToast('Error', err.message, 'error');
  7627. }
  7628. } catch (err) {
  7629. showToast('Error', err.message, 'error');
  7630. }
  7631. }
  7632. // Server Config submissions
  7633. async function savePPPoEServerConfig(e) {
  7634. e.preventDefault();
  7635. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7636. const name = document.getElementById('pppoe-server-name').value.trim();
  7637. const iface = document.getElementById('pppoe-server-iface').value;
  7638. const profile = document.getElementById('pppoe-server-profile').value;
  7639. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7640. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7641. try {
  7642. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7643. method: 'POST',
  7644. headers: { 'Content-Type': 'application/json' },
  7645. body: JSON.stringify({
  7646. enabled,
  7647. service_name: name,
  7648. interface: iface,
  7649. default_profile: profile,
  7650. max_mtu: mtu,
  7651. max_mru: mtu,
  7652. one_session_per_host: onesession
  7653. })
  7654. });
  7655. if (res.ok) {
  7656. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7657. loadPPPServers();
  7658. fetchData(false);
  7659. } else {
  7660. const err = await res.json();
  7661. showToast('Error', err.message, 'error');
  7662. }
  7663. } catch (err) {
  7664. showToast('Error', err.message, 'error');
  7665. }
  7666. }
  7667. async function savePPTPServerConfig(e) {
  7668. e.preventDefault();
  7669. const enabled = document.getElementById('pptp-server-enabled').checked;
  7670. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7671. const profile = document.getElementById('pptp-server-profile').value;
  7672. const mppe = document.getElementById('pptp-server-mppe').checked;
  7673. try {
  7674. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7675. method: 'POST',
  7676. headers: { 'Content-Type': 'application/json' },
  7677. body: JSON.stringify({
  7678. enabled,
  7679. port,
  7680. default_profile: profile,
  7681. require_mppe: mppe
  7682. })
  7683. });
  7684. if (res.ok) {
  7685. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7686. loadPPPServers();
  7687. fetchData(false);
  7688. } else {
  7689. const err = await res.json();
  7690. showToast('Error', err.message, 'error');
  7691. }
  7692. } catch (err) {
  7693. showToast('Error', err.message, 'error');
  7694. }
  7695. }
  7696. async function saveL2TPServerConfig(e) {
  7697. e.preventDefault();
  7698. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7699. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7700. const profile = document.getElementById('l2tp-server-profile').value;
  7701. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7702. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7703. try {
  7704. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7705. method: 'POST',
  7706. headers: { 'Content-Type': 'application/json' },
  7707. body: JSON.stringify({
  7708. enabled,
  7709. port,
  7710. default_profile: profile,
  7711. use_ipsec: useipsec,
  7712. ipsec_secret: psk
  7713. })
  7714. });
  7715. if (res.ok) {
  7716. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7717. loadPPPServers();
  7718. fetchData(false);
  7719. } else {
  7720. const err = await res.json();
  7721. showToast('Error', err.message, 'error');
  7722. }
  7723. } catch (err) {
  7724. showToast('Error', err.message, 'error');
  7725. }
  7726. }
  7727. // IPSec Server Modal
  7728. function openIPSecServerModal() {
  7729. loadPPPServers();
  7730. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7731. }
  7732. function closeIPSecServerModal() {
  7733. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7734. }
  7735. async function submitSaveIPSecServer(e) {
  7736. e.preventDefault();
  7737. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7738. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7739. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7740. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7741. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7742. try {
  7743. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7744. method: 'POST',
  7745. headers: { 'Content-Type': 'application/json' },
  7746. body: JSON.stringify({
  7747. enabled,
  7748. preshared_key: psk,
  7749. pool_address: pool,
  7750. dns_servers: dns,
  7751. local_subnet: subnet
  7752. })
  7753. });
  7754. if (res.ok) {
  7755. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7756. closeIPSecServerModal();
  7757. loadPPPServers();
  7758. fetchData(false);
  7759. } else {
  7760. const err = await res.json();
  7761. showToast('Error', err.message, 'error');
  7762. }
  7763. } catch (err) {
  7764. showToast('Error', err.message, 'error');
  7765. }
  7766. }
  7767. // WireGuard Client Config Viewer
  7768. let currentWGClientConf = '';
  7769. async function openWGClientConfModal(iface, clientIP) {
  7770. try {
  7771. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7772. method: 'POST',
  7773. headers: { 'Content-Type': 'application/json' },
  7774. body: JSON.stringify({
  7775. interface: iface,
  7776. address: clientIP || '10.10.0.2/32',
  7777. dns: '1.1.1.1, 8.8.8.8'
  7778. })
  7779. });
  7780. if (res.ok) {
  7781. const data = await res.json();
  7782. currentWGClientConf = data.config;
  7783. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7784. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7785. } else {
  7786. const err = await res.json();
  7787. showToast('Error', err.message, 'error');
  7788. }
  7789. } catch (err) {
  7790. showToast('Error', err.message, 'error');
  7791. }
  7792. }
  7793. function closeWGClientConfModal() {
  7794. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7795. }
  7796. function copyWGClientConf() {
  7797. if (!currentWGClientConf) return;
  7798. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7799. }
  7800. function downloadWGClientConf() {
  7801. if (!currentWGClientConf) return;
  7802. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7803. const a = document.createElement('a');
  7804. a.href = URL.createObjectURL(blob);
  7805. a.download = 'wireguard-client.conf';
  7806. document.body.appendChild(a);
  7807. a.click();
  7808. document.body.removeChild(a);
  7809. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7810. }
  7811. // =========================================================================
  7812. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7813. // =========================================================================
  7814. state.activeDynSubTab = 'bgp-peers';
  7815. state.activeBgpSubTab = 'bgp-peers';
  7816. state.activeOspfTab = 'instances';
  7817. state.bgpInstance = null;
  7818. state.bgpPeers = [];
  7819. state.bgpNets = [];
  7820. state.bgpRoutes = [];
  7821. state.ospfInstance = null;
  7822. state.ospfInstances = [];
  7823. state.ospfAreas = [];
  7824. state.ospfAreaRanges = [];
  7825. state.ospfTemplates = [];
  7826. state.ospfLiveInterfaces = [];
  7827. state.ospfStaticNbrs = [];
  7828. state.ospfNeighbors = [];
  7829. state.ospfLSA = [];
  7830. state.ospfRoutes = [];
  7831. state.selectedOspfRow = {
  7832. instances: null,
  7833. areas: null,
  7834. 'area-ranges': null,
  7835. templates: null,
  7836. interfaces: null,
  7837. 'static-nbrs': null,
  7838. neighbors: null,
  7839. lsa: null,
  7840. };
  7841. state.ospfSort = {
  7842. instances: { col: 'name', asc: true },
  7843. areas: { col: 'name', asc: true },
  7844. ranges: { col: 'area', asc: true },
  7845. templates: { col: 'interfaces', asc: true },
  7846. live_ifaces: { col: 'interface', asc: true },
  7847. snbrs: { col: 'address', asc: true },
  7848. neighbors: { col: 'address', asc: true },
  7849. lsa: { col: 'instance', asc: true },
  7850. };
  7851. function switchBgpSubTab(subTab) {
  7852. state.activeBgpSubTab = subTab;
  7853. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7854. tabs.forEach(t => {
  7855. const el = document.getElementById(`dyn-subtab-${t}`);
  7856. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7857. if (el) el.classList.toggle('hidden', t !== subTab);
  7858. if (btn) {
  7859. if (t === subTab) {
  7860. 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';
  7861. } else {
  7862. 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';
  7863. }
  7864. }
  7865. });
  7866. }
  7867. function switchOspfTab(tabName) {
  7868. state.activeOspfTab = tabName;
  7869. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7870. tabs.forEach(t => {
  7871. const pane = document.getElementById(`ospf-pane-${t}`);
  7872. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7873. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7874. if (btn) {
  7875. if (t === tabName) {
  7876. 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';
  7877. } else {
  7878. 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';
  7879. }
  7880. }
  7881. });
  7882. }
  7883. function switchOspfSubTab(tab) {
  7884. // Legacy alias
  7885. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7886. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7887. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7888. else switchOspfTab('instances');
  7889. }
  7890. function switchDynSubTab(subTab) {
  7891. if (subTab.startsWith('bgp')) {
  7892. if (state.activeTab !== 'bgp') navigate('bgp');
  7893. switchBgpSubTab(subTab);
  7894. } else if (subTab.startsWith('ospf')) {
  7895. if (state.activeTab !== 'ospf') navigate('ospf');
  7896. switchOspfTab('instances');
  7897. }
  7898. }
  7899. async function loadDynamicRouting(showToastMsg = false) {
  7900. try {
  7901. const fetchSafeJson = async (url) => {
  7902. try {
  7903. const r = await fetch(url);
  7904. return r.ok ? await r.json() : null;
  7905. } catch (e) {
  7906. return null;
  7907. }
  7908. };
  7909. const [
  7910. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7911. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7912. selectRules, commLists, asLists
  7913. ] = await Promise.all([
  7914. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7915. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7916. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7917. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7918. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7919. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7920. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7921. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7922. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7923. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7924. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7925. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7926. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7927. fetchSafeJson(`${API_BASE}/routing/filters`),
  7928. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7929. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7930. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7931. ]);
  7932. if (sum) state.dynSummary = sum;
  7933. if (bgpInst) state.bgpInstance = bgpInst;
  7934. if (bgpPeers) state.bgpPeers = bgpPeers;
  7935. if (bgpNets) state.bgpNets = bgpNets;
  7936. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7937. if (ospfInsts) state.ospfInstances = ospfInsts;
  7938. if (ospfAreas) state.ospfAreas = ospfAreas;
  7939. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7940. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7941. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7942. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7943. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7944. if (ospfLsa) state.ospfLSA = ospfLsa;
  7945. if (filters) state.routingFilters = filters;
  7946. if (selectRules) state.routingSelectRules = selectRules;
  7947. if (commLists) state.routingCommunityLists = commLists;
  7948. if (asLists) state.routingASLists = asLists;
  7949. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7950. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7951. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7952. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7953. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7954. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7955. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7956. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7957. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7958. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7959. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7960. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7961. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7962. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7963. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7964. } catch (err) {
  7965. console.error('Failed to load dynamic routing:', err);
  7966. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7967. }
  7968. }
  7969. async function loadOspfAll() {
  7970. await loadDynamicRouting(true);
  7971. }
  7972. function renderBgpStatusPill() {
  7973. const pills = document.querySelectorAll('.bgp-live-status-pill');
  7974. pills.forEach(pill => {
  7975. const inst = state.bgpInstance;
  7976. if (!inst || !inst.enabled) {
  7977. 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';
  7978. pill.innerText = 'BGP DISABLED';
  7979. } else if (inst.running) {
  7980. 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';
  7981. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7982. } else {
  7983. 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';
  7984. pill.innerText = 'BGP STARTING...';
  7985. }
  7986. });
  7987. }
  7988. function renderBgpPeers() {
  7989. const tbody = document.getElementById('bgp-peers-table-body');
  7990. if (!tbody) return;
  7991. const empty = document.getElementById('bgp-peers-empty');
  7992. const countBadge = document.getElementById('bgp-peers-count-badge');
  7993. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7994. const peers = state.bgpPeers || [];
  7995. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7996. if (navBadge) navBadge.innerText = peers.length;
  7997. if (peers.length === 0) {
  7998. tbody.innerHTML = '';
  7999. if (empty) empty.classList.remove('hidden');
  8000. return;
  8001. }
  8002. if (empty) empty.classList.add('hidden');
  8003. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  8004. if (tbody.dataset.sig === sig) return;
  8005. tbody.dataset.sig = sig;
  8006. tbody.innerHTML = peers.map(p => {
  8007. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  8008. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  8009. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  8010. let stateBadge = '';
  8011. if (p.disabled) {
  8012. 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>';
  8013. } else if (p.state === 'Established') {
  8014. 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>';
  8015. } else if (p.state === 'Connect' || p.state === 'Active') {
  8016. 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>`;
  8017. } else {
  8018. 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>`;
  8019. }
  8020. return `
  8021. <tr class="hover:bg-slate-800/40 transition">
  8022. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  8023. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  8024. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  8025. <td class="py-2.5 px-3">
  8026. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  8027. ${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>`}
  8028. </td>
  8029. <td class="py-2.5 px-3">${stateBadge}</td>
  8030. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  8031. <td class="py-2.5 px-3 text-slate-300">
  8032. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  8033. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  8034. </td>
  8035. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  8036. ${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> ` : ''}
  8037. ${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>` : ''}
  8038. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  8039. </td>
  8040. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  8041. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  8042. <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'}">
  8043. ${p.disabled ? 'Enable' : 'Disable'}
  8044. </button>
  8045. <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">
  8046. Edit
  8047. </button>
  8048. <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">
  8049. Delete
  8050. </button>
  8051. </td>
  8052. </tr>
  8053. `;
  8054. }).join('');
  8055. }
  8056. function renderBgpNetworks() {
  8057. const tbody = document.getElementById('bgp-nets-table-body');
  8058. if (!tbody) return;
  8059. const empty = document.getElementById('bgp-nets-empty');
  8060. const countBadge = document.getElementById('bgp-nets-count-badge');
  8061. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  8062. const nets = state.bgpNets || [];
  8063. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  8064. if (navBadge) navBadge.innerText = nets.length;
  8065. if (nets.length === 0) {
  8066. tbody.innerHTML = '';
  8067. if (empty) empty.classList.remove('hidden');
  8068. return;
  8069. }
  8070. if (empty) empty.classList.add('hidden');
  8071. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  8072. if (tbody.dataset.sig === sig) return;
  8073. tbody.dataset.sig = sig;
  8074. tbody.innerHTML = nets.map(n => `
  8075. <tr class="hover:bg-slate-800/40 transition">
  8076. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  8077. <td class="py-2.5 px-3">
  8078. ${n.disabled
  8079. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  8080. : '<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>'}
  8081. </td>
  8082. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  8083. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  8084. <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">
  8085. Delete
  8086. </button>
  8087. </td>
  8088. </tr>
  8089. `).join('');
  8090. }
  8091. function renderBgpRoutes() {
  8092. const tbody = document.getElementById('bgp-routes-table-body');
  8093. if (!tbody) return;
  8094. const empty = document.getElementById('bgp-routes-empty');
  8095. const countBadge = document.getElementById('bgp-routes-count-badge');
  8096. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  8097. const routes = state.bgpRoutes || [];
  8098. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  8099. if (navBadge) navBadge.innerText = routes.length;
  8100. if (routes.length === 0) {
  8101. tbody.innerHTML = '';
  8102. if (empty) empty.classList.remove('hidden');
  8103. return;
  8104. }
  8105. if (empty) empty.classList.add('hidden');
  8106. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  8107. if (tbody.dataset.sig === sig) return;
  8108. tbody.dataset.sig = sig;
  8109. tbody.innerHTML = routes.map(r => `
  8110. <tr class="hover:bg-slate-800/40 transition">
  8111. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8112. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8113. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8114. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8115. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8116. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8117. </tr>
  8118. `).join('');
  8119. }
  8120. // =========================================================================
  8121. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  8122. // =========================================================================
  8123. function sortOspfTable(tab, col) {
  8124. if (!state.ospfSort) state.ospfSort = {};
  8125. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8126. if (state.ospfSort[tab].col === col) {
  8127. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8128. } else {
  8129. state.ospfSort[tab].col = col;
  8130. state.ospfSort[tab].asc = true;
  8131. }
  8132. const asc = state.ospfSort[tab].asc;
  8133. let list = [];
  8134. if (tab === 'instances') list = state.ospfInstances || [];
  8135. else if (tab === 'areas') list = state.ospfAreas || [];
  8136. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8137. else if (tab === 'templates') list = state.ospfTemplates || [];
  8138. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8139. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8140. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8141. else if (tab === 'lsa') list = state.ospfLSA || [];
  8142. list.sort((a, b) => {
  8143. let valA = a[col] ?? '';
  8144. let valB = b[col] ?? '';
  8145. if (typeof valA === 'number' && typeof valB === 'number') {
  8146. return asc ? valA - valB : valB - valA;
  8147. }
  8148. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8149. });
  8150. if (tab === 'instances') renderOspfInstances();
  8151. else if (tab === 'areas') renderOspfAreas();
  8152. else if (tab === 'ranges') renderOspfAreaRanges();
  8153. else if (tab === 'templates') renderOspfTemplates();
  8154. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8155. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8156. else if (tab === 'neighbors') renderOspfNeighbors();
  8157. else if (tab === 'lsa') renderOspfLSA();
  8158. }
  8159. function selectOspfRow(tab, id) {
  8160. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8161. state.selectedOspfRow[tab] = id;
  8162. if (tab === 'instances') {
  8163. renderOspfInstances();
  8164. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8165. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8166. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8167. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8168. if (btnEn) btnEn.disabled = false;
  8169. if (btnDis) btnDis.disabled = false;
  8170. if (btnRem) btnRem.disabled = false;
  8171. if (btnCom) btnCom.disabled = false;
  8172. } else if (tab === 'areas') {
  8173. renderOspfAreas();
  8174. const btnEn = document.getElementById('btn-ospf-area-enable');
  8175. const btnDis = document.getElementById('btn-ospf-area-disable');
  8176. const btnRem = document.getElementById('btn-ospf-area-remove');
  8177. const btnCom = document.getElementById('btn-ospf-area-comment');
  8178. if (btnEn) btnEn.disabled = false;
  8179. if (btnDis) btnDis.disabled = false;
  8180. if (btnRem) btnRem.disabled = false;
  8181. if (btnCom) btnCom.disabled = false;
  8182. } else if (tab === 'ranges') {
  8183. renderOspfAreaRanges();
  8184. const btnEn = document.getElementById('btn-ospf-range-enable');
  8185. const btnDis = document.getElementById('btn-ospf-range-disable');
  8186. const btnRem = document.getElementById('btn-ospf-range-remove');
  8187. const btnCom = document.getElementById('btn-ospf-range-comment');
  8188. if (btnEn) btnEn.disabled = false;
  8189. if (btnDis) btnDis.disabled = false;
  8190. if (btnRem) btnRem.disabled = false;
  8191. if (btnCom) btnCom.disabled = false;
  8192. } else if (tab === 'templates') {
  8193. renderOspfTemplates();
  8194. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8195. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8196. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8197. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8198. if (btnEn) btnEn.disabled = false;
  8199. if (btnDis) btnDis.disabled = false;
  8200. if (btnRem) btnRem.disabled = false;
  8201. if (btnCom) btnCom.disabled = false;
  8202. } else if (tab === 'snbrs') {
  8203. renderOspfStaticNbrs();
  8204. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8205. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8206. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8207. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8208. if (btnEn) btnEn.disabled = false;
  8209. if (btnDis) btnDis.disabled = false;
  8210. if (btnRem) btnRem.disabled = false;
  8211. if (btnCom) btnCom.disabled = false;
  8212. }
  8213. }
  8214. // TAB 1: INSTANCES
  8215. function renderOspfInstances() {
  8216. const tbody = document.getElementById('ospf-instances-table-body');
  8217. if (!tbody) return;
  8218. const countEl = document.getElementById('ospf-instances-footer-count');
  8219. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8220. let list = state.ospfInstances || [];
  8221. if (filter) {
  8222. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8223. }
  8224. if (countEl) countEl.innerText = list.length;
  8225. const selId = state.selectedOspfRow?.instances;
  8226. tbody.innerHTML = list.map((inst, idx) => {
  8227. const isSel = inst.id === selId;
  8228. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8229. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8230. return `
  8231. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8232. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8233. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8234. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8235. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8236. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8237. </td>
  8238. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8239. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8240. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8241. </tr>
  8242. `;
  8243. }).join('');
  8244. }
  8245. // TAB 2: AREAS
  8246. function renderOspfAreas() {
  8247. const tbody = document.getElementById('ospf-areas-table-body');
  8248. if (!tbody) return;
  8249. const countEl = document.getElementById('ospf-areas-footer-count');
  8250. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8251. let list = state.ospfAreas || [];
  8252. if (filter) {
  8253. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8254. }
  8255. if (countEl) countEl.innerText = list.length;
  8256. const selId = state.selectedOspfRow?.areas;
  8257. tbody.innerHTML = list.map((a, idx) => {
  8258. const isSel = a.id === selId;
  8259. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8260. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8261. return `
  8262. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8263. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8264. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8265. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8266. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8267. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8268. </td>
  8269. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8270. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8271. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8272. </tr>
  8273. `;
  8274. }).join('');
  8275. }
  8276. // TAB 3: AREA RANGES
  8277. function renderOspfAreaRanges() {
  8278. const tbody = document.getElementById('ospf-ranges-table-body');
  8279. if (!tbody) return;
  8280. const countEl = document.getElementById('ospf-ranges-footer-count');
  8281. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8282. let list = state.ospfAreaRanges || [];
  8283. if (filter) {
  8284. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8285. }
  8286. if (countEl) countEl.innerText = list.length;
  8287. const selId = state.selectedOspfRow?.['area-ranges'];
  8288. tbody.innerHTML = list.map((r, idx) => {
  8289. const isSel = r.id === selId;
  8290. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8291. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8292. return `
  8293. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8294. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8295. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8296. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8297. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8298. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8299. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8300. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8301. </tr>
  8302. `;
  8303. }).join('');
  8304. }
  8305. // TAB 4: INTERFACE TEMPLATES
  8306. function renderOspfTemplates() {
  8307. const tbody = document.getElementById('ospf-templates-table-body');
  8308. if (!tbody) return;
  8309. const countEl = document.getElementById('ospf-templates-footer-count');
  8310. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8311. let list = state.ospfTemplates || [];
  8312. if (filter) {
  8313. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8314. }
  8315. if (countEl) countEl.innerText = list.length;
  8316. const selId = state.selectedOspfRow?.templates;
  8317. tbody.innerHTML = list.map((t, idx) => {
  8318. const isSel = t.id === selId;
  8319. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8320. const ifaces = t.interfaces || t.interface || 'all';
  8321. const nets = t.networks || t.network || '';
  8322. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8323. return `
  8324. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8325. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8326. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8327. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8328. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8329. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8330. </td>
  8331. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8332. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8333. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8334. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8335. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8336. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8337. </tr>
  8338. `;
  8339. }).join('');
  8340. }
  8341. // TAB 5: LIVE INTERFACES
  8342. function renderOspfLiveInterfaces() {
  8343. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8344. if (!tbody) return;
  8345. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8346. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8347. let list = state.ospfLiveInterfaces || [];
  8348. if (filter) {
  8349. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8350. }
  8351. if (countEl) countEl.innerText = list.length;
  8352. tbody.innerHTML = list.map(i => `
  8353. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8354. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8355. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8356. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8357. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8358. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8359. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8360. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8361. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8362. </tr>
  8363. `).join('');
  8364. }
  8365. // TAB 6: STATIC NEIGHBORS
  8366. function renderOspfStaticNbrs() {
  8367. const tbody = document.getElementById('ospf-snbrs-table-body');
  8368. if (!tbody) return;
  8369. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8370. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8371. let list = state.ospfStaticNbrs || [];
  8372. if (filter) {
  8373. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8374. }
  8375. if (countEl) countEl.innerText = list.length;
  8376. const selId = state.selectedOspfRow?.['static-nbrs'];
  8377. tbody.innerHTML = list.map((n, idx) => {
  8378. const isSel = n.id === selId;
  8379. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8380. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8381. return `
  8382. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8383. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8384. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8385. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8386. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8387. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8388. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8389. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8390. </tr>
  8391. `;
  8392. }).join('');
  8393. }
  8394. // TAB 7: LIVE NEIGHBORS
  8395. function renderOspfNeighbors() {
  8396. const tbody = document.getElementById('ospf-neighbors-table-body');
  8397. if (!tbody) return;
  8398. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8399. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8400. let list = state.ospfNeighbors || [];
  8401. if (filter) {
  8402. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8403. }
  8404. if (countEl) countEl.innerText = list.length;
  8405. tbody.innerHTML = list.map(n => `
  8406. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8407. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8408. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8409. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8410. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8411. </td>
  8412. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8413. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8414. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8415. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8416. </tr>
  8417. `).join('');
  8418. }
  8419. // TAB 8: LINK-STATE DATABASE (LSA)
  8420. function renderOspfLSA() {
  8421. const tbody = document.getElementById('ospf-lsa-table-body');
  8422. if (!tbody) return;
  8423. const countEl = document.getElementById('ospf-lsa-footer-count');
  8424. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8425. let list = state.ospfLSA || [];
  8426. if (filter) {
  8427. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8428. }
  8429. if (countEl) countEl.innerText = list.length;
  8430. tbody.innerHTML = list.map(l => `
  8431. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8432. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8433. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8434. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8435. </td>
  8436. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8437. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8438. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8439. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8440. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8441. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8442. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8443. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8444. </tr>
  8445. `).join('');
  8446. }
  8447. function renderOspfStatusPill() {
  8448. // Maintained for backward compatibility
  8449. const pill = document.getElementById('ospf-live-status-pill');
  8450. if (!pill) return;
  8451. 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';
  8452. pill.innerText = 'OSPF ACTIVE';
  8453. }
  8454. function renderOspfInterfaces() {
  8455. renderOspfTemplates();
  8456. }
  8457. function renderOspfRoutes() {
  8458. // Routes retained in background
  8459. }
  8460. // BGP Modals & Actions
  8461. function openBgpInstanceModal() {
  8462. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8463. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8464. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8465. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8466. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8467. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8468. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8469. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8470. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8471. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8472. }
  8473. function closeBgpInstanceModal() {
  8474. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8475. }
  8476. async function submitBgpInstance(e) {
  8477. e.preventDefault();
  8478. const payload = {
  8479. enabled: document.getElementById('modal-bgp-enabled').checked,
  8480. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8481. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8482. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8483. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8484. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8485. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8486. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8487. };
  8488. try {
  8489. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8490. method: 'POST',
  8491. headers: { 'Content-Type': 'application/json' },
  8492. body: JSON.stringify(payload)
  8493. });
  8494. if (res.ok) {
  8495. closeBgpInstanceModal();
  8496. showToast('Success', 'BGP instance configuration updated', 'success');
  8497. loadDynamicRouting();
  8498. } else {
  8499. const err = await res.json();
  8500. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8501. }
  8502. } catch (err) {
  8503. showToast('Error', err.message, 'error');
  8504. }
  8505. }
  8506. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  8507. function switchBgpPeerModalTab(tab) {
  8508. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8509. tabs.forEach(t => {
  8510. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8511. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8512. if (t === tab) {
  8513. if (pane) pane.classList.remove('hidden');
  8514. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8515. } else {
  8516. if (pane) pane.classList.add('hidden');
  8517. 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';
  8518. }
  8519. });
  8520. }
  8521. function addOutputNetworkRow(val = '') {
  8522. const container = document.getElementById('modal-bgp-output-networks-container');
  8523. if (!container) return;
  8524. const row = document.createElement('div');
  8525. row.className = 'flex items-center gap-2 output-net-row';
  8526. row.innerHTML = `
  8527. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" 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">
  8528. <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>
  8529. `;
  8530. container.appendChild(row);
  8531. }
  8532. function parseBgpTime(val) {
  8533. if (!val) return 0;
  8534. val = String(val).trim();
  8535. if (val.includes(':')) {
  8536. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8537. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8538. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8539. }
  8540. return parseInt(val, 10) || 0;
  8541. }
  8542. function formatBgpTime(secs) {
  8543. if (!secs || secs <= 0) return '00:00:00';
  8544. const h = Math.floor(secs / 3600);
  8545. const m = Math.floor((secs % 3600) / 60);
  8546. const s = secs % 60;
  8547. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8548. }
  8549. function populateBgpRoutingTables() {
  8550. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8551. if (!sel) return;
  8552. const cur = sel.value || 'main';
  8553. sel.innerHTML = '<option value="main">main</option>';
  8554. (state.routingTables || []).forEach(t => {
  8555. if (t.name !== 'main') {
  8556. const opt = document.createElement('option');
  8557. opt.value = t.name;
  8558. opt.innerText = t.name;
  8559. sel.appendChild(opt);
  8560. }
  8561. });
  8562. sel.value = cur;
  8563. }
  8564. function openAddBgpPeerModal() {
  8565. document.getElementById('bgp-peer-form').reset();
  8566. document.getElementById('modal-bgp-peer-id').value = '';
  8567. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8568. // General Tab
  8569. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8570. document.getElementById('modal-bgp-peer-comment').value = '';
  8571. document.getElementById('modal-bgp-peer-name').value = '';
  8572. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8573. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8574. document.getElementById('modal-bgp-peer-local-as').value = '';
  8575. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8576. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8577. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8578. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8579. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8580. document.getElementById('modal-bgp-peer-router-id').value = '';
  8581. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8582. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8583. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8584. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8585. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8586. document.getElementById('modal-bgp-peer-local-port').value = '';
  8587. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8588. document.getElementById('modal-bgp-peer-password').value = '';
  8589. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8590. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8591. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8592. document.getElementById('modal-bgp-peer-connect').checked = true;
  8593. document.getElementById('modal-bgp-peer-listen').checked = true;
  8594. // Extra Tab
  8595. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8596. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8597. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8598. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8599. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8600. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8601. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8602. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8603. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8604. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8605. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8606. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8607. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8608. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8609. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8610. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8611. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8612. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8613. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8614. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8615. // Attributes Tab
  8616. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8617. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8618. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8619. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8620. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8621. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8622. // Filter Tab
  8623. populateFilterChainsDatalist();
  8624. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8625. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8626. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8627. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8628. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8629. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8630. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8631. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8632. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8633. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8634. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8635. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8636. populateBgpRoutingTables();
  8637. const container = document.getElementById('modal-bgp-output-networks-container');
  8638. if (container) {
  8639. container.innerHTML = '';
  8640. addOutputNetworkRow('');
  8641. }
  8642. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8643. if (removeBtn) removeBtn.classList.add('hidden');
  8644. switchBgpPeerModalTab('general');
  8645. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8646. }
  8647. function populateFilterChainsDatalist() {
  8648. const dl = document.getElementById('filter-chains-list');
  8649. if (!dl) return;
  8650. const chains = new Set();
  8651. (state.routingFilters || []).forEach(f => {
  8652. if (f.chain) chains.add(f.chain);
  8653. });
  8654. if (chains.size === 0) {
  8655. chains.add('awmn');
  8656. chains.add('bgp-in');
  8657. chains.add('bgp-out');
  8658. }
  8659. dl.innerHTML = '';
  8660. chains.forEach(c => {
  8661. const opt = document.createElement('option');
  8662. opt.value = c;
  8663. dl.appendChild(opt);
  8664. });
  8665. }
  8666. function openEditBgpPeerModal(id) {
  8667. const p = (state.bgpPeers || []).find(item => item.id === id);
  8668. if (!p) return;
  8669. populateBgpRoutingTables();
  8670. populateFilterChainsDatalist();
  8671. document.getElementById('modal-bgp-peer-id').value = p.id;
  8672. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8673. // General Tab
  8674. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8675. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8676. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8677. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8678. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8679. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8680. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8681. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8682. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8683. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8684. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8685. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8686. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8687. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8688. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8689. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8690. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8691. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8692. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8693. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8694. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8695. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8696. // Extra Tab
  8697. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8698. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8699. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8700. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8701. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8702. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8703. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8704. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8705. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8706. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8707. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8708. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8709. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8710. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8711. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8712. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8713. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8714. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8715. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8716. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8717. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8718. // Attributes Tab
  8719. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8720. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8721. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8722. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8723. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8724. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8725. // Filter Tab
  8726. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8727. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8728. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8729. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8730. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8731. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8732. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8733. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8734. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8735. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8736. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8737. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8738. // Output Networks
  8739. const container = document.getElementById('modal-bgp-output-networks-container');
  8740. if (container) {
  8741. container.innerHTML = '';
  8742. if (p.output_networks && p.output_networks.length > 0) {
  8743. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8744. } else {
  8745. addOutputNetworkRow('');
  8746. }
  8747. }
  8748. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8749. if (removeBtn) removeBtn.classList.remove('hidden');
  8750. switchBgpPeerModalTab('general');
  8751. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8752. }
  8753. function copyCurrentBgpPeer() {
  8754. document.getElementById('modal-bgp-peer-id').value = '';
  8755. const nameEl = document.getElementById('modal-bgp-peer-name');
  8756. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8757. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8758. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8759. if (removeBtn) removeBtn.classList.add('hidden');
  8760. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8761. }
  8762. function removeCurrentBgpPeer() {
  8763. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8764. if (!id) return;
  8765. deleteBgpPeer(id);
  8766. closeBgpPeerModal();
  8767. }
  8768. function closeBgpPeerModal() {
  8769. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8770. }
  8771. function getBgpPeerFormData() {
  8772. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8773. const outputNetworks = [];
  8774. netInputs.forEach(inp => {
  8775. const v = inp.value.trim();
  8776. if (v) outputNetworks.push(v);
  8777. });
  8778. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8779. return {
  8780. id: document.getElementById('modal-bgp-peer-id').value,
  8781. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8782. enabled: enabled,
  8783. disabled: !enabled,
  8784. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8785. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8786. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8787. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8788. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8789. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8790. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8791. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8792. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8793. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8794. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8795. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8796. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8797. password: document.getElementById('modal-bgp-peer-password').value,
  8798. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8799. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8800. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8801. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8802. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8803. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8804. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8805. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8806. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8807. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8808. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8809. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8810. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8811. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8812. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8813. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8814. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8815. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8816. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8817. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8818. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8819. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8820. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8821. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8822. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8823. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8824. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8825. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8826. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8827. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8828. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8829. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8830. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8831. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8832. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8833. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8834. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8835. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8836. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8837. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8838. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8839. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8840. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8841. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8842. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8843. output_networks: outputNetworks
  8844. };
  8845. }
  8846. async function submitBgpPeer(e) {
  8847. if (e) e.preventDefault();
  8848. const payload = getBgpPeerFormData();
  8849. try {
  8850. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8851. method: 'POST',
  8852. headers: { 'Content-Type': 'application/json' },
  8853. body: JSON.stringify(payload)
  8854. });
  8855. if (res.ok) {
  8856. closeBgpPeerModal();
  8857. showToast('Success', 'BGP Connection saved', 'success');
  8858. loadDynamicRouting();
  8859. } else {
  8860. const err = await res.json();
  8861. showToast('Error', err.error || 'Failed to save peer', 'error');
  8862. }
  8863. } catch (err) {
  8864. showToast('Error', err.message, 'error');
  8865. }
  8866. }
  8867. async function applyBgpPeerModal(e) {
  8868. if (e) e.preventDefault();
  8869. const payload = getBgpPeerFormData();
  8870. try {
  8871. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8872. method: 'POST',
  8873. headers: { 'Content-Type': 'application/json' },
  8874. body: JSON.stringify(payload)
  8875. });
  8876. if (res.ok) {
  8877. const data = await res.json();
  8878. if (data.peer && data.peer.id) {
  8879. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8880. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8881. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8882. }
  8883. showToast('Applied', 'BGP Connection applied', 'success');
  8884. loadDynamicRouting();
  8885. } else {
  8886. const err = await res.json();
  8887. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8888. }
  8889. } catch (err) {
  8890. showToast('Error', err.message, 'error');
  8891. }
  8892. }
  8893. async function deleteBgpPeer(id) {
  8894. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8895. try {
  8896. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8897. if (res.ok) {
  8898. showToast('Deleted', 'BGP peer removed', 'success');
  8899. loadDynamicRouting();
  8900. }
  8901. } catch (err) {
  8902. showToast('Error', err.message, 'error');
  8903. }
  8904. }
  8905. async function toggleBgpPeerState(id, disabled) {
  8906. try {
  8907. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8908. method: 'POST',
  8909. headers: { 'Content-Type': 'application/json' },
  8910. body: JSON.stringify({ disabled })
  8911. });
  8912. if (res.ok) {
  8913. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8914. loadDynamicRouting();
  8915. }
  8916. } catch (err) {
  8917. showToast('Error', err.message, 'error');
  8918. }
  8919. }
  8920. function openAddBgpNetworkModal() {
  8921. document.getElementById('bgp-network-form').reset();
  8922. document.getElementById('modal-bgp-net-id').value = '';
  8923. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8924. }
  8925. function closeBgpNetworkModal() {
  8926. document.getElementById('bgp-network-modal').classList.add('hidden');
  8927. }
  8928. async function submitBgpNetwork(e) {
  8929. e.preventDefault();
  8930. const payload = {
  8931. id: document.getElementById('modal-bgp-net-id').value,
  8932. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8933. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8934. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8935. };
  8936. try {
  8937. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8938. method: 'POST',
  8939. headers: { 'Content-Type': 'application/json' },
  8940. body: JSON.stringify(payload)
  8941. });
  8942. if (res.ok) {
  8943. closeBgpNetworkModal();
  8944. showToast('Success', 'BGP network advertisement saved', 'success');
  8945. loadDynamicRouting();
  8946. } else {
  8947. const err = await res.json();
  8948. showToast('Error', err.error || 'Failed to save network', 'error');
  8949. }
  8950. } catch (err) {
  8951. showToast('Error', err.message, 'error');
  8952. }
  8953. }
  8954. async function deleteBgpNetwork(id) {
  8955. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8956. try {
  8957. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8958. if (res.ok) {
  8959. showToast('Deleted', 'Network advertisement removed', 'success');
  8960. loadDynamicRouting();
  8961. }
  8962. } catch (err) {
  8963. showToast('Error', err.message, 'error');
  8964. }
  8965. }
  8966. // =========================================================================
  8967. // DEBTIK v7 OSPF MODALS & ACTIONS
  8968. // =========================================================================
  8969. // --- 1. OSPF INSTANCE ---
  8970. function openOspfInstanceModal(id = null) {
  8971. const isEdit = !!id;
  8972. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8973. id: '',
  8974. name: 'Default',
  8975. version: 2,
  8976. vrf: 'main',
  8977. router_id: '192.168.131.56',
  8978. routing_table: 'main',
  8979. enabled: true,
  8980. redistribute_connected: false,
  8981. redistribute_static: true,
  8982. redistribute_bgp: false,
  8983. comment: ''
  8984. };
  8985. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8986. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8987. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8988. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8989. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8990. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8991. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8992. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8993. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8994. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8995. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8996. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8997. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8998. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8999. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9000. }
  9001. function openEditOspfInstanceModal(id) {
  9002. openOspfInstanceModal(id);
  9003. }
  9004. function closeOspfInstanceModal() {
  9005. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9006. }
  9007. async function submitOspfInstance(e) {
  9008. if (e) e.preventDefault();
  9009. const payload = {
  9010. id: document.getElementById('modal-ospf-inst-id').value,
  9011. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  9012. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  9013. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  9014. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  9015. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  9016. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  9017. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  9018. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  9019. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  9020. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  9021. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  9022. };
  9023. try {
  9024. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  9025. method: 'POST',
  9026. headers: { 'Content-Type': 'application/json' },
  9027. body: JSON.stringify(payload)
  9028. });
  9029. if (res.ok) {
  9030. closeOspfInstanceModal();
  9031. showToast('Saved', 'OSPF instance updated', 'success');
  9032. loadDynamicRouting();
  9033. } else {
  9034. const err = await res.json();
  9035. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  9036. }
  9037. } catch (err) {
  9038. showToast('Error', err.message, 'error');
  9039. }
  9040. }
  9041. function applyOspfInstanceForm() {
  9042. submitOspfInstance(null);
  9043. }
  9044. function copyOspfInstance() {
  9045. document.getElementById('modal-ospf-inst-id').value = '';
  9046. document.getElementById('modal-ospf-inst-name').value += '-copy';
  9047. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  9048. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  9049. }
  9050. async function deleteCurrentOspfInstance() {
  9051. const id = document.getElementById('modal-ospf-inst-id').value;
  9052. if (!id) return;
  9053. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  9054. try {
  9055. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9056. if (res.ok) {
  9057. closeOspfInstanceModal();
  9058. showToast('Removed', 'OSPF instance deleted', 'success');
  9059. loadDynamicRouting();
  9060. }
  9061. } catch (err) {
  9062. showToast('Error', err.message, 'error');
  9063. }
  9064. }
  9065. async function enableSelectedOspfInstance() {
  9066. const id = state.selectedOspfRow?.instances;
  9067. if (!id) return;
  9068. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9069. method: 'POST',
  9070. headers: { 'Content-Type': 'application/json' },
  9071. body: JSON.stringify({ disabled: false })
  9072. });
  9073. loadDynamicRouting();
  9074. }
  9075. async function disableSelectedOspfInstance() {
  9076. const id = state.selectedOspfRow?.instances;
  9077. if (!id) return;
  9078. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  9079. method: 'POST',
  9080. headers: { 'Content-Type': 'application/json' },
  9081. body: JSON.stringify({ disabled: true })
  9082. });
  9083. loadDynamicRouting();
  9084. }
  9085. async function removeSelectedOspfInstance() {
  9086. const id = state.selectedOspfRow?.instances;
  9087. if (!id) return;
  9088. if (!confirm('Delete selected OSPF instance?')) return;
  9089. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9090. loadDynamicRouting();
  9091. }
  9092. async function promptCommentOspfInstance() {
  9093. const id = state.selectedOspfRow?.instances;
  9094. if (!id) return;
  9095. const inst = (state.ospfInstances || []).find(i => i.id === id);
  9096. if (!inst) return;
  9097. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  9098. if (comment === null) return;
  9099. inst.comment = comment;
  9100. await fetch(`${API_BASE}/routing/ospf/instances`, {
  9101. method: 'POST',
  9102. headers: { 'Content-Type': 'application/json' },
  9103. body: JSON.stringify(inst)
  9104. });
  9105. loadDynamicRouting();
  9106. }
  9107. // --- 2. OSPF AREA ---
  9108. function populateOspfAreaDropdowns() {
  9109. const instSelect = document.getElementById('modal-ospf-area-instance');
  9110. if (instSelect) {
  9111. const cur = instSelect.value;
  9112. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9113. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9114. if (cur) instSelect.value = cur;
  9115. }
  9116. }
  9117. function openOspfAreaModal(id = null) {
  9118. const isEdit = !!id;
  9119. populateOspfAreaDropdowns();
  9120. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9121. id: '',
  9122. name: 'Default',
  9123. instance: 'Default',
  9124. area_id: '0.0.0.0',
  9125. area_type: 'default',
  9126. default_cost: 1,
  9127. no_summaries: false,
  9128. disabled: false,
  9129. comment: ''
  9130. };
  9131. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9132. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9133. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9134. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9135. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9136. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9137. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9138. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9139. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9140. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9141. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9142. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9143. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9144. }
  9145. function openEditOspfAreaModal(id) {
  9146. openOspfAreaModal(id);
  9147. }
  9148. function closeOspfAreaModal() {
  9149. document.getElementById('ospf-area-modal').classList.add('hidden');
  9150. }
  9151. async function submitOspfArea(e) {
  9152. if (e) e.preventDefault();
  9153. const payload = {
  9154. id: document.getElementById('modal-ospf-area-id').value,
  9155. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9156. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9157. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9158. area_type: document.getElementById('modal-ospf-area-type').value,
  9159. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9160. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9161. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9162. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9163. };
  9164. try {
  9165. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9166. method: 'POST',
  9167. headers: { 'Content-Type': 'application/json' },
  9168. body: JSON.stringify(payload)
  9169. });
  9170. if (res.ok) {
  9171. closeOspfAreaModal();
  9172. showToast('Saved', 'OSPF area saved', 'success');
  9173. loadDynamicRouting();
  9174. } else {
  9175. const err = await res.json();
  9176. showToast('Error', err.error || 'Failed to save area', 'error');
  9177. }
  9178. } catch (err) {
  9179. showToast('Error', err.message, 'error');
  9180. }
  9181. }
  9182. function applyOspfAreaForm() {
  9183. submitOspfArea(null);
  9184. }
  9185. function copyOspfArea() {
  9186. document.getElementById('modal-ospf-area-id').value = '';
  9187. document.getElementById('modal-ospf-area-name').value += '-copy';
  9188. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9189. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9190. }
  9191. async function deleteCurrentOspfArea() {
  9192. const id = document.getElementById('modal-ospf-area-id').value;
  9193. if (!id) return;
  9194. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9195. try {
  9196. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9197. if (res.ok) {
  9198. closeOspfAreaModal();
  9199. showToast('Removed', 'OSPF area deleted', 'success');
  9200. loadDynamicRouting();
  9201. }
  9202. } catch (err) {
  9203. showToast('Error', err.message, 'error');
  9204. }
  9205. }
  9206. async function enableSelectedOspfArea() {
  9207. const id = state.selectedOspfRow?.areas;
  9208. if (!id) return;
  9209. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9210. method: 'POST',
  9211. headers: { 'Content-Type': 'application/json' },
  9212. body: JSON.stringify({ disabled: false })
  9213. });
  9214. loadDynamicRouting();
  9215. }
  9216. async function disableSelectedOspfArea() {
  9217. const id = state.selectedOspfRow?.areas;
  9218. if (!id) return;
  9219. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9220. method: 'POST',
  9221. headers: { 'Content-Type': 'application/json' },
  9222. body: JSON.stringify({ disabled: true })
  9223. });
  9224. loadDynamicRouting();
  9225. }
  9226. async function removeSelectedOspfArea() {
  9227. const id = state.selectedOspfRow?.areas;
  9228. if (!id) return;
  9229. if (!confirm('Delete selected OSPF area?')) return;
  9230. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9231. loadDynamicRouting();
  9232. }
  9233. async function promptCommentOspfArea() {
  9234. const id = state.selectedOspfRow?.areas;
  9235. if (!id) return;
  9236. const area = (state.ospfAreas || []).find(a => a.id === id);
  9237. if (!area) return;
  9238. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9239. if (comment === null) return;
  9240. area.comment = comment;
  9241. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9242. method: 'POST',
  9243. headers: { 'Content-Type': 'application/json' },
  9244. body: JSON.stringify(area)
  9245. });
  9246. loadDynamicRouting();
  9247. }
  9248. // --- 3. OSPF AREA RANGE ---
  9249. function populateAreaRangeDropdowns() {
  9250. const select = document.getElementById('modal-ospf-range-area');
  9251. if (select) {
  9252. const cur = select.value;
  9253. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9254. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9255. if (cur) select.value = cur;
  9256. }
  9257. }
  9258. function openOspfAreaRangeModal(id = null) {
  9259. const isEdit = !!id;
  9260. populateAreaRangeDropdowns();
  9261. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9262. id: '',
  9263. area: 'Default',
  9264. prefix: '',
  9265. cost: 1,
  9266. advertise: true,
  9267. disabled: false,
  9268. comment: ''
  9269. };
  9270. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9271. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9272. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9273. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9274. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9275. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9276. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9277. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9278. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9279. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9280. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9281. }
  9282. function openEditOspfAreaRangeModal(id) {
  9283. openOspfAreaRangeModal(id);
  9284. }
  9285. function closeOspfAreaRangeModal() {
  9286. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9287. }
  9288. async function submitOspfAreaRange(e) {
  9289. if (e) e.preventDefault();
  9290. const payload = {
  9291. id: document.getElementById('modal-ospf-range-id').value,
  9292. area: document.getElementById('modal-ospf-range-area').value,
  9293. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9294. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9295. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9296. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9297. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9298. };
  9299. try {
  9300. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9301. method: 'POST',
  9302. headers: { 'Content-Type': 'application/json' },
  9303. body: JSON.stringify(payload)
  9304. });
  9305. if (res.ok) {
  9306. closeOspfAreaRangeModal();
  9307. showToast('Saved', 'Area range saved', 'success');
  9308. loadDynamicRouting();
  9309. } else {
  9310. const err = await res.json();
  9311. showToast('Error', err.error || 'Failed to save area range', 'error');
  9312. }
  9313. } catch (err) {
  9314. showToast('Error', err.message, 'error');
  9315. }
  9316. }
  9317. function applyOspfAreaRangeForm() {
  9318. submitOspfAreaRange(null);
  9319. }
  9320. async function deleteCurrentOspfAreaRange() {
  9321. const id = document.getElementById('modal-ospf-range-id').value;
  9322. if (!id) return;
  9323. if (!confirm('Delete this area range?')) return;
  9324. try {
  9325. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9326. closeOspfAreaRangeModal();
  9327. showToast('Removed', 'Area range removed', 'success');
  9328. loadDynamicRouting();
  9329. } catch (err) {
  9330. showToast('Error', err.message, 'error');
  9331. }
  9332. }
  9333. async function enableSelectedOspfAreaRange() {
  9334. const id = state.selectedOspfRow?.['area-ranges'];
  9335. if (!id) return;
  9336. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9337. if (!r) return;
  9338. r.disabled = false;
  9339. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9340. loadDynamicRouting();
  9341. }
  9342. async function disableSelectedOspfAreaRange() {
  9343. const id = state.selectedOspfRow?.['area-ranges'];
  9344. if (!id) return;
  9345. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9346. if (!r) return;
  9347. r.disabled = true;
  9348. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9349. loadDynamicRouting();
  9350. }
  9351. async function removeSelectedOspfAreaRange() {
  9352. const id = state.selectedOspfRow?.['area-ranges'];
  9353. if (!id) return;
  9354. if (!confirm('Delete selected area range?')) return;
  9355. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9356. loadDynamicRouting();
  9357. }
  9358. async function promptCommentOspfAreaRange() {
  9359. const id = state.selectedOspfRow?.['area-ranges'];
  9360. if (!id) return;
  9361. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9362. if (!r) return;
  9363. const comment = prompt('Enter comment for area range:', r.comment || '');
  9364. if (comment === null) return;
  9365. r.comment = comment;
  9366. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9367. loadDynamicRouting();
  9368. }
  9369. // --- 4. OSPF INTERFACE TEMPLATE ---
  9370. function switchOspfTemplateTab(tab) {
  9371. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9372. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9373. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9374. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9375. if (tab === 'general') {
  9376. if (tabGen) tabGen.classList.remove('hidden');
  9377. if (tabAuth) tabAuth.classList.add('hidden');
  9378. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9379. 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';
  9380. } else {
  9381. if (tabGen) tabGen.classList.add('hidden');
  9382. if (tabAuth) tabAuth.classList.remove('hidden');
  9383. 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';
  9384. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9385. }
  9386. }
  9387. function populateTemplateAreaDropdowns() {
  9388. const select = document.getElementById('modal-ospf-tmpl-area');
  9389. if (select) {
  9390. const cur = select.value;
  9391. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9392. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9393. if (cur) select.value = cur;
  9394. }
  9395. }
  9396. function openOspfTemplateModal(id = null) {
  9397. const isEdit = !!id;
  9398. populateTemplateAreaDropdowns();
  9399. switchOspfTemplateTab('general');
  9400. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9401. id: '',
  9402. interfaces: '',
  9403. area: 'Default',
  9404. networks: '',
  9405. network_type: 'broadcast',
  9406. cost: 1,
  9407. priority: 128,
  9408. passive: false,
  9409. hello_interval: 10,
  9410. dead_interval: 40,
  9411. auth: 'none',
  9412. auth_key: '',
  9413. disabled: false,
  9414. comment: ''
  9415. };
  9416. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9417. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9418. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9419. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9420. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9421. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9422. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9423. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9424. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9425. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9426. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9427. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9428. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9429. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9430. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9431. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9432. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9433. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9434. }
  9435. function openEditOspfTemplateModal(id) {
  9436. openOspfTemplateModal(id);
  9437. }
  9438. function closeOspfTemplateModal() {
  9439. document.getElementById('ospf-template-modal').classList.add('hidden');
  9440. }
  9441. async function submitOspfTemplate(e) {
  9442. if (e) e.preventDefault();
  9443. const payload = {
  9444. id: document.getElementById('modal-ospf-tmpl-id').value,
  9445. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9446. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9447. area: document.getElementById('modal-ospf-tmpl-area').value,
  9448. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9449. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9450. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9451. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9452. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9453. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9454. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9455. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9456. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9457. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9458. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9459. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9460. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9461. };
  9462. try {
  9463. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9464. method: 'POST',
  9465. headers: { 'Content-Type': 'application/json' },
  9466. body: JSON.stringify(payload)
  9467. });
  9468. if (res.ok) {
  9469. closeOspfTemplateModal();
  9470. showToast('Saved', 'Interface template saved', 'success');
  9471. loadDynamicRouting();
  9472. } else {
  9473. const err = await res.json();
  9474. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9475. }
  9476. } catch (err) {
  9477. showToast('Error', err.message, 'error');
  9478. }
  9479. }
  9480. function applyOspfTemplateForm() {
  9481. submitOspfTemplate(null);
  9482. }
  9483. function copyOspfTemplate() {
  9484. document.getElementById('modal-ospf-tmpl-id').value = '';
  9485. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9486. showToast('Copied', 'Duplicated as new template', 'info');
  9487. }
  9488. async function deleteCurrentOspfTemplate() {
  9489. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9490. if (!id) return;
  9491. if (!confirm('Delete this interface template?')) return;
  9492. try {
  9493. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9494. closeOspfTemplateModal();
  9495. showToast('Removed', 'Interface template deleted', 'success');
  9496. loadDynamicRouting();
  9497. } catch (err) {
  9498. showToast('Error', err.message, 'error');
  9499. }
  9500. }
  9501. async function enableSelectedOspfTemplate() {
  9502. const id = state.selectedOspfRow?.templates;
  9503. if (!id) return;
  9504. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9505. method: 'POST',
  9506. headers: { 'Content-Type': 'application/json' },
  9507. body: JSON.stringify({ disabled: false })
  9508. });
  9509. loadDynamicRouting();
  9510. }
  9511. async function disableSelectedOspfTemplate() {
  9512. const id = state.selectedOspfRow?.templates;
  9513. if (!id) return;
  9514. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9515. method: 'POST',
  9516. headers: { 'Content-Type': 'application/json' },
  9517. body: JSON.stringify({ disabled: true })
  9518. });
  9519. loadDynamicRouting();
  9520. }
  9521. async function removeSelectedOspfTemplate() {
  9522. const id = state.selectedOspfRow?.templates;
  9523. if (!id) return;
  9524. if (!confirm('Delete selected interface template?')) return;
  9525. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9526. loadDynamicRouting();
  9527. }
  9528. async function promptCommentOspfTemplate() {
  9529. const id = state.selectedOspfRow?.templates;
  9530. if (!id) return;
  9531. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9532. if (!tmpl) return;
  9533. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9534. if (comment === null) return;
  9535. tmpl.comment = comment;
  9536. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9537. method: 'POST',
  9538. headers: { 'Content-Type': 'application/json' },
  9539. body: JSON.stringify(tmpl)
  9540. });
  9541. loadDynamicRouting();
  9542. }
  9543. // --- 5. OSPF STATIC NEIGHBOR ---
  9544. function populateStaticNbrAreaDropdowns() {
  9545. const select = document.getElementById('modal-ospf-snbr-area');
  9546. if (select) {
  9547. const cur = select.value;
  9548. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9549. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9550. if (cur) select.value = cur;
  9551. }
  9552. }
  9553. function openOspfStaticNbrModal(id = null) {
  9554. const isEdit = !!id;
  9555. populateStaticNbrAreaDropdowns();
  9556. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9557. id: '',
  9558. address: '',
  9559. area: 'Default',
  9560. poll_interval: 120,
  9561. cost: 1,
  9562. disabled: false,
  9563. comment: ''
  9564. };
  9565. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9566. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9567. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9568. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9569. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9570. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9571. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9572. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9573. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9574. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9575. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9576. }
  9577. function openEditOspfStaticNbrModal(id) {
  9578. openOspfStaticNbrModal(id);
  9579. }
  9580. function closeOspfStaticNbrModal() {
  9581. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9582. }
  9583. async function submitOspfStaticNbr(e) {
  9584. if (e) e.preventDefault();
  9585. const payload = {
  9586. id: document.getElementById('modal-ospf-snbr-id').value,
  9587. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9588. area: document.getElementById('modal-ospf-snbr-area').value,
  9589. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9590. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9591. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9592. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9593. };
  9594. try {
  9595. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9596. method: 'POST',
  9597. headers: { 'Content-Type': 'application/json' },
  9598. body: JSON.stringify(payload)
  9599. });
  9600. if (res.ok) {
  9601. closeOspfStaticNbrModal();
  9602. showToast('Saved', 'Static neighbor saved', 'success');
  9603. loadDynamicRouting();
  9604. } else {
  9605. const err = await res.json();
  9606. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9607. }
  9608. } catch (err) {
  9609. showToast('Error', err.message, 'error');
  9610. }
  9611. }
  9612. function applyOspfStaticNbrForm() {
  9613. submitOspfStaticNbr(null);
  9614. }
  9615. async function deleteCurrentOspfStaticNbr() {
  9616. const id = document.getElementById('modal-ospf-snbr-id').value;
  9617. if (!id) return;
  9618. if (!confirm('Delete this static neighbor?')) return;
  9619. try {
  9620. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9621. closeOspfStaticNbrModal();
  9622. showToast('Removed', 'Static neighbor removed', 'success');
  9623. loadDynamicRouting();
  9624. } catch (err) {
  9625. showToast('Error', err.message, 'error');
  9626. }
  9627. }
  9628. async function enableSelectedOspfStaticNbr() {
  9629. const id = state.selectedOspfRow?.['static-nbrs'];
  9630. if (!id) return;
  9631. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9632. if (!n) return;
  9633. n.disabled = false;
  9634. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9635. loadDynamicRouting();
  9636. }
  9637. async function disableSelectedOspfStaticNbr() {
  9638. const id = state.selectedOspfRow?.['static-nbrs'];
  9639. if (!id) return;
  9640. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9641. if (!n) return;
  9642. n.disabled = true;
  9643. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9644. loadDynamicRouting();
  9645. }
  9646. async function removeSelectedOspfStaticNbr() {
  9647. const id = state.selectedOspfRow?.['static-nbrs'];
  9648. if (!id) return;
  9649. if (!confirm('Delete selected static neighbor?')) return;
  9650. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9651. loadDynamicRouting();
  9652. }
  9653. async function promptCommentOspfStaticNbr() {
  9654. const id = state.selectedOspfRow?.['static-nbrs'];
  9655. if (!id) return;
  9656. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9657. if (!n) return;
  9658. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9659. if (comment === null) return;
  9660. n.comment = comment;
  9661. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9662. loadDynamicRouting();
  9663. }
  9664. // Backward-compat aliases
  9665. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9666. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9667. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9668. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9669. function deleteOspfInterface(id) {
  9670. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9671. }
  9672. function toggleOspfInterfaceState(id, disabled) {
  9673. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9674. method: 'POST',
  9675. headers: { 'Content-Type': 'application/json' },
  9676. body: JSON.stringify({ disabled })
  9677. }).then(() => loadDynamicRouting());
  9678. }
  9679. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9680. function deleteOspfArea(id) {
  9681. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9682. }
  9683. // ============================================================================
  9684. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9685. // ============================================================================
  9686. function switchBridgeSubTab(tab) {
  9687. state.bridgeSubTab = tab;
  9688. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9689. tabs.forEach(t => {
  9690. const panel = document.getElementById(`bridge-subtab-${t}`);
  9691. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9692. if (panel) {
  9693. if (t === tab) panel.classList.remove('hidden');
  9694. else panel.classList.add('hidden');
  9695. }
  9696. if (btn) {
  9697. if (t === tab) {
  9698. 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';
  9699. } else {
  9700. 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';
  9701. }
  9702. }
  9703. });
  9704. const addBtn = document.getElementById('bridge-top-action-btn');
  9705. if (addBtn) {
  9706. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9707. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9708. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9709. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9710. }
  9711. if (tab === 'hosts') loadBridgeHosts();
  9712. setTimeout(initTableSorting, 50);
  9713. }
  9714. function openCurrentBridgeModal() {
  9715. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9716. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9717. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9718. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9719. }
  9720. async function loadBridge() {
  9721. try {
  9722. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9723. fetch(`${API_BASE}/bridge/bridges`),
  9724. fetch(`${API_BASE}/bridge/ports`),
  9725. fetch(`${API_BASE}/bridge/vlans`),
  9726. fetch(`${API_BASE}/bridge/summary`),
  9727. fetch(`${API_BASE}/vpn/eoip`),
  9728. fetch(`${API_BASE}/vlans`)
  9729. ]);
  9730. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9731. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9732. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9733. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9734. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9735. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9736. // Badges & Stats
  9737. const bBridges = document.getElementById('bridge-badge-bridges');
  9738. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9739. const bPorts = document.getElementById('bridge-badge-ports');
  9740. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9741. const bVlans = document.getElementById('bridge-badge-vlans');
  9742. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9743. const bHosts = document.getElementById('bridge-badge-hosts');
  9744. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9745. const sBr = document.getElementById('bridge-stat-bridges');
  9746. if (sBr) sBr.innerText = (state.bridges || []).length;
  9747. const sPorts = document.getElementById('bridge-stat-ports');
  9748. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9749. const sHosts = document.getElementById('bridge-stat-hosts');
  9750. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9751. renderBridges();
  9752. renderBridgePorts();
  9753. renderBridgeVLANs();
  9754. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9755. } catch (err) {
  9756. console.error('Failed to load bridge subsystem:', err);
  9757. }
  9758. }
  9759. // ----------------- Bridges -----------------
  9760. function renderBridges() {
  9761. const tbody = document.getElementById('bridge-table-body');
  9762. const empty = document.getElementById('bridge-empty-bridges');
  9763. const countBadge = document.getElementById('bridge-count-badge');
  9764. if (!tbody) return;
  9765. tbody.innerHTML = '';
  9766. const bridges = state.bridges || [];
  9767. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9768. if (bridges.length === 0) {
  9769. empty?.classList.remove('hidden');
  9770. return;
  9771. }
  9772. empty?.classList.add('hidden');
  9773. bridges.forEach((b, idx) => {
  9774. const tr = document.createElement('tr');
  9775. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9776. // Format IP addresses pill list
  9777. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9778. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9779. ipsHtml = b.ip_addresses.map(ip => `
  9780. <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">
  9781. <span>${ip}</span>
  9782. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9783. </span>
  9784. `).join(' ');
  9785. }
  9786. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9787. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9788. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9789. tr.innerHTML = `
  9790. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9791. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9792. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9793. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9794. </td>
  9795. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9796. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9797. <td class="py-2.5 px-3">
  9798. <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>
  9799. </td>
  9800. <td class="py-2.5 px-3 text-center">
  9801. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9802. </td>
  9803. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9804. <td class="py-2.5 px-3">
  9805. <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>
  9806. </td>
  9807. <td class="py-2.5 px-3">
  9808. <div class="flex items-center gap-1.5 flex-wrap">
  9809. ${ipsHtml}
  9810. <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>
  9811. </div>
  9812. </td>
  9813. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9814. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9815. </td>
  9816. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9817. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9818. <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>
  9819. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9820. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9821. </td>
  9822. `;
  9823. tbody.appendChild(tr);
  9824. });
  9825. }
  9826. function openAddBridgeModal() {
  9827. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9828. document.getElementById('bridge-modal-id').value = '';
  9829. document.getElementById('bridge-modal-name').value = 'bridge1';
  9830. document.getElementById('bridge-modal-name').disabled = false;
  9831. document.getElementById('bridge-modal-mtu').value = '1500';
  9832. document.getElementById('bridge-modal-mac').value = '';
  9833. document.getElementById('bridge-modal-stp').value = 'stp';
  9834. document.getElementById('bridge-modal-priority').value = '32768';
  9835. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9836. document.getElementById('bridge-modal-pvid').value = '1';
  9837. document.getElementById('bridge-modal-fastforward').checked = true;
  9838. document.getElementById('bridge-modal-comment').value = '';
  9839. document.getElementById('bridge-modal-disabled').checked = false;
  9840. toggleBridgeModalVlanFiltering();
  9841. document.getElementById('bridge-modal').classList.remove('hidden');
  9842. }
  9843. function openEditBridgeModal(id) {
  9844. const b = (state.bridges || []).find(x => x.id === id);
  9845. if (!b) return;
  9846. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9847. document.getElementById('bridge-modal-id').value = b.id;
  9848. document.getElementById('bridge-modal-name').value = b.name;
  9849. document.getElementById('bridge-modal-name').disabled = true;
  9850. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9851. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9852. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  9853. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9854. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9855. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9856. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9857. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9858. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9859. toggleBridgeModalVlanFiltering();
  9860. document.getElementById('bridge-modal').classList.remove('hidden');
  9861. }
  9862. function closeBridgeModal() {
  9863. document.getElementById('bridge-modal').classList.add('hidden');
  9864. }
  9865. function toggleBridgeModalVlanFiltering() {
  9866. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9867. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9868. if (pvidBox) {
  9869. if (chk) pvidBox.classList.remove('opacity-40');
  9870. else pvidBox.classList.add('opacity-40');
  9871. }
  9872. }
  9873. async function submitSaveBridge(e) {
  9874. e.preventDefault();
  9875. const id = document.getElementById('bridge-modal-id').value;
  9876. const name = document.getElementById('bridge-modal-name').value.trim();
  9877. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9878. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9879. const stp = document.getElementById('bridge-modal-stp').value;
  9880. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9881. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9882. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9883. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9884. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9885. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9886. try {
  9887. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9888. method: 'POST',
  9889. headers: { 'Content-Type': 'application/json' },
  9890. body: JSON.stringify({
  9891. id,
  9892. name,
  9893. mtu,
  9894. mac_address: mac,
  9895. stp,
  9896. priority,
  9897. vlan_filtering: vlanFiltering,
  9898. pvid,
  9899. fast_forward: fastForward,
  9900. comment,
  9901. disabled
  9902. })
  9903. });
  9904. if (res.ok) {
  9905. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9906. closeBridgeModal();
  9907. loadBridge();
  9908. fetchData(false);
  9909. } else {
  9910. const err = await res.json();
  9911. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9912. }
  9913. } catch (err) {
  9914. showToast('Error', err.message, 'error');
  9915. }
  9916. }
  9917. async function toggleBridgeState(id, disabled) {
  9918. try {
  9919. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9920. method: 'POST',
  9921. headers: { 'Content-Type': 'application/json' },
  9922. body: JSON.stringify({ disabled })
  9923. });
  9924. if (res.ok) {
  9925. loadBridge();
  9926. fetchData(false);
  9927. }
  9928. } catch (err) {
  9929. showToast('Error', err.message, 'error');
  9930. }
  9931. }
  9932. async function deleteBridge(id) {
  9933. const b = (state.bridges || []).find(x => x.id === id);
  9934. const name = b ? b.name : id;
  9935. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9936. try {
  9937. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9938. if (res.ok) {
  9939. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9940. loadBridge();
  9941. fetchData(false);
  9942. } else {
  9943. const err = await res.json();
  9944. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9945. }
  9946. } catch (err) {
  9947. showToast('Error', err.message, 'error');
  9948. }
  9949. }
  9950. // ----------------- Bridge IP Assignments -----------------
  9951. function openAddBridgeIPModal(id, name) {
  9952. document.getElementById('bridge-ip-modal-id').value = id;
  9953. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9954. document.getElementById('bridge-ip-modal-cidr').value = '';
  9955. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9956. }
  9957. function closeBridgeIPModal() {
  9958. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9959. }
  9960. async function submitAddBridgeIP(e) {
  9961. e.preventDefault();
  9962. const id = document.getElementById('bridge-ip-modal-id').value;
  9963. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9964. try {
  9965. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9966. method: 'POST',
  9967. headers: { 'Content-Type': 'application/json' },
  9968. body: JSON.stringify({ ip })
  9969. });
  9970. if (res.ok) {
  9971. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9972. closeBridgeIPModal();
  9973. loadBridge();
  9974. fetchData(false);
  9975. } else {
  9976. const err = await res.json();
  9977. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9978. }
  9979. } catch (err) {
  9980. showToast('Error', err.message, 'error');
  9981. }
  9982. }
  9983. async function deleteBridgeIP(id, ip) {
  9984. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9985. try {
  9986. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9987. method: 'DELETE',
  9988. headers: { 'Content-Type': 'application/json' },
  9989. body: JSON.stringify({ ip })
  9990. });
  9991. if (res.ok) {
  9992. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9993. loadBridge();
  9994. fetchData(false);
  9995. }
  9996. } catch (err) {
  9997. showToast('Error', err.message, 'error');
  9998. }
  9999. }
  10000. // ----------------- Bridge Ports -----------------
  10001. function renderBridgePorts() {
  10002. const tbody = document.getElementById('bridge-ports-table-body');
  10003. const empty = document.getElementById('bridge-empty-ports');
  10004. const countBadge = document.getElementById('bridge-ports-count-badge');
  10005. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10006. if (!tbody) return;
  10007. tbody.innerHTML = '';
  10008. // Update filter select
  10009. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10010. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  10011. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  10012. if (ports.length === 0) {
  10013. empty?.classList.remove('hidden');
  10014. return;
  10015. }
  10016. empty?.classList.add('hidden');
  10017. ports.forEach((p, idx) => {
  10018. const tr = document.createElement('tr');
  10019. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  10020. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10021. tr.innerHTML = `
  10022. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10023. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10024. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10025. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  10026. </td>
  10027. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  10028. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  10029. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  10030. <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>
  10031. <td class="py-2.5 px-3">
  10032. ${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>'}
  10033. </td>
  10034. <td class="py-2.5 px-3">
  10035. <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>
  10036. </td>
  10037. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  10038. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10039. <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>
  10040. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10041. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10042. </td>
  10043. `;
  10044. tbody.appendChild(tr);
  10045. });
  10046. }
  10047. function openAddBridgePortModal() {
  10048. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  10049. document.getElementById('bridge-port-modal-id').value = '';
  10050. populateBridgeSelect('bridge-port-modal-bridge');
  10051. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  10052. document.getElementById('bridge-port-modal-pvid').value = '1';
  10053. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  10054. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  10055. document.getElementById('bridge-port-modal-horizon').value = '0';
  10056. document.getElementById('bridge-port-modal-pathcost').value = '10';
  10057. document.getElementById('bridge-port-modal-priority').value = '128';
  10058. document.getElementById('bridge-port-modal-learn').checked = true;
  10059. document.getElementById('bridge-port-modal-comment').value = '';
  10060. document.getElementById('bridge-port-modal-disabled').checked = false;
  10061. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10062. }
  10063. function openEditBridgePortModal(id) {
  10064. const p = (state.bridgePorts || []).find(x => x.id === id);
  10065. if (!p) return;
  10066. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  10067. document.getElementById('bridge-port-modal-id').value = p.id;
  10068. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  10069. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  10070. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  10071. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  10072. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  10073. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  10074. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  10075. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  10076. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  10077. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  10078. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  10079. document.getElementById('bridge-port-modal').classList.remove('hidden');
  10080. }
  10081. function closeBridgePortModal() {
  10082. document.getElementById('bridge-port-modal').classList.add('hidden');
  10083. }
  10084. async function submitSaveBridgePort(e) {
  10085. e.preventDefault();
  10086. const id = document.getElementById('bridge-port-modal-id').value;
  10087. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  10088. const iface = document.getElementById('bridge-port-modal-interface').value;
  10089. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  10090. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  10091. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  10092. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  10093. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  10094. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  10095. const learn = document.getElementById('bridge-port-modal-learn').checked;
  10096. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  10097. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  10098. try {
  10099. const res = await fetch(`${API_BASE}/bridge/ports`, {
  10100. method: 'POST',
  10101. headers: { 'Content-Type': 'application/json' },
  10102. body: JSON.stringify({
  10103. id,
  10104. bridge,
  10105. interface: iface,
  10106. pvid,
  10107. frame_types: frameTypes,
  10108. ingress_filtering: ingressFiltering,
  10109. horizon,
  10110. path_cost: pathCost,
  10111. priority,
  10112. learn,
  10113. comment,
  10114. disabled
  10115. })
  10116. });
  10117. if (res.ok) {
  10118. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10119. closeBridgePortModal();
  10120. loadBridge();
  10121. fetchData(false);
  10122. } else {
  10123. const err = await res.json();
  10124. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10125. }
  10126. } catch (err) {
  10127. showToast('Error', err.message, 'error');
  10128. }
  10129. }
  10130. async function toggleBridgePortState(id, disabled) {
  10131. try {
  10132. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10133. method: 'POST',
  10134. headers: { 'Content-Type': 'application/json' },
  10135. body: JSON.stringify({ disabled })
  10136. });
  10137. if (res.ok) {
  10138. loadBridge();
  10139. fetchData(false);
  10140. }
  10141. } catch (err) {
  10142. showToast('Error', err.message, 'error');
  10143. }
  10144. }
  10145. async function deleteBridgePort(id) {
  10146. const p = (state.bridgePorts || []).find(x => x.id === id);
  10147. const iface = p ? p.interface : id;
  10148. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10149. try {
  10150. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10151. if (res.ok) {
  10152. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10153. loadBridge();
  10154. fetchData(false);
  10155. }
  10156. } catch (err) {
  10157. showToast('Error', err.message, 'error');
  10158. }
  10159. }
  10160. // ----------------- Bridge VLANs -----------------
  10161. function renderBridgeVLANs() {
  10162. const tbody = document.getElementById('bridge-vlans-table-body');
  10163. const empty = document.getElementById('bridge-empty-vlans');
  10164. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10165. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10166. if (!tbody) return;
  10167. tbody.innerHTML = '';
  10168. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10169. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10170. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10171. if (vlans.length === 0) {
  10172. empty?.classList.remove('hidden');
  10173. return;
  10174. }
  10175. empty?.classList.add('hidden');
  10176. vlans.forEach((v, idx) => {
  10177. const tr = document.createElement('tr');
  10178. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10179. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10180. ? 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(' ')
  10181. : '<span class="text-slate-600">none</span>';
  10182. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10183. ? 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(' ')
  10184. : '<span class="text-slate-600">none</span>';
  10185. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10186. tr.innerHTML = `
  10187. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10188. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10189. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10190. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10191. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10192. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10193. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10194. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10195. <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>
  10196. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10197. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10198. </td>
  10199. `;
  10200. tbody.appendChild(tr);
  10201. });
  10202. }
  10203. function openAddBridgeVLANModal() {
  10204. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10205. document.getElementById('bridge-vlan-modal-id').value = '';
  10206. populateBridgeSelect('bridge-vlan-modal-bridge');
  10207. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10208. document.getElementById('bridge-vlan-modal-comment').value = '';
  10209. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10210. updateBridgeVlanPortCheckboxes();
  10211. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10212. }
  10213. function openEditBridgeVLANModal(id) {
  10214. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10215. if (!v) return;
  10216. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10217. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10218. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10219. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10220. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10221. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10222. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10223. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10224. }
  10225. function closeBridgeVlanModal() {
  10226. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10227. }
  10228. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10229. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10230. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10231. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10232. if (!taggedBox || !untaggedBox) return;
  10233. // Ports belonging to the selected bridge
  10234. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10235. if (memberPorts.length === 0) {
  10236. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10237. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10238. return;
  10239. }
  10240. taggedBox.innerHTML = memberPorts.map(p => `
  10241. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10242. <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">
  10243. <span>${p.interface}</span>
  10244. </label>
  10245. `).join('');
  10246. untaggedBox.innerHTML = memberPorts.map(p => `
  10247. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10248. <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">
  10249. <span>${p.interface}</span>
  10250. </label>
  10251. `).join('');
  10252. }
  10253. async function submitSaveBridgeVLAN(e) {
  10254. e.preventDefault();
  10255. const id = document.getElementById('bridge-vlan-modal-id').value;
  10256. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10257. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10258. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10259. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10260. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10261. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10262. try {
  10263. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10264. method: 'POST',
  10265. headers: { 'Content-Type': 'application/json' },
  10266. body: JSON.stringify({
  10267. id,
  10268. bridge,
  10269. vlan_ids: vlanIDs,
  10270. tagged,
  10271. untagged,
  10272. comment,
  10273. disabled
  10274. })
  10275. });
  10276. if (res.ok) {
  10277. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10278. closeBridgeVlanModal();
  10279. loadBridge();
  10280. } else {
  10281. const err = await res.json();
  10282. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10283. }
  10284. } catch (err) {
  10285. showToast('Error', err.message, 'error');
  10286. }
  10287. }
  10288. async function toggleBridgeVLANState(id, disabled) {
  10289. try {
  10290. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10291. method: 'POST',
  10292. headers: { 'Content-Type': 'application/json' },
  10293. body: JSON.stringify({ disabled })
  10294. });
  10295. if (res.ok) loadBridge();
  10296. } catch (err) {
  10297. showToast('Error', err.message, 'error');
  10298. }
  10299. }
  10300. async function deleteBridgeVLAN(id) {
  10301. if (!confirm('Delete this bridge VLAN entry?')) return;
  10302. try {
  10303. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10304. if (res.ok) {
  10305. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10306. loadBridge();
  10307. }
  10308. } catch (err) {
  10309. showToast('Error', err.message, 'error');
  10310. }
  10311. }
  10312. // ----------------- Hosts / MAC Table -----------------
  10313. async function loadBridgeHosts() {
  10314. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10315. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10316. try {
  10317. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10318. const res = await fetch(url);
  10319. if (res.ok) {
  10320. state.bridgeHosts = await res.json();
  10321. renderBridgeHosts();
  10322. }
  10323. } catch (err) {
  10324. console.error('Failed to load bridge hosts:', err);
  10325. }
  10326. }
  10327. function renderBridgeHosts() {
  10328. const tbody = document.getElementById('bridge-hosts-table-body');
  10329. const empty = document.getElementById('bridge-empty-hosts');
  10330. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10331. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10332. if (!tbody) return;
  10333. tbody.innerHTML = '';
  10334. const hosts = (state.bridgeHosts || []).filter(h => {
  10335. if (!search) return true;
  10336. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10337. });
  10338. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10339. if (hosts.length === 0) {
  10340. empty?.classList.remove('hidden');
  10341. return;
  10342. }
  10343. empty?.classList.add('hidden');
  10344. hosts.forEach(h => {
  10345. const tr = document.createElement('tr');
  10346. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10347. let flagBadges = '';
  10348. 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>';
  10349. 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>';
  10350. 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>';
  10351. tr.innerHTML = `
  10352. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10353. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10354. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10355. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10356. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10357. <td class="py-2.5 px-3">${flagBadges}</td>
  10358. `;
  10359. tbody.appendChild(tr);
  10360. });
  10361. }
  10362. async function flushBridgeHosts() {
  10363. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10364. if (!selBridge) {
  10365. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10366. return;
  10367. }
  10368. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10369. try {
  10370. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10371. method: 'POST',
  10372. headers: { 'Content-Type': 'application/json' },
  10373. body: JSON.stringify({ bridge: selBridge })
  10374. });
  10375. if (res.ok) {
  10376. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10377. loadBridgeHosts();
  10378. }
  10379. } catch (err) {
  10380. showToast('Error', err.message, 'error');
  10381. }
  10382. }
  10383. // ----------------- Helpers -----------------
  10384. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10385. const sel = document.getElementById(selectId);
  10386. if (!sel) return;
  10387. const prevVal = currentVal || sel.value;
  10388. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10389. (state.bridges || []).forEach(b => {
  10390. const opt = document.createElement('option');
  10391. opt.value = b.name;
  10392. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10393. if (b.name === prevVal) opt.selected = true;
  10394. sel.appendChild(opt);
  10395. });
  10396. }
  10397. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10398. const sel = document.getElementById(selectId);
  10399. if (!sel) return;
  10400. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10401. // 1. Physical Interfaces
  10402. const grpPhys = document.createElement('optgroup');
  10403. grpPhys.label = 'Physical Interfaces';
  10404. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10405. const opt = document.createElement('option');
  10406. opt.value = i.name;
  10407. opt.innerText = `${i.name} (${i.role || i.type})`;
  10408. if (i.name === currentVal) opt.selected = true;
  10409. grpPhys.appendChild(opt);
  10410. });
  10411. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10412. // 2. VLAN Sub-interfaces
  10413. const grpVlans = document.createElement('optgroup');
  10414. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10415. (state.vlans || []).forEach(v => {
  10416. const opt = document.createElement('option');
  10417. opt.value = v.name;
  10418. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10419. if (v.name === currentVal) opt.selected = true;
  10420. grpVlans.appendChild(opt);
  10421. });
  10422. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10423. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10424. const grpEoip = document.createElement('optgroup');
  10425. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10426. (state.eoipTunnels || []).forEach(t => {
  10427. const opt = document.createElement('option');
  10428. opt.value = t.name;
  10429. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10430. if (t.name === currentVal) opt.selected = true;
  10431. grpEoip.appendChild(opt);
  10432. });
  10433. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10434. }
  10435. // -------------------------------------------------------------
  10436. // DebTik Routing Filters Management (/routing filter)
  10437. // -------------------------------------------------------------
  10438. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10439. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10440. if (!state.rfSort) state.rfSort = {};
  10441. function switchRoutingFilterTab(tab) {
  10442. state.activeRoutingFilterTab = tab;
  10443. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10444. tabs.forEach(t => {
  10445. const btn = document.getElementById(`tab-rf-${t}`);
  10446. const content = document.getElementById(`tab-content-rf-${t}`);
  10447. if (btn) {
  10448. if (t === tab) {
  10449. 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';
  10450. } else {
  10451. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10452. }
  10453. }
  10454. if (content) {
  10455. if (t === tab) content.classList.remove('hidden');
  10456. else content.classList.add('hidden');
  10457. }
  10458. });
  10459. const chainContainer = document.getElementById('rf-chain-filter-container');
  10460. if (chainContainer) {
  10461. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10462. else chainContainer.classList.add('hidden');
  10463. }
  10464. renderRoutingFilters();
  10465. }
  10466. function selectFilterRow(tab, id) {
  10467. if (state.selectedFilterRow[tab] === id) {
  10468. delete state.selectedFilterRow[tab];
  10469. } else {
  10470. state.selectedFilterRow[tab] = id;
  10471. }
  10472. if (tab === 'rules') renderRoutingFilterRules();
  10473. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10474. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10475. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10476. }
  10477. function openRoutingFilterNewModal() {
  10478. const tab = state.activeRoutingFilterTab || 'rules';
  10479. if (tab === 'rules') openAddRoutingFilterModal();
  10480. else if (tab === 'select-rules') openAddSelectRuleModal();
  10481. else if (tab === 'community-lists') openAddCommunityListModal();
  10482. else if (tab === 'as-lists') openAddASListModal();
  10483. }
  10484. function toggleSelectedRoutingFilter(disabled) {
  10485. const tab = state.activeRoutingFilterTab || 'rules';
  10486. const id = state.selectedFilterRow[tab];
  10487. if (!id) {
  10488. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10489. return;
  10490. }
  10491. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10492. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10493. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10494. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10495. }
  10496. function removeSelectedRoutingFilter() {
  10497. const tab = state.activeRoutingFilterTab || 'rules';
  10498. const id = state.selectedFilterRow[tab];
  10499. if (!id) {
  10500. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10501. return;
  10502. }
  10503. if (tab === 'rules') deleteRoutingFilter(id);
  10504. else if (tab === 'select-rules') deleteSelectRule(id);
  10505. else if (tab === 'community-lists') deleteCommunityList(id);
  10506. else if (tab === 'as-lists') deleteASList(id);
  10507. }
  10508. function searchRoutingFilters(q) {
  10509. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10510. renderRoutingFilters();
  10511. }
  10512. function sortFilterTable(tab, col) {
  10513. if (!state.rfSort) state.rfSort = {};
  10514. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10515. if (state.rfSort[tab].col === col) {
  10516. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10517. } else {
  10518. state.rfSort[tab].col = col;
  10519. state.rfSort[tab].asc = true;
  10520. }
  10521. const asc = state.rfSort[tab].asc;
  10522. let list = [];
  10523. if (tab === 'rules') list = state.routingFilters || [];
  10524. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10525. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10526. else if (tab === 'as-lists') list = state.routingASLists || [];
  10527. list.sort((a, b) => {
  10528. let valA = a[col] ?? '';
  10529. let valB = b[col] ?? '';
  10530. if (col === 'flags') {
  10531. valA = a.disabled ? 'X' : 'A';
  10532. valB = b.disabled ? 'X' : 'A';
  10533. }
  10534. if (typeof valA === 'number' && typeof valB === 'number') {
  10535. return asc ? valA - valB : valB - valA;
  10536. }
  10537. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10538. });
  10539. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10540. allCols.forEach(c => {
  10541. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10542. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10543. });
  10544. if (tab === 'rules') renderRoutingFilterRules();
  10545. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10546. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10547. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10548. }
  10549. function renderRoutingFilters() {
  10550. const navBadge = document.getElementById('badge-filters-count');
  10551. const allRules = state.routingFilters || [];
  10552. if (navBadge) navBadge.innerText = allRules.length;
  10553. // Populate chain filter select options and datalist
  10554. const chainSelect = document.getElementById('routing-filter-chain-select');
  10555. const chainDatalist = document.getElementById('dl-routing-chains');
  10556. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10557. if (chainSelect) {
  10558. const currentVal = state.filterChainSelected || 'all';
  10559. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10560. uniqueChains.map(ch => {
  10561. const count = allRules.filter(r => r.chain === ch).length;
  10562. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10563. }).join('');
  10564. chainSelect.value = currentVal;
  10565. }
  10566. if (chainDatalist) {
  10567. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10568. }
  10569. renderRoutingFilterRules();
  10570. renderRoutingFilterSelectRules();
  10571. renderRoutingFilterCommunityLists();
  10572. renderRoutingFilterASLists();
  10573. }
  10574. function filterRoutingFiltersByChain(chain) {
  10575. state.filterChainSelected = chain;
  10576. renderRoutingFilters();
  10577. }
  10578. // -------------------------------------------------------------
  10579. // TAB 1: RULES (/routing filter rule)
  10580. // -------------------------------------------------------------
  10581. function renderRoutingFilterRules() {
  10582. const tbody = document.getElementById('routing-filter-rules-tbody');
  10583. if (!tbody) return;
  10584. const empty = document.getElementById('rf-rules-empty');
  10585. const statusCount = document.getElementById('rf-status-count');
  10586. let list = (state.routingFilters || []).slice();
  10587. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10588. list = list.filter(r => r.chain === state.filterChainSelected);
  10589. }
  10590. const q = state.rfSearchQuery;
  10591. if (q) {
  10592. list = list.filter(r =>
  10593. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10594. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10595. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10596. (r.comment && r.comment.toLowerCase().includes(q))
  10597. );
  10598. }
  10599. if (!state.rfSort?.['rules']) {
  10600. list.sort((a, b) => {
  10601. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10602. return (a.rule_order || 0) - (b.rule_order || 0);
  10603. });
  10604. }
  10605. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10606. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10607. }
  10608. if (list.length === 0) {
  10609. tbody.innerHTML = '';
  10610. if (empty) empty.classList.remove('hidden');
  10611. return;
  10612. }
  10613. if (empty) empty.classList.add('hidden');
  10614. tbody.innerHTML = list.map(r => {
  10615. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10616. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10617. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10618. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10619. let ruleDisplay = '';
  10620. if (r.rule && r.rule.trim() !== '') {
  10621. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10622. } else {
  10623. let conds = [];
  10624. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10625. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10626. let act = r.action || 'accept';
  10627. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10628. }
  10629. return `
  10630. <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'}">
  10631. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10632. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10633. <td class="py-2 px-3">
  10634. <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>
  10635. </td>
  10636. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10637. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10638. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10639. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  10640. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  10641. <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'}">
  10642. ${r.disabled ? 'Enable' : 'Disable'}
  10643. </button>
  10644. <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">
  10645. Edit
  10646. </button>
  10647. <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">
  10648. ✕
  10649. </button>
  10650. </td>
  10651. </tr>
  10652. `;
  10653. }).join('');
  10654. }
  10655. // -------------------------------------------------------------
  10656. // TAB 2: SELECT RULES (/routing filter select-rule)
  10657. // -------------------------------------------------------------
  10658. function renderRoutingFilterSelectRules() {
  10659. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10660. if (!tbody) return;
  10661. const empty = document.getElementById('rf-select-rules-empty');
  10662. const statusCount = document.getElementById('rf-status-count');
  10663. let list = (state.routingSelectRules || []).slice();
  10664. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10665. list = list.filter(r => r.chain === state.filterChainSelected);
  10666. }
  10667. const q = state.rfSearchQuery;
  10668. if (q) {
  10669. list = list.filter(r =>
  10670. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10671. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10672. (r.comment && r.comment.toLowerCase().includes(q))
  10673. );
  10674. }
  10675. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10676. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10677. }
  10678. if (list.length === 0) {
  10679. tbody.innerHTML = '';
  10680. if (empty) empty.classList.remove('hidden');
  10681. return;
  10682. }
  10683. if (empty) empty.classList.add('hidden');
  10684. tbody.innerHTML = list.map(r => {
  10685. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10686. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10687. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10688. return `
  10689. <tr onclick="selectFilterRow('select-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'}">
  10690. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10691. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10692. <td class="py-2 px-3">
  10693. <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>
  10694. </td>
  10695. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10696. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10697. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10698. <button onclick="toggleSelectRuleState('${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'}">
  10699. ${r.disabled ? 'Enable' : 'Disable'}
  10700. </button>
  10701. <button onclick="openEditSelectRuleModal('${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">
  10702. Edit
  10703. </button>
  10704. <button onclick="deleteSelectRule('${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">
  10705. ✕
  10706. </button>
  10707. </td>
  10708. </tr>
  10709. `;
  10710. }).join('');
  10711. }
  10712. // -------------------------------------------------------------
  10713. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10714. // -------------------------------------------------------------
  10715. function renderRoutingFilterCommunityLists() {
  10716. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10717. if (!tbody) return;
  10718. const empty = document.getElementById('rf-comm-lists-empty');
  10719. const statusCount = document.getElementById('rf-status-count');
  10720. let list = (state.routingCommunityLists || []).slice();
  10721. const q = state.rfSearchQuery;
  10722. if (q) {
  10723. list = list.filter(cl =>
  10724. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10725. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10726. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10727. );
  10728. }
  10729. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10730. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10731. }
  10732. if (list.length === 0) {
  10733. tbody.innerHTML = '';
  10734. if (empty) empty.classList.remove('hidden');
  10735. return;
  10736. }
  10737. if (empty) empty.classList.add('hidden');
  10738. tbody.innerHTML = list.map(cl => {
  10739. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10740. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10741. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10742. const commBadges = (cl.communities || []).map(c =>
  10743. `<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>`
  10744. ).join(' ');
  10745. return `
  10746. <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'}">
  10747. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10748. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10749. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10750. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10751. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10752. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10753. <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'}">
  10754. ${cl.disabled ? 'Enable' : 'Disable'}
  10755. </button>
  10756. <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">
  10757. Edit
  10758. </button>
  10759. <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">
  10760. ✕
  10761. </button>
  10762. </td>
  10763. </tr>
  10764. `;
  10765. }).join('');
  10766. }
  10767. // -------------------------------------------------------------
  10768. // TAB 4: AS LISTS (/routing filter num-list)
  10769. // -------------------------------------------------------------
  10770. function renderRoutingFilterASLists() {
  10771. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10772. if (!tbody) return;
  10773. const empty = document.getElementById('rf-as-lists-empty');
  10774. const statusCount = document.getElementById('rf-status-count');
  10775. let list = (state.routingASLists || []).slice();
  10776. const q = state.rfSearchQuery;
  10777. if (q) {
  10778. list = list.filter(al =>
  10779. (al.name && al.name.toLowerCase().includes(q)) ||
  10780. (al.range && al.range.toLowerCase().includes(q)) ||
  10781. (al.comment && al.comment.toLowerCase().includes(q))
  10782. );
  10783. }
  10784. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10785. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10786. }
  10787. if (list.length === 0) {
  10788. tbody.innerHTML = '';
  10789. if (empty) empty.classList.remove('hidden');
  10790. return;
  10791. }
  10792. if (empty) empty.classList.add('hidden');
  10793. tbody.innerHTML = list.map(al => {
  10794. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10795. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10796. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10797. return `
  10798. <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'}">
  10799. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10800. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10801. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10802. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10803. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10804. <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'}">
  10805. ${al.disabled ? 'Enable' : 'Disable'}
  10806. </button>
  10807. <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">
  10808. Edit
  10809. </button>
  10810. <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">
  10811. ✕
  10812. </button>
  10813. </td>
  10814. </tr>
  10815. `;
  10816. }).join('');
  10817. }
  10818. // -------------------------------------------------------------
  10819. // SNIPPETS & WIZARD HELPERS
  10820. // -------------------------------------------------------------
  10821. function insertRuleSnippet(type) {
  10822. const textarea = document.getElementById('modal-rf-rule');
  10823. if (!textarea) return;
  10824. let snippet = '';
  10825. switch (type) {
  10826. case 'accept-default':
  10827. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10828. break;
  10829. case 'drop-rfc1918':
  10830. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10831. break;
  10832. case 'len-24':
  10833. snippet = 'if (dst-len > 24) { reject; }';
  10834. break;
  10835. case 'local-pref-150':
  10836. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10837. break;
  10838. case 'as-prepend-2':
  10839. snippet = 'set bgp-path-prepend 2; accept;';
  10840. break;
  10841. case 'set-comm':
  10842. snippet = 'set bgp-communities.add 65000:100; accept;';
  10843. break;
  10844. case 'match-comm':
  10845. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10846. break;
  10847. case 'reject-all':
  10848. snippet = 'reject;';
  10849. break;
  10850. }
  10851. if (!snippet) return;
  10852. if (!textarea.value.trim()) {
  10853. textarea.value = snippet;
  10854. } else {
  10855. textarea.value = textarea.value.trim() + '\n' + snippet;
  10856. }
  10857. }
  10858. function generateScriptFromWizard() {
  10859. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10860. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10861. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10862. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10863. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10864. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10865. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10866. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10867. const conds = [];
  10868. if (pfx) {
  10869. if (pfxLen) {
  10870. if (pfxLen.includes('-')) {
  10871. const parts = pfxLen.split('-');
  10872. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10873. } else {
  10874. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10875. }
  10876. } else {
  10877. conds.push(`dst in ${pfx}`);
  10878. }
  10879. }
  10880. if (proto && proto !== 'any') {
  10881. conds.push(`protocol ${proto}`);
  10882. }
  10883. if (asp) {
  10884. conds.push(`bgp-as-path "${asp}"`);
  10885. }
  10886. if (comm) {
  10887. conds.push(`bgp-communities includes ${comm}`);
  10888. }
  10889. const actions = [];
  10890. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10891. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10892. actions.push(`${act};`);
  10893. let code = '';
  10894. if (conds.length > 0) {
  10895. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10896. } else {
  10897. code = actions.join(' ');
  10898. }
  10899. const textarea = document.getElementById('modal-rf-rule');
  10900. if (textarea) textarea.value = code;
  10901. }
  10902. // -------------------------------------------------------------
  10903. // MODAL CRUD: RULES (/routing filter rule)
  10904. // -------------------------------------------------------------
  10905. function openAddRoutingFilterModal(defaultChain = '') {
  10906. const form = document.getElementById('routing-filter-form');
  10907. if (form) form.reset();
  10908. const idEl = document.getElementById('modal-rf-id');
  10909. if (idEl) idEl.value = '';
  10910. const titleEl = document.getElementById('modal-rf-title');
  10911. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10912. const chainEl = document.getElementById('modal-rf-chain');
  10913. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10914. const orderEl = document.getElementById('modal-rf-order');
  10915. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10916. const ruleEl = document.getElementById('modal-rf-rule');
  10917. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10918. const disEl = document.getElementById('modal-rf-disabled');
  10919. if (disEl) disEl.checked = false;
  10920. const modal = document.getElementById('modal-routing-filter');
  10921. if (modal) modal.classList.remove('hidden');
  10922. }
  10923. function openEditRoutingFilterModal(id) {
  10924. const r = (state.routingFilters || []).find(item => item.id === id);
  10925. if (!r) return;
  10926. const idEl = document.getElementById('modal-rf-id');
  10927. if (idEl) idEl.value = r.id;
  10928. const titleEl = document.getElementById('modal-rf-title');
  10929. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10930. const chainEl = document.getElementById('modal-rf-chain');
  10931. if (chainEl) chainEl.value = r.chain || '';
  10932. const orderEl = document.getElementById('modal-rf-order');
  10933. if (orderEl) orderEl.value = r.rule_order || 10;
  10934. const ruleEl = document.getElementById('modal-rf-rule');
  10935. if (ruleEl) {
  10936. if (r.rule) {
  10937. ruleEl.value = r.rule;
  10938. } else {
  10939. let conds = [];
  10940. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10941. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10942. let act = r.action || 'accept';
  10943. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10944. }
  10945. }
  10946. const comEl = document.getElementById('modal-rf-comment');
  10947. if (comEl) comEl.value = r.comment || '';
  10948. const disEl = document.getElementById('modal-rf-disabled');
  10949. if (disEl) disEl.checked = !!r.disabled;
  10950. const modal = document.getElementById('modal-routing-filter');
  10951. if (modal) modal.classList.remove('hidden');
  10952. }
  10953. function closeRoutingFilterModal() {
  10954. const modal = document.getElementById('modal-routing-filter');
  10955. if (modal) modal.classList.add('hidden');
  10956. }
  10957. async function submitRoutingFilter(e) {
  10958. if (e) e.preventDefault();
  10959. const payload = {
  10960. id: document.getElementById('modal-rf-id').value,
  10961. chain: document.getElementById('modal-rf-chain').value.trim(),
  10962. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10963. rule: document.getElementById('modal-rf-rule').value.trim(),
  10964. comment: document.getElementById('modal-rf-comment').value.trim(),
  10965. disabled: document.getElementById('modal-rf-disabled').checked
  10966. };
  10967. try {
  10968. const res = await fetch(`${API_BASE}/routing/filters`, {
  10969. method: 'POST',
  10970. headers: { 'Content-Type': 'application/json' },
  10971. body: JSON.stringify(payload)
  10972. });
  10973. if (res.ok) {
  10974. closeRoutingFilterModal();
  10975. showToast('Success', 'Routing filter rule saved', 'success');
  10976. loadDynamicRouting();
  10977. } else {
  10978. const err = await res.json();
  10979. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10980. }
  10981. } catch (err) {
  10982. showToast('Error', err.message, 'error');
  10983. }
  10984. }
  10985. async function applyRoutingFilterForm() {
  10986. const payload = {
  10987. id: document.getElementById('modal-rf-id').value,
  10988. chain: document.getElementById('modal-rf-chain').value.trim(),
  10989. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10990. rule: document.getElementById('modal-rf-rule').value.trim(),
  10991. comment: document.getElementById('modal-rf-comment').value.trim(),
  10992. disabled: document.getElementById('modal-rf-disabled').checked
  10993. };
  10994. try {
  10995. const res = await fetch(`${API_BASE}/routing/filters`, {
  10996. method: 'POST',
  10997. headers: { 'Content-Type': 'application/json' },
  10998. body: JSON.stringify(payload)
  10999. });
  11000. if (res.ok) {
  11001. const data = await res.json();
  11002. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11003. showToast('Applied', 'Routing filter configuration applied', 'success');
  11004. loadDynamicRouting();
  11005. } else {
  11006. const err = await res.json();
  11007. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11008. }
  11009. } catch (err) {
  11010. showToast('Error', err.message, 'error');
  11011. }
  11012. }
  11013. async function moveRoutingFilterOrder(id, delta) {
  11014. const list = state.routingFilters || [];
  11015. const idx = list.findIndex(r => r.id === id);
  11016. if (idx < 0) return;
  11017. const targetIdx = idx + delta;
  11018. if (targetIdx < 0 || targetIdx >= list.length) return;
  11019. const currentOrder = list[idx].rule_order || 10;
  11020. const targetOrder = list[targetIdx].rule_order || 20;
  11021. list[idx].rule_order = targetOrder;
  11022. list[targetIdx].rule_order = currentOrder;
  11023. try {
  11024. await fetch(`${API_BASE}/routing/filters`, {
  11025. method: 'POST',
  11026. headers: { 'Content-Type': 'application/json' },
  11027. body: JSON.stringify(list[idx])
  11028. });
  11029. await fetch(`${API_BASE}/routing/filters`, {
  11030. method: 'POST',
  11031. headers: { 'Content-Type': 'application/json' },
  11032. body: JSON.stringify(list[targetIdx])
  11033. });
  11034. loadDynamicRouting();
  11035. } catch (e) {
  11036. console.error('Reorder error:', e);
  11037. }
  11038. }
  11039. async function deleteRoutingFilter(id) {
  11040. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11041. try {
  11042. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11043. if (res.ok) {
  11044. showToast('Deleted', 'Routing filter rule removed', 'info');
  11045. loadDynamicRouting();
  11046. } else {
  11047. const err = await res.json();
  11048. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11049. }
  11050. } catch (err) {
  11051. showToast('Error', err.message, 'error');
  11052. }
  11053. }
  11054. async function toggleRoutingFilterState(id, disabled) {
  11055. try {
  11056. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11057. method: 'POST',
  11058. headers: { 'Content-Type': 'application/json' },
  11059. body: JSON.stringify({ disabled })
  11060. });
  11061. if (res.ok) {
  11062. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11063. loadDynamicRouting();
  11064. } else {
  11065. const err = await res.json();
  11066. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  11067. }
  11068. } catch (err) {
  11069. showToast('Error', err.message, 'error');
  11070. }
  11071. }
  11072. // -------------------------------------------------------------
  11073. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  11074. // -------------------------------------------------------------
  11075. function openAddSelectRuleModal() {
  11076. document.getElementById('modal-rf-sr-id').value = '';
  11077. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  11078. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  11079. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  11080. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  11081. document.getElementById('modal-rf-sr-comment').value = '';
  11082. document.getElementById('modal-rf-sr-disabled').checked = false;
  11083. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11084. }
  11085. function openEditSelectRuleModal(id) {
  11086. const r = (state.routingSelectRules || []).find(item => item.id === id);
  11087. if (!r) return;
  11088. document.getElementById('modal-rf-sr-id').value = r.id;
  11089. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  11090. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  11091. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  11092. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  11093. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  11094. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  11095. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  11096. }
  11097. function closeSelectRuleModal() {
  11098. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  11099. }
  11100. async function submitSelectRule(e) {
  11101. e.preventDefault();
  11102. const payload = {
  11103. id: document.getElementById('modal-rf-sr-id').value,
  11104. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  11105. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  11106. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  11107. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11108. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11109. };
  11110. try {
  11111. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11112. method: 'POST',
  11113. headers: { 'Content-Type': 'application/json' },
  11114. body: JSON.stringify(payload)
  11115. });
  11116. if (res.ok) {
  11117. closeSelectRuleModal();
  11118. showToast('Success', 'Select rule saved', 'success');
  11119. loadDynamicRouting();
  11120. } else {
  11121. const err = await res.json();
  11122. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11123. }
  11124. } catch (err) {
  11125. showToast('Error', err.message, 'error');
  11126. }
  11127. }
  11128. async function deleteSelectRule(id) {
  11129. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11130. try {
  11131. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11132. if (res.ok) {
  11133. showToast('Deleted', 'Select rule removed', 'info');
  11134. loadDynamicRouting();
  11135. } else {
  11136. const err = await res.json();
  11137. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11138. }
  11139. } catch (err) {
  11140. showToast('Error', err.message, 'error');
  11141. }
  11142. }
  11143. async function toggleSelectRuleState(id, disabled) {
  11144. try {
  11145. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11146. method: 'POST',
  11147. headers: { 'Content-Type': 'application/json' },
  11148. body: JSON.stringify({ disabled })
  11149. });
  11150. if (res.ok) {
  11151. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11152. loadDynamicRouting();
  11153. } else {
  11154. const err = await res.json();
  11155. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11156. }
  11157. } catch (err) {
  11158. showToast('Error', err.message, 'error');
  11159. }
  11160. }
  11161. // -------------------------------------------------------------
  11162. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11163. // -------------------------------------------------------------
  11164. function openAddCommunityListModal() {
  11165. document.getElementById('modal-rf-cl-id').value = '';
  11166. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11167. document.getElementById('modal-rf-cl-name').value = '';
  11168. document.getElementById('modal-rf-cl-communities').value = '';
  11169. document.getElementById('modal-rf-cl-regexp').value = '';
  11170. document.getElementById('modal-rf-cl-comment').value = '';
  11171. document.getElementById('modal-rf-cl-disabled').checked = false;
  11172. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11173. }
  11174. function openEditCommunityListModal(id) {
  11175. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11176. if (!cl) return;
  11177. document.getElementById('modal-rf-cl-id').value = cl.id;
  11178. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11179. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11180. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11181. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11182. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11183. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11184. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11185. }
  11186. function closeCommunityListModal() {
  11187. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11188. }
  11189. async function submitCommunityList(e) {
  11190. e.preventDefault();
  11191. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11192. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11193. const payload = {
  11194. id: document.getElementById('modal-rf-cl-id').value,
  11195. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11196. communities: comms,
  11197. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11198. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11199. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11200. };
  11201. try {
  11202. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11203. method: 'POST',
  11204. headers: { 'Content-Type': 'application/json' },
  11205. body: JSON.stringify(payload)
  11206. });
  11207. if (res.ok) {
  11208. closeCommunityListModal();
  11209. showToast('Success', 'Community list saved', 'success');
  11210. loadDynamicRouting();
  11211. } else {
  11212. const err = await res.json();
  11213. showToast('Error', err.error || 'Failed to save community list', 'error');
  11214. }
  11215. } catch (err) {
  11216. showToast('Error', err.message, 'error');
  11217. }
  11218. }
  11219. async function deleteCommunityList(id) {
  11220. if (!confirm('Are you sure you want to delete this community list?')) return;
  11221. try {
  11222. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11223. if (res.ok) {
  11224. showToast('Deleted', 'Community list removed', 'info');
  11225. loadDynamicRouting();
  11226. } else {
  11227. const err = await res.json();
  11228. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11229. }
  11230. } catch (err) {
  11231. showToast('Error', err.message, 'error');
  11232. }
  11233. }
  11234. async function toggleCommunityListState(id, disabled) {
  11235. try {
  11236. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11237. method: 'POST',
  11238. headers: { 'Content-Type': 'application/json' },
  11239. body: JSON.stringify({ disabled })
  11240. });
  11241. if (res.ok) {
  11242. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11243. loadDynamicRouting();
  11244. } else {
  11245. const err = await res.json();
  11246. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11247. }
  11248. } catch (err) {
  11249. showToast('Error', err.message, 'error');
  11250. }
  11251. }
  11252. // -------------------------------------------------------------
  11253. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11254. // -------------------------------------------------------------
  11255. function openAddASListModal() {
  11256. document.getElementById('modal-rf-al-id').value = '';
  11257. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11258. document.getElementById('modal-rf-al-name').value = '';
  11259. document.getElementById('modal-rf-al-range').value = '';
  11260. document.getElementById('modal-rf-al-comment').value = '';
  11261. document.getElementById('modal-rf-al-disabled').checked = false;
  11262. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11263. }
  11264. function openEditASListModal(id) {
  11265. const al = (state.routingASLists || []).find(item => item.id === id);
  11266. if (!al) return;
  11267. document.getElementById('modal-rf-al-id').value = al.id;
  11268. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11269. document.getElementById('modal-rf-al-name').value = al.name || '';
  11270. document.getElementById('modal-rf-al-range').value = al.range || '';
  11271. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11272. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11273. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11274. }
  11275. function closeASListModal() {
  11276. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11277. }
  11278. async function submitASList(e) {
  11279. e.preventDefault();
  11280. const payload = {
  11281. id: document.getElementById('modal-rf-al-id').value,
  11282. name: document.getElementById('modal-rf-al-name').value.trim(),
  11283. range: document.getElementById('modal-rf-al-range').value.trim(),
  11284. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11285. disabled: document.getElementById('modal-rf-al-disabled').checked
  11286. };
  11287. try {
  11288. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11289. method: 'POST',
  11290. headers: { 'Content-Type': 'application/json' },
  11291. body: JSON.stringify(payload)
  11292. });
  11293. if (res.ok) {
  11294. closeASListModal();
  11295. showToast('Success', 'AS number list saved', 'success');
  11296. loadDynamicRouting();
  11297. } else {
  11298. const err = await res.json();
  11299. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11300. }
  11301. } catch (err) {
  11302. showToast('Error', err.message, 'error');
  11303. }
  11304. }
  11305. async function deleteASList(id) {
  11306. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11307. try {
  11308. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11309. if (res.ok) {
  11310. showToast('Deleted', 'AS list removed', 'info');
  11311. loadDynamicRouting();
  11312. } else {
  11313. const err = await res.json();
  11314. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11315. }
  11316. } catch (err) {
  11317. showToast('Error', err.message, 'error');
  11318. }
  11319. }
  11320. async function toggleASListState(id, disabled) {
  11321. try {
  11322. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11323. method: 'POST',
  11324. headers: { 'Content-Type': 'application/json' },
  11325. body: JSON.stringify({ disabled })
  11326. });
  11327. if (res.ok) {
  11328. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11329. loadDynamicRouting();
  11330. } else {
  11331. const err = await res.json();
  11332. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11333. }
  11334. } catch (err) {
  11335. showToast('Error', err.message, 'error');
  11336. }
  11337. }
  11338. // ==========================================
  11339. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11340. // ==========================================
  11341. function loadToolsView() {
  11342. populateToolsInterfaces();
  11343. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11344. }
  11345. function populateToolsInterfaces() {
  11346. const pingSel = document.getElementById('tools-ping-iface');
  11347. const traceSel = document.getElementById('tools-tr-iface');
  11348. let opts = '<option value="">Auto (Default Route)</option>';
  11349. if (Array.isArray(state.interfaces)) {
  11350. state.interfaces.forEach(iface => {
  11351. if (iface.name) {
  11352. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11353. }
  11354. });
  11355. }
  11356. if (pingSel) {
  11357. const cur = pingSel.value;
  11358. pingSel.innerHTML = opts;
  11359. if (cur) pingSel.value = cur;
  11360. }
  11361. if (traceSel) {
  11362. const cur = traceSel.value;
  11363. traceSel.innerHTML = opts;
  11364. if (cur) traceSel.value = cur;
  11365. }
  11366. }
  11367. function switchToolsSubTab(subTab) {
  11368. state.activeToolsSubTab = subTab;
  11369. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11370. tabs.forEach(t => {
  11371. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11372. const view = document.getElementById(`tools-view-${t}`);
  11373. if (btn) {
  11374. if (t === subTab) {
  11375. 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';
  11376. } else {
  11377. 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';
  11378. }
  11379. }
  11380. if (view) {
  11381. if (t === subTab) {
  11382. view.classList.remove('hidden');
  11383. } else {
  11384. view.classList.add('hidden');
  11385. }
  11386. }
  11387. });
  11388. }
  11389. function setPortPreset(port) {
  11390. const input = document.getElementById('tools-port-num');
  11391. if (input) input.value = port;
  11392. }
  11393. let pingAbortController = null;
  11394. let tracerouteAbortController = null;
  11395. function clearPingTable() {
  11396. const tbody = document.getElementById('tools-ping-tbody');
  11397. if (tbody) tbody.innerHTML = '';
  11398. const rawEl = document.getElementById('tools-ping-raw');
  11399. if (rawEl) rawEl.innerText = '';
  11400. const sentEl = document.getElementById('tools-ping-stat-sent');
  11401. if (sentEl) sentEl.innerText = '0';
  11402. const recvEl = document.getElementById('tools-ping-stat-recv');
  11403. if (recvEl) recvEl.innerText = '0';
  11404. const lossEl = document.getElementById('tools-ping-stat-loss');
  11405. if (lossEl) lossEl.innerText = '0%';
  11406. const avgEl = document.getElementById('tools-ping-stat-avg');
  11407. if (avgEl) avgEl.innerText = '0 ms';
  11408. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11409. if (minMaxEl) minMaxEl.innerText = '-';
  11410. const badge = document.getElementById('tools-ping-status-badge');
  11411. if (badge) {
  11412. badge.className = '';
  11413. badge.innerText = '';
  11414. }
  11415. }
  11416. function clearTracerouteTable() {
  11417. const tbody = document.getElementById('tools-tr-tbody');
  11418. if (tbody) tbody.innerHTML = '';
  11419. const rawEl = document.getElementById('tools-tr-raw');
  11420. if (rawEl) rawEl.innerText = '';
  11421. const statHops = document.getElementById('tools-tr-hops-count');
  11422. if (statHops) statHops.innerText = '0 Hops';
  11423. }
  11424. function resetPingButton() {
  11425. const btn = document.getElementById('tools-ping-btn');
  11426. const btnText = document.getElementById('tools-ping-btn-text');
  11427. const spinner = document.getElementById('tools-ping-spinner');
  11428. if (btn) {
  11429. btn.disabled = false;
  11430. 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';
  11431. }
  11432. if (btnText) btnText.innerText = 'Start Ping';
  11433. if (spinner) spinner.classList.add('hidden');
  11434. }
  11435. function setPingRunningButton() {
  11436. const btn = document.getElementById('tools-ping-btn');
  11437. const btnText = document.getElementById('tools-ping-btn-text');
  11438. const spinner = document.getElementById('tools-ping-spinner');
  11439. if (btn) {
  11440. btn.disabled = false;
  11441. 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';
  11442. }
  11443. if (btnText) btnText.innerText = 'Stop Ping';
  11444. if (spinner) spinner.classList.remove('hidden');
  11445. }
  11446. function resetTracerouteButton() {
  11447. const btn = document.getElementById('tools-tr-btn');
  11448. const btnText = document.getElementById('tools-tr-btn-text');
  11449. const spinner = document.getElementById('tools-tr-spinner');
  11450. if (btn) {
  11451. btn.disabled = false;
  11452. 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';
  11453. }
  11454. if (btnText) btnText.innerText = 'Start Traceroute';
  11455. if (spinner) spinner.classList.add('hidden');
  11456. }
  11457. function setTracerouteRunningButton() {
  11458. const btn = document.getElementById('tools-tr-btn');
  11459. const btnText = document.getElementById('tools-tr-btn-text');
  11460. const spinner = document.getElementById('tools-tr-spinner');
  11461. if (btn) {
  11462. btn.disabled = false;
  11463. 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';
  11464. }
  11465. if (btnText) btnText.innerText = 'Stop Traceroute';
  11466. if (spinner) spinner.classList.remove('hidden');
  11467. }
  11468. async function executePing(e) {
  11469. if (e) e.preventDefault();
  11470. // If already running, clicking the button stops the stream!
  11471. if (pingAbortController) {
  11472. pingAbortController.abort();
  11473. pingAbortController = null;
  11474. resetPingButton();
  11475. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11476. return;
  11477. }
  11478. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11479. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11480. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11481. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11482. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11483. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11484. if (!target) {
  11485. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11486. return;
  11487. }
  11488. clearPingTable();
  11489. const resCard = document.getElementById('tools-ping-results');
  11490. if (resCard) resCard.classList.remove('hidden');
  11491. pingAbortController = new AbortController();
  11492. setPingRunningButton();
  11493. try {
  11494. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11495. method: 'POST',
  11496. headers: { 'Content-Type': 'application/json' },
  11497. body: JSON.stringify({
  11498. target,
  11499. count,
  11500. size,
  11501. timeout,
  11502. interface: iface,
  11503. dont_frag: dontFrag
  11504. }),
  11505. signal: pingAbortController.signal
  11506. });
  11507. if (!res.ok) {
  11508. const errText = await res.text();
  11509. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11510. resetPingButton();
  11511. pingAbortController = null;
  11512. return;
  11513. }
  11514. const reader = res.body.getReader();
  11515. const decoder = new TextDecoder('utf-8');
  11516. let buffer = '';
  11517. while (true) {
  11518. const { done, value } = await reader.read();
  11519. if (done) break;
  11520. buffer += decoder.decode(value, { stream: true });
  11521. const blocks = buffer.split('\n\n');
  11522. buffer = blocks.pop() || '';
  11523. for (const block of blocks) {
  11524. const trimmed = block.trim();
  11525. if (!trimmed) continue;
  11526. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11527. try {
  11528. const evt = JSON.parse(line);
  11529. handleLivePingEvent(evt);
  11530. } catch (parseErr) {
  11531. console.warn('Ping SSE parse error:', parseErr, line);
  11532. }
  11533. }
  11534. }
  11535. } catch (err) {
  11536. if (err.name === 'AbortError') {
  11537. // User aborted normally
  11538. } else {
  11539. showToast('Ping Error', err.message, 'error');
  11540. }
  11541. } finally {
  11542. pingAbortController = null;
  11543. resetPingButton();
  11544. }
  11545. }
  11546. function handleLivePingEvent(evt) {
  11547. const sentEl = document.getElementById('tools-ping-stat-sent');
  11548. const recvEl = document.getElementById('tools-ping-stat-recv');
  11549. const lossEl = document.getElementById('tools-ping-stat-loss');
  11550. const avgEl = document.getElementById('tools-ping-stat-avg');
  11551. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11552. const badge = document.getElementById('tools-ping-status-badge');
  11553. const tbody = document.getElementById('tools-ping-tbody');
  11554. const rawEl = document.getElementById('tools-ping-raw');
  11555. if (evt.raw && rawEl) {
  11556. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11557. rawEl.scrollTop = rawEl.scrollHeight;
  11558. }
  11559. if (evt.type === 'reply') {
  11560. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11561. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11562. if (lossEl && evt.packet_loss_pct !== undefined) {
  11563. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11564. lossEl.className = evt.packet_loss_pct === 0
  11565. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11566. : (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');
  11567. }
  11568. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11569. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11570. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11571. }
  11572. if (badge) {
  11573. if (evt.packet_loss_pct === 0) {
  11574. 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';
  11575. badge.innerText = '100% OK';
  11576. } else {
  11577. 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';
  11578. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11579. }
  11580. }
  11581. if (tbody) {
  11582. const tr = document.createElement('tr');
  11583. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11584. tr.innerHTML = `
  11585. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11586. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11587. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11588. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11589. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11590. <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>
  11591. `;
  11592. tbody.appendChild(tr);
  11593. }
  11594. } else if (evt.type === 'timeout') {
  11595. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11596. if (lossEl && evt.packet_loss_pct !== undefined) {
  11597. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11598. 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';
  11599. }
  11600. if (badge) {
  11601. 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';
  11602. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11603. }
  11604. if (tbody) {
  11605. const tr = document.createElement('tr');
  11606. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11607. tr.innerHTML = `
  11608. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11609. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11610. <td class="py-2 px-3 text-slate-600">--</td>
  11611. <td class="py-2 px-3 text-slate-600">--</td>
  11612. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11613. <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>
  11614. `;
  11615. tbody.appendChild(tr);
  11616. }
  11617. } else if (evt.type === 'unreach') {
  11618. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11619. if (lossEl && evt.packet_loss_pct !== undefined) {
  11620. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11621. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11622. }
  11623. if (badge) {
  11624. 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';
  11625. badge.innerText = 'UNREACHABLE';
  11626. }
  11627. if (tbody) {
  11628. const tr = document.createElement('tr');
  11629. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11630. tr.innerHTML = `
  11631. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11632. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11633. <td class="py-2 px-3 text-slate-600">--</td>
  11634. <td class="py-2 px-3 text-slate-600">--</td>
  11635. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11636. <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>
  11637. `;
  11638. tbody.appendChild(tr);
  11639. }
  11640. } else if (evt.type === 'stats') {
  11641. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11642. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11643. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11644. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11645. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11646. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11647. }
  11648. } else if (evt.type === 'done') {
  11649. 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');
  11650. }
  11651. }
  11652. async function executeTraceroute(e) {
  11653. if (e) e.preventDefault();
  11654. if (tracerouteAbortController) {
  11655. tracerouteAbortController.abort();
  11656. tracerouteAbortController = null;
  11657. resetTracerouteButton();
  11658. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11659. return;
  11660. }
  11661. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11662. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11663. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11664. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11665. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11666. if (!target) {
  11667. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11668. return;
  11669. }
  11670. clearTracerouteTable();
  11671. const resCard = document.getElementById('tools-tr-results');
  11672. if (resCard) resCard.classList.remove('hidden');
  11673. tracerouteAbortController = new AbortController();
  11674. setTracerouteRunningButton();
  11675. try {
  11676. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11677. method: 'POST',
  11678. headers: { 'Content-Type': 'application/json' },
  11679. body: JSON.stringify({
  11680. target,
  11681. max_hops: maxHops,
  11682. protocol,
  11683. interface: iface,
  11684. resolve
  11685. }),
  11686. signal: tracerouteAbortController.signal
  11687. });
  11688. if (!res.ok) {
  11689. const errText = await res.text();
  11690. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11691. resetTracerouteButton();
  11692. tracerouteAbortController = null;
  11693. return;
  11694. }
  11695. const reader = res.body.getReader();
  11696. const decoder = new TextDecoder('utf-8');
  11697. let buffer = '';
  11698. while (true) {
  11699. const { done, value } = await reader.read();
  11700. if (done) break;
  11701. buffer += decoder.decode(value, { stream: true });
  11702. const blocks = buffer.split('\n\n');
  11703. buffer = blocks.pop() || '';
  11704. for (const block of blocks) {
  11705. const trimmed = block.trim();
  11706. if (!trimmed) continue;
  11707. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11708. try {
  11709. const evt = JSON.parse(line);
  11710. handleLiveTracerouteEvent(evt);
  11711. } catch (parseErr) {
  11712. console.warn('Traceroute SSE parse error:', parseErr, line);
  11713. }
  11714. }
  11715. }
  11716. } catch (err) {
  11717. if (err.name === 'AbortError') {
  11718. // User aborted normally
  11719. } else {
  11720. showToast('Traceroute Error', err.message, 'error');
  11721. }
  11722. } finally {
  11723. tracerouteAbortController = null;
  11724. resetTracerouteButton();
  11725. }
  11726. }
  11727. function handleLiveTracerouteEvent(evt) {
  11728. const statHops = document.getElementById('tools-tr-hops-count');
  11729. const tbody = document.getElementById('tools-tr-tbody');
  11730. const rawEl = document.getElementById('tools-tr-raw');
  11731. if (evt.raw && rawEl) {
  11732. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11733. rawEl.scrollTop = rawEl.scrollHeight;
  11734. }
  11735. if (evt.hops_count !== undefined && statHops) {
  11736. statHops.innerText = `${evt.hops_count} Hops`;
  11737. }
  11738. if (evt.type === 'hop' && evt.hop && tbody) {
  11739. const h = evt.hop;
  11740. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11741. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11742. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11743. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11744. const tr = document.createElement('tr');
  11745. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11746. tr.innerHTML = `
  11747. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11748. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11749. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11750. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11751. <td class="py-2.5 px-3 text-right">
  11752. ${isTimeout
  11753. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11754. : '<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>'}
  11755. </td>
  11756. `;
  11757. tbody.appendChild(tr);
  11758. } else if (evt.type === 'done') {
  11759. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11760. }
  11761. }
  11762. async function executeMTR(e) {
  11763. if (e) e.preventDefault();
  11764. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11765. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11766. if (!target) {
  11767. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11768. return;
  11769. }
  11770. const btn = document.getElementById('tools-mtr-btn');
  11771. const spinner = document.getElementById('tools-mtr-spinner');
  11772. if (btn) btn.disabled = true;
  11773. if (spinner) spinner.classList.remove('hidden');
  11774. try {
  11775. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11776. method: 'POST',
  11777. headers: { 'Content-Type': 'application/json' },
  11778. body: JSON.stringify({ target, count: cycles })
  11779. });
  11780. const data = await res.json();
  11781. if (!res.ok) {
  11782. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11783. return;
  11784. }
  11785. const resCard = document.getElementById('tools-mtr-results');
  11786. if (resCard) resCard.classList.remove('hidden');
  11787. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11788. const statHops = document.getElementById('tools-mtr-hops-count');
  11789. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11790. const tbody = document.getElementById('tools-mtr-tbody');
  11791. if (tbody) {
  11792. if (hopsCount > 0) {
  11793. tbody.innerHTML = data.hops.map(h => {
  11794. 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');
  11795. return `
  11796. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11797. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11798. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11799. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11800. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11801. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11802. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11803. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11804. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11805. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11806. </tr>
  11807. `;
  11808. }).join('');
  11809. } else {
  11810. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11811. }
  11812. }
  11813. const rawEl = document.getElementById('tools-mtr-raw');
  11814. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11815. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11816. } catch (err) {
  11817. showToast('MTR Error', err.message, 'error');
  11818. } finally {
  11819. if (btn) btn.disabled = false;
  11820. if (spinner) spinner.classList.add('hidden');
  11821. }
  11822. }
  11823. async function executeDNS(e) {
  11824. if (e) e.preventDefault();
  11825. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11826. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11827. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11828. if (!domain) {
  11829. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11830. return;
  11831. }
  11832. const btn = document.getElementById('tools-dns-btn');
  11833. const spinner = document.getElementById('tools-dns-spinner');
  11834. if (btn) btn.disabled = true;
  11835. if (spinner) spinner.classList.remove('hidden');
  11836. try {
  11837. const res = await fetch(`${API_BASE}/tools/dns`, {
  11838. method: 'POST',
  11839. headers: { 'Content-Type': 'application/json' },
  11840. body: JSON.stringify({ domain, type, server })
  11841. });
  11842. const data = await res.json();
  11843. if (!res.ok) {
  11844. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11845. return;
  11846. }
  11847. const resCard = document.getElementById('tools-dns-results');
  11848. if (resCard) resCard.classList.remove('hidden');
  11849. const metaEl = document.getElementById('tools-dns-meta');
  11850. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11851. const tbody = document.getElementById('tools-dns-tbody');
  11852. if (tbody) {
  11853. if (Array.isArray(data.records) && data.records.length > 0) {
  11854. tbody.innerHTML = data.records.map(r => `
  11855. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11856. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11857. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11858. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11859. <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>
  11860. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11861. </tr>
  11862. `).join('');
  11863. } else {
  11864. 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>`;
  11865. }
  11866. }
  11867. const rawEl = document.getElementById('tools-dns-raw');
  11868. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11869. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11870. } catch (err) {
  11871. showToast('DNS Error', err.message, 'error');
  11872. } finally {
  11873. if (btn) btn.disabled = false;
  11874. if (spinner) spinner.classList.add('hidden');
  11875. }
  11876. }
  11877. async function executePortProbe(e) {
  11878. if (e) e.preventDefault();
  11879. const target = document.getElementById('tools-port-target')?.value?.trim();
  11880. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11881. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11882. if (!target || !port) {
  11883. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11884. return;
  11885. }
  11886. const btn = document.getElementById('tools-port-btn');
  11887. const spinner = document.getElementById('tools-port-spinner');
  11888. if (btn) btn.disabled = true;
  11889. if (spinner) spinner.classList.remove('hidden');
  11890. try {
  11891. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11892. method: 'POST',
  11893. headers: { 'Content-Type': 'application/json' },
  11894. body: JSON.stringify({ target, port, timeout })
  11895. });
  11896. const data = await res.json();
  11897. if (!res.ok) {
  11898. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11899. return;
  11900. }
  11901. const resCard = document.getElementById('tools-port-results');
  11902. if (resCard) resCard.classList.remove('hidden');
  11903. const banner = document.getElementById('tools-port-banner');
  11904. const icon = document.getElementById('tools-port-icon');
  11905. const title = document.getElementById('tools-port-title');
  11906. const sub = document.getElementById('tools-port-sub');
  11907. const latency = document.getElementById('tools-port-latency');
  11908. if (data.open) {
  11909. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11910. if (icon) {
  11911. 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';
  11912. icon.innerText = '✓';
  11913. }
  11914. if (title) {
  11915. title.className = 'text-sm font-bold text-emerald-300';
  11916. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11917. }
  11918. if (sub) {
  11919. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11920. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11921. }
  11922. if (latency) {
  11923. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11924. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11925. }
  11926. } else {
  11927. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11928. if (icon) {
  11929. 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';
  11930. icon.innerText = '✕';
  11931. }
  11932. if (title) {
  11933. title.className = 'text-sm font-bold text-rose-300';
  11934. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11935. }
  11936. if (sub) {
  11937. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11938. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11939. }
  11940. if (latency) {
  11941. latency.className = 'text-base font-bold font-mono text-slate-500';
  11942. latency.innerText = '--';
  11943. }
  11944. }
  11945. const rawEl = document.getElementById('tools-port-raw');
  11946. 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'}`);
  11947. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11948. } catch (err) {
  11949. showToast('Probe Error', err.message, 'error');
  11950. } finally {
  11951. if (btn) btn.disabled = false;
  11952. if (spinner) spinner.classList.add('hidden');
  11953. }
  11954. }
  11955. // ==========================================
  11956. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11957. // ==========================================
  11958. async function loadDHCPClients(showToastMsg = false) {
  11959. try {
  11960. const [clientsRes, sumRes] = await Promise.all([
  11961. fetch(`${API_BASE}/dhcp/clients`),
  11962. fetch(`${API_BASE}/dhcp/clients/summary`)
  11963. ]);
  11964. if (clientsRes.ok) {
  11965. state.dhcpClients = await clientsRes.json();
  11966. }
  11967. if (sumRes.ok) {
  11968. state.dhcpSummary = await sumRes.json();
  11969. }
  11970. renderDHCPClients();
  11971. updateDHCPSummaryCards();
  11972. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11973. if (bDhcp && state.dhcpSummary) {
  11974. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11975. }
  11976. if (showToastMsg) {
  11977. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11978. }
  11979. } catch (err) {
  11980. console.error('Failed to load DHCP clients:', err);
  11981. if (showToastMsg) {
  11982. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11983. }
  11984. }
  11985. }
  11986. function updateDHCPSummaryCards() {
  11987. const sum = state.dhcpSummary || {
  11988. total_clients: (state.dhcpClients || []).length,
  11989. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11990. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11991. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11992. };
  11993. const totalEl = document.getElementById('dhcp-stat-total');
  11994. const boundEl = document.getElementById('dhcp-stat-bound');
  11995. const searchEl = document.getElementById('dhcp-stat-searching');
  11996. const disEl = document.getElementById('dhcp-stat-disabled');
  11997. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11998. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11999. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12000. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12001. }
  12002. function renderDHCPClients() {
  12003. const tbody = document.getElementById('dhcp-clients-tbody');
  12004. const emptyState = document.getElementById('dhcp-clients-empty');
  12005. if (!tbody) return;
  12006. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12007. if (clients.length === 0) {
  12008. tbody.innerHTML = '';
  12009. if (emptyState) emptyState.classList.remove('hidden');
  12010. return;
  12011. }
  12012. if (emptyState) emptyState.classList.add('hidden');
  12013. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12014. if (tbody.dataset.sig === sig) return;
  12015. tbody.dataset.sig = sig;
  12016. tbody.innerHTML = clients.map(c => {
  12017. let statusBadge = '';
  12018. if (!c.enabled) {
  12019. 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>';
  12020. } else if (c.status === 'bound') {
  12021. 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>';
  12022. } else if (c.status === 'searching') {
  12023. 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>';
  12024. } else if (c.status === 'stopped') {
  12025. 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>';
  12026. } else {
  12027. 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>`;
  12028. }
  12029. 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>';
  12030. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12031. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12032. 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>';
  12033. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12034. // Option flags
  12035. const flags = [];
  12036. 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>');
  12037. 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>');
  12038. 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>');
  12039. 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>`);
  12040. return `
  12041. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12042. <td class="py-3 px-4">
  12043. <div class="flex items-center gap-2">
  12044. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12045. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12046. </div>
  12047. </td>
  12048. <td class="py-3 px-4">${statusBadge}</td>
  12049. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12050. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12051. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12052. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12053. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12054. <td class="py-3 px-4">
  12055. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12056. </td>
  12057. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12058. ${c.enabled ? `
  12059. <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>
  12060. <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>
  12061. <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>
  12062. ` : `
  12063. <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>
  12064. `}
  12065. <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>
  12066. <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>
  12067. </td>
  12068. </tr>
  12069. `;
  12070. }).join('');
  12071. }
  12072. function openDHCPClientModal(clientId = null) {
  12073. const modal = document.getElementById('modal-dhcp-client');
  12074. if (!modal) return;
  12075. const title = document.getElementById('modal-dhcp-title');
  12076. const idInput = document.getElementById('modal-dhcp-id');
  12077. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12078. const distInput = document.getElementById('modal-dhcp-distance');
  12079. const commentInput = document.getElementById('modal-dhcp-comment');
  12080. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12081. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12082. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12083. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12084. // Populate interfaces
  12085. if (ifaceSelect) {
  12086. let opts = '<option value="">Select interface...</option>';
  12087. const allIfaces = state.interfaces || [];
  12088. const allVlans = state.vlans || [];
  12089. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12090. // Group 1: Physical & Bridge Interfaces
  12091. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12092. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12093. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12094. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12095. });
  12096. opts += '</optgroup>';
  12097. // Group 2: VLAN Interfaces
  12098. if (allVlans.length > 0) {
  12099. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12100. allVlans.forEach(v => {
  12101. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12102. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12103. });
  12104. opts += '</optgroup>';
  12105. }
  12106. ifaceSelect.innerHTML = opts;
  12107. }
  12108. if (clientId) {
  12109. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12110. if (client) {
  12111. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12112. if (idInput) idInput.value = client.id;
  12113. if (ifaceSelect) {
  12114. ifaceSelect.value = client.interface;
  12115. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12116. }
  12117. if (distInput) distInput.value = client.default_route_distance || 1;
  12118. if (commentInput) commentInput.value = client.comment || '';
  12119. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12120. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12121. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12122. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12123. }
  12124. } else {
  12125. if (title) title.innerText = 'Add DHCP Client';
  12126. if (idInput) idInput.value = '';
  12127. if (ifaceSelect) {
  12128. ifaceSelect.value = '';
  12129. ifaceSelect.disabled = false;
  12130. }
  12131. if (distInput) distInput.value = 1;
  12132. if (commentInput) commentInput.value = '';
  12133. if (defRouteCheck) defRouteCheck.checked = true;
  12134. if (peerDnsCheck) peerDnsCheck.checked = true;
  12135. if (peerNtpCheck) peerNtpCheck.checked = true;
  12136. if (enabledCheck) enabledCheck.checked = true;
  12137. }
  12138. modal.classList.remove('hidden');
  12139. }
  12140. function openDHCPClientModalForIface(ifaceName) {
  12141. openDHCPClientModal();
  12142. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12143. if (ifaceSelect && ifaceName) {
  12144. ifaceSelect.value = ifaceName;
  12145. }
  12146. }
  12147. function closeDHCPClientModal() {
  12148. const modal = document.getElementById('modal-dhcp-client');
  12149. if (modal) modal.classList.add('hidden');
  12150. }
  12151. async function submitSaveDHCPClient(e) {
  12152. if (e) e.preventDefault();
  12153. const id = document.getElementById('modal-dhcp-id')?.value;
  12154. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12155. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12156. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12157. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12158. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12159. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12160. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12161. if (!id && !iface) {
  12162. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12163. return;
  12164. }
  12165. try {
  12166. let res;
  12167. if (id) {
  12168. // PUT update
  12169. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12170. method: 'PUT',
  12171. headers: { 'Content-Type': 'application/json' },
  12172. body: JSON.stringify({
  12173. enabled,
  12174. add_default_route: defRoute,
  12175. default_route_distance: distance,
  12176. use_peer_dns: peerDns,
  12177. use_peer_ntp: peerNtp,
  12178. comment
  12179. })
  12180. });
  12181. } else {
  12182. // POST create
  12183. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12184. method: 'POST',
  12185. headers: { 'Content-Type': 'application/json' },
  12186. body: JSON.stringify({
  12187. interface: iface,
  12188. enabled,
  12189. add_default_route: defRoute,
  12190. default_route_distance: distance,
  12191. use_peer_dns: peerDns,
  12192. use_peer_ntp: peerNtp,
  12193. comment
  12194. })
  12195. });
  12196. }
  12197. const data = await res.json();
  12198. if (!res.ok) {
  12199. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12200. return;
  12201. }
  12202. closeDHCPClientModal();
  12203. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12204. await loadDHCPClients();
  12205. fetchData(); // refresh interfaces list with new lease/status
  12206. } catch (err) {
  12207. showToast('Error', err.message, 'error');
  12208. }
  12209. }
  12210. async function toggleDHCPClientState(id, enabled) {
  12211. try {
  12212. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12213. method: 'POST',
  12214. headers: { 'Content-Type': 'application/json' },
  12215. body: JSON.stringify({ enabled })
  12216. });
  12217. const data = await res.json();
  12218. if (!res.ok) {
  12219. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12220. return;
  12221. }
  12222. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12223. await loadDHCPClients();
  12224. fetchData();
  12225. } catch (err) {
  12226. showToast('Error', err.message, 'error');
  12227. }
  12228. }
  12229. async function renewDHCPClient(id) {
  12230. try {
  12231. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12232. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12233. method: 'POST'
  12234. });
  12235. const data = await res.json();
  12236. if (!res.ok) {
  12237. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12238. return;
  12239. }
  12240. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12241. setTimeout(() => {
  12242. loadDHCPClients();
  12243. fetchData();
  12244. }, 1500);
  12245. } catch (err) {
  12246. showToast('Error', err.message, 'error');
  12247. }
  12248. }
  12249. async function releaseDHCPClient(id) {
  12250. try {
  12251. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12252. method: 'POST'
  12253. });
  12254. const data = await res.json();
  12255. if (!res.ok) {
  12256. showToast('Error', data.error || 'Failed to release lease', 'error');
  12257. return;
  12258. }
  12259. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12260. await loadDHCPClients();
  12261. fetchData();
  12262. } catch (err) {
  12263. showToast('Error', err.message, 'error');
  12264. }
  12265. }
  12266. async function deleteDHCPClient(id, ifaceName) {
  12267. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12268. return;
  12269. }
  12270. try {
  12271. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12272. method: 'DELETE'
  12273. });
  12274. const data = await res.json();
  12275. if (!res.ok) {
  12276. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12277. return;
  12278. }
  12279. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12280. await loadDHCPClients();
  12281. fetchData();
  12282. } catch (err) {
  12283. showToast('Error', err.message, 'error');
  12284. }
  12285. }
  12286. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12287. async function loadDHCPServer(populate = true) {
  12288. try {
  12289. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12290. fetch(`${API_BASE}/dhcp-server/summary`),
  12291. fetch(`${API_BASE}/dhcp-server/servers`),
  12292. fetch(`${API_BASE}/dhcp-server/networks`),
  12293. fetch(`${API_BASE}/dhcp-server/leases`),
  12294. fetch(`${API_BASE}/dhcp-server/options`)
  12295. ]);
  12296. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12297. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12298. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12299. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12300. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12301. const sum = state.dhcpServerSummary || {};
  12302. const srvs = state.dhcpServers || [];
  12303. const nets = state.dhcpNetworks || [];
  12304. const leases = state.dhcpLeases || [];
  12305. const opts = state.dhcpOptions || [];
  12306. // KPI Cards
  12307. const statActive = document.getElementById('dhcp-server-stat-active');
  12308. if (statActive) {
  12309. const activeCount = srvs.filter(s => s.running).length;
  12310. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12311. }
  12312. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12313. if (statLeases) {
  12314. statLeases.innerText = leases.length;
  12315. }
  12316. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12317. if (statLeasesSub) {
  12318. const dyn = leases.filter(l => l.dynamic).length;
  12319. const st = leases.filter(l => !l.dynamic).length;
  12320. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12321. }
  12322. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12323. if (statNetworks) {
  12324. statNetworks.innerText = nets.length;
  12325. }
  12326. // Subtab Badges
  12327. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12328. if (bSrv) bSrv.innerText = srvs.length;
  12329. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12330. if (bNet) bNet.innerText = nets.length;
  12331. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12332. if (bLease) bLease.innerText = leases.length;
  12333. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12334. if (bOpt) bOpt.innerText = opts.length;
  12335. // Sidebar Badge
  12336. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12337. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12338. renderCurrentDHCPServerTab();
  12339. } catch (err) {
  12340. console.error('Failed to load DHCP Server:', err);
  12341. }
  12342. }
  12343. function switchDHCPServerTab(tab) {
  12344. state.dhcpServerTab = tab;
  12345. const tabs = ['servers', 'networks', 'leases', 'options'];
  12346. tabs.forEach(t => {
  12347. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12348. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12349. if (panel) {
  12350. if (t === tab) panel.classList.remove('hidden');
  12351. else panel.classList.add('hidden');
  12352. }
  12353. if (btn) {
  12354. if (t === tab) {
  12355. 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';
  12356. } else {
  12357. 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';
  12358. }
  12359. }
  12360. });
  12361. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12362. if (addBtn) {
  12363. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12364. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12365. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12366. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12367. }
  12368. renderCurrentDHCPServerTab();
  12369. }
  12370. function handleDHCPServerPrimaryAdd() {
  12371. const tab = state.dhcpServerTab || 'servers';
  12372. if (tab === 'servers') openAddDHCPServerModal();
  12373. else if (tab === 'networks') openAddDHCPNetworkModal();
  12374. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12375. else if (tab === 'options') openAddDHCPOptionModal();
  12376. }
  12377. function renderCurrentDHCPServerTab() {
  12378. const tab = state.dhcpServerTab || 'servers';
  12379. if (tab === 'servers') renderDHCPServers();
  12380. else if (tab === 'networks') renderDHCPNetworks();
  12381. else if (tab === 'leases') renderDHCPLeases();
  12382. else if (tab === 'options') renderDHCPOptions();
  12383. }
  12384. function renderDHCPServers() {
  12385. const tbody = document.getElementById('dhcp-server-tbody');
  12386. const empty = document.getElementById('dhcp-server-empty');
  12387. if (!tbody) return;
  12388. const servers = state.dhcpServers || [];
  12389. if (servers.length === 0) {
  12390. tbody.innerHTML = '';
  12391. empty?.classList.remove('hidden');
  12392. return;
  12393. }
  12394. empty?.classList.add('hidden');
  12395. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12396. if (tbody.dataset.sig === sig) return;
  12397. tbody.dataset.sig = sig;
  12398. tbody.innerHTML = '';
  12399. servers.forEach(s => {
  12400. const tr = document.createElement('tr');
  12401. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12402. tr.innerHTML = `
  12403. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12404. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12405. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12406. <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>
  12407. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12408. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12409. <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>
  12410. <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>
  12411. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12412. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12413. <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>
  12414. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12415. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12416. </td>
  12417. `;
  12418. tbody.appendChild(tr);
  12419. });
  12420. }
  12421. function renderDHCPNetworks() {
  12422. const tbody = document.getElementById('dhcp-networks-tbody');
  12423. const empty = document.getElementById('dhcp-networks-empty');
  12424. if (!tbody) return;
  12425. tbody.innerHTML = '';
  12426. const networks = state.dhcpNetworks || [];
  12427. if (networks.length === 0) {
  12428. empty?.classList.remove('hidden');
  12429. return;
  12430. }
  12431. empty?.classList.add('hidden');
  12432. networks.forEach(n => {
  12433. const tr = document.createElement('tr');
  12434. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12435. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12436. const optionsChips = (n.dhcp_options || []).map(optId => {
  12437. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12438. if (!opt) return '';
  12439. 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>`;
  12440. }).filter(Boolean).join('');
  12441. tr.innerHTML = `
  12442. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12443. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12444. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12445. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12446. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12447. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12448. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12449. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12450. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12451. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12452. </td>
  12453. `;
  12454. tbody.appendChild(tr);
  12455. });
  12456. }
  12457. function renderDHCPLeases() {
  12458. const tbody = document.getElementById('dhcp-leases-tbody');
  12459. const empty = document.getElementById('dhcp-leases-empty');
  12460. if (!tbody) return;
  12461. tbody.innerHTML = '';
  12462. const leases = state.dhcpLeases || [];
  12463. if (leases.length === 0) {
  12464. empty?.classList.remove('hidden');
  12465. return;
  12466. }
  12467. empty?.classList.add('hidden');
  12468. leases.forEach(l => {
  12469. const tr = document.createElement('tr');
  12470. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12471. 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>';
  12472. const statusBadge = l.status === 'bound'
  12473. ? '<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>'
  12474. : l.status === 'static'
  12475. ? '<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>'
  12476. : '<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>';
  12477. const makeStaticBtn = l.dynamic
  12478. ? `<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>`
  12479. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12480. tr.innerHTML = `
  12481. <td class="py-2.5 px-3 text-center">${flag}</td>
  12482. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12483. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12484. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12485. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12486. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12487. <td class="py-2.5 px-3">${statusBadge}</td>
  12488. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12489. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12490. ${makeStaticBtn}
  12491. </td>
  12492. `;
  12493. tbody.appendChild(tr);
  12494. });
  12495. }
  12496. function renderDHCPOptions() {
  12497. const tbody = document.getElementById('dhcp-options-tbody');
  12498. const empty = document.getElementById('dhcp-options-empty');
  12499. if (!tbody) return;
  12500. tbody.innerHTML = '';
  12501. const options = state.dhcpOptions || [];
  12502. if (options.length === 0) {
  12503. empty?.classList.remove('hidden');
  12504. return;
  12505. }
  12506. empty?.classList.add('hidden');
  12507. options.forEach(o => {
  12508. const tr = document.createElement('tr');
  12509. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12510. tr.innerHTML = `
  12511. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12512. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12513. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12514. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12515. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12516. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12517. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12518. </td>
  12519. `;
  12520. tbody.appendChild(tr);
  12521. });
  12522. }
  12523. // ==================== MODALS & ACTIONS: SERVER ====================
  12524. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12525. const sel = document.getElementById(elemId);
  12526. if (!sel) return;
  12527. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12528. const networks = state.dhcpNetworks || [];
  12529. networks.forEach(n => {
  12530. const opt = document.createElement('option');
  12531. opt.value = n.address;
  12532. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12533. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12534. opt.selected = true;
  12535. }
  12536. sel.appendChild(opt);
  12537. });
  12538. }
  12539. function onDHCPServerNetworkChange() {
  12540. const netSel = document.getElementById('dhcp-server-modal-network');
  12541. if (!netSel) return;
  12542. const netVal = netSel.value;
  12543. if (!netVal) return;
  12544. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12545. if (!poolInput) return;
  12546. // Auto-calculate suggested address pool based on subnet CIDR
  12547. const parts = netVal.split('/');
  12548. const ip = parts[0];
  12549. const cidr = parseInt(parts[1] || '24', 10);
  12550. if (cidr === 24) {
  12551. const octets = ip.split('.');
  12552. if (octets.length === 4) {
  12553. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12554. poolInput.value = `${base}.10-${base}.254`;
  12555. }
  12556. }
  12557. }
  12558. function openAddDHCPServerModal() {
  12559. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12560. document.getElementById('dhcp-server-modal-id').value = '';
  12561. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12562. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12563. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12564. document.getElementById('dhcp-server-modal-comment').value = '';
  12565. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12566. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12567. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12568. const networks = state.dhcpNetworks || [];
  12569. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12570. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12571. if (defaultNet) {
  12572. onDHCPServerNetworkChange();
  12573. }
  12574. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12575. }
  12576. function openEditDHCPServerModal(id) {
  12577. const s = (state.dhcpServers || []).find(item => item.id === id);
  12578. if (!s) return;
  12579. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12580. document.getElementById('dhcp-server-modal-id').value = s.id;
  12581. document.getElementById('dhcp-server-modal-name').value = s.name;
  12582. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12583. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12584. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12585. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12586. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12587. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12588. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12589. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12590. }
  12591. function closeDHCPServerModal() {
  12592. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12593. }
  12594. async function submitSaveDHCPServer(e) {
  12595. e.preventDefault();
  12596. const id = document.getElementById('dhcp-server-modal-id').value;
  12597. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12598. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12599. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12600. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12601. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12602. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12603. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12604. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12605. try {
  12606. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12607. method: 'POST',
  12608. headers: { 'Content-Type': 'application/json' },
  12609. body: JSON.stringify({
  12610. id,
  12611. name,
  12612. interface: iface,
  12613. network,
  12614. address_pool: pool,
  12615. lease_time: leaseTime,
  12616. authoritative,
  12617. disabled,
  12618. comment
  12619. })
  12620. });
  12621. if (res.ok) {
  12622. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12623. closeDHCPServerModal();
  12624. loadDHCPServer(false);
  12625. fetchData(false);
  12626. } else {
  12627. const err = await res.text();
  12628. showToast('Error', err, 'error');
  12629. }
  12630. } catch (err) {
  12631. showToast('Error', err.message, 'error');
  12632. }
  12633. }
  12634. async function toggleDHCPServerState(id, disabled) {
  12635. try {
  12636. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12637. method: 'POST',
  12638. headers: { 'Content-Type': 'application/json' },
  12639. body: JSON.stringify({ disabled })
  12640. });
  12641. if (res.ok) {
  12642. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12643. loadDHCPServer(false);
  12644. fetchData(false);
  12645. }
  12646. } catch (err) {
  12647. showToast('Error', err.message, 'error');
  12648. }
  12649. }
  12650. async function deleteDHCPServer(id, name) {
  12651. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12652. try {
  12653. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12654. if (res.ok) {
  12655. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12656. loadDHCPServer(false);
  12657. fetchData(false);
  12658. }
  12659. } catch (err) {
  12660. showToast('Error', err.message, 'error');
  12661. }
  12662. }
  12663. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12664. function openAddDHCPNetworkModal() {
  12665. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12666. document.getElementById('dhcp-network-modal-id').value = '';
  12667. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12668. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12669. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12670. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12671. document.getElementById('dhcp-network-modal-netmask').value = '';
  12672. document.getElementById('dhcp-network-modal-comment').value = '';
  12673. renderDHCPNetworkOptionsCheckboxes([]);
  12674. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12675. }
  12676. function openEditDHCPNetworkModal(id) {
  12677. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12678. if (!n) return;
  12679. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12680. document.getElementById('dhcp-network-modal-id').value = n.id;
  12681. document.getElementById('dhcp-network-modal-address').value = n.address;
  12682. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12683. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12684. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12685. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12686. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12687. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12688. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12689. }
  12690. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12691. const container = document.getElementById('dhcp-network-modal-options-list');
  12692. if (!container) return;
  12693. container.innerHTML = '';
  12694. const opts = state.dhcpOptions || [];
  12695. if (opts.length === 0) {
  12696. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12697. return;
  12698. }
  12699. opts.forEach(o => {
  12700. const isChecked = selectedIds.includes(o.id);
  12701. const label = document.createElement('label');
  12702. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12703. label.innerHTML = `
  12704. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12705. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12706. `;
  12707. container.appendChild(label);
  12708. });
  12709. }
  12710. function closeDHCPNetworkModal() {
  12711. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12712. }
  12713. async function submitSaveDHCPNetwork(e) {
  12714. e.preventDefault();
  12715. const id = document.getElementById('dhcp-network-modal-id').value;
  12716. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12717. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12718. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12719. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12720. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12721. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12722. const selectedOpts = [];
  12723. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12724. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12725. try {
  12726. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12727. method: 'POST',
  12728. headers: { 'Content-Type': 'application/json' },
  12729. body: JSON.stringify({
  12730. id,
  12731. address,
  12732. gateway,
  12733. netmask,
  12734. dns_servers: dnsServers,
  12735. domain,
  12736. dhcp_options: selectedOpts,
  12737. comment
  12738. })
  12739. });
  12740. if (res.ok) {
  12741. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12742. closeDHCPNetworkModal();
  12743. loadDHCPServer(false);
  12744. fetchData(false);
  12745. } else {
  12746. const err = await res.text();
  12747. showToast('Error', err, 'error');
  12748. }
  12749. } catch (err) {
  12750. showToast('Error', err.message, 'error');
  12751. }
  12752. }
  12753. async function deleteDHCPNetwork(id, addr) {
  12754. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12755. try {
  12756. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12757. if (res.ok) {
  12758. showToast('Deleted', `Network ${addr} removed`, 'success');
  12759. loadDHCPServer(false);
  12760. fetchData(false);
  12761. }
  12762. } catch (err) {
  12763. showToast('Error', err.message, 'error');
  12764. }
  12765. }
  12766. // ==================== MODALS & ACTIONS: LEASES ====================
  12767. function openAddDHCPStaticLeaseModal() {
  12768. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12769. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12770. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12771. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12772. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12773. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12774. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12775. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12776. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12777. }
  12778. function closeDHCPStaticLeaseModal() {
  12779. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12780. }
  12781. async function submitSaveDHCPStaticLease(e) {
  12782. e.preventDefault();
  12783. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12784. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12785. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12786. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12787. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12788. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12789. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12790. try {
  12791. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12792. method: 'POST',
  12793. headers: { 'Content-Type': 'application/json' },
  12794. body: JSON.stringify({
  12795. id,
  12796. mac_address: mac,
  12797. address: ip,
  12798. hostname,
  12799. server,
  12800. comment,
  12801. disabled
  12802. })
  12803. });
  12804. if (res.ok) {
  12805. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12806. closeDHCPStaticLeaseModal();
  12807. loadDHCPServer(false);
  12808. fetchData(false);
  12809. } else {
  12810. const err = await res.text();
  12811. showToast('Error', err, 'error');
  12812. }
  12813. } catch (err) {
  12814. showToast('Error', err.message, 'error');
  12815. }
  12816. }
  12817. async function deleteDHCPStaticLease(id) {
  12818. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12819. try {
  12820. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12821. if (res.ok) {
  12822. showToast('Deleted', 'Static lease removed', 'success');
  12823. loadDHCPServer(false);
  12824. fetchData(false);
  12825. }
  12826. } catch (err) {
  12827. showToast('Error', err.message, 'error');
  12828. }
  12829. }
  12830. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12831. try {
  12832. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12833. method: 'POST',
  12834. headers: { 'Content-Type': 'application/json' },
  12835. body: JSON.stringify({
  12836. mac_address: mac,
  12837. address: ip,
  12838. hostname,
  12839. comment: comment || 'Converted to static'
  12840. })
  12841. });
  12842. if (res.ok) {
  12843. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12844. loadDHCPServer(false);
  12845. fetchData(false);
  12846. } else {
  12847. const err = await res.text();
  12848. showToast('Error', err, 'error');
  12849. }
  12850. } catch (err) {
  12851. showToast('Error', err.message, 'error');
  12852. }
  12853. }
  12854. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12855. function openAddDHCPOptionModal() {
  12856. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12857. document.getElementById('dhcp-option-modal-id').value = '';
  12858. document.getElementById('dhcp-option-modal-name').value = '';
  12859. document.getElementById('dhcp-option-modal-code').value = '';
  12860. document.getElementById('dhcp-option-modal-value').value = '';
  12861. document.getElementById('dhcp-option-modal-comment').value = '';
  12862. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12863. }
  12864. function openEditDHCPOptionModal(id) {
  12865. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12866. if (!o) return;
  12867. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12868. document.getElementById('dhcp-option-modal-id').value = o.id;
  12869. document.getElementById('dhcp-option-modal-name').value = o.name;
  12870. document.getElementById('dhcp-option-modal-code').value = o.code;
  12871. document.getElementById('dhcp-option-modal-value').value = o.value;
  12872. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12873. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12874. }
  12875. function closeDHCPOptionModal() {
  12876. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12877. }
  12878. async function submitSaveDHCPOption(e) {
  12879. e.preventDefault();
  12880. const id = document.getElementById('dhcp-option-modal-id').value;
  12881. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12882. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12883. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12884. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12885. try {
  12886. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12887. method: 'POST',
  12888. headers: { 'Content-Type': 'application/json' },
  12889. body: JSON.stringify({ id, name, code, value, comment })
  12890. });
  12891. if (res.ok) {
  12892. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12893. closeDHCPOptionModal();
  12894. loadDHCPServer(false);
  12895. fetchData(false);
  12896. } else {
  12897. const err = await res.text();
  12898. showToast('Error', err, 'error');
  12899. }
  12900. } catch (err) {
  12901. showToast('Error', err.message, 'error');
  12902. }
  12903. }
  12904. async function deleteDHCPOption(id, name) {
  12905. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12906. try {
  12907. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12908. if (res.ok) {
  12909. showToast('Deleted', `Option ${name} removed`, 'success');
  12910. loadDHCPServer(false);
  12911. fetchData(false);
  12912. }
  12913. } catch (err) {
  12914. showToast('Error', err.message, 'error');
  12915. }
  12916. }
  12917. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12918. function openDHCPServerSetupModal() {
  12919. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12920. onDHCPWizardIfaceChange();
  12921. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12922. }
  12923. function closeDHCPServerSetupModal() {
  12924. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12925. }
  12926. function onDHCPWizardIfaceChange() {
  12927. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12928. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12929. let ip = '192.168.88.1';
  12930. let prefix = '24';
  12931. if (iface && iface.ip_address) {
  12932. const parts = iface.ip_address.split('/');
  12933. ip = parts[0];
  12934. if (parts.length > 1) prefix = parts[1];
  12935. }
  12936. // Calculate subnet base (e.g. 192.168.88.0/24)
  12937. const ipParts = ip.split('.');
  12938. if (ipParts.length === 4) {
  12939. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12940. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12941. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12942. document.getElementById('dhcp-wizard-gateway').value = ip;
  12943. document.getElementById('dhcp-wizard-pool').value = pool;
  12944. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12945. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12946. }
  12947. }
  12948. async function submitDHCPServerSetupWizard(e) {
  12949. e.preventDefault();
  12950. const iface = document.getElementById('dhcp-wizard-iface').value;
  12951. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12952. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12953. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12954. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12955. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12956. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12957. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12958. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12959. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12960. try {
  12961. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12962. method: 'POST',
  12963. headers: { 'Content-Type': 'application/json' },
  12964. body: JSON.stringify({
  12965. interface: iface,
  12966. address_space: space,
  12967. gateway: gw,
  12968. address_pool: pool,
  12969. dns_servers: dnsServers,
  12970. lease_time: leaseTime,
  12971. ntp_servers: ntpServers,
  12972. next_server: tftp
  12973. })
  12974. });
  12975. if (res.ok) {
  12976. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12977. closeDHCPServerSetupModal();
  12978. loadDHCPServer(false);
  12979. fetchData(false);
  12980. } else {
  12981. const err = await res.text();
  12982. showToast('Error', err, 'error');
  12983. }
  12984. } catch (err) {
  12985. showToast('Error', err.message, 'error');
  12986. }
  12987. }
  12988. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12989. const sel = document.getElementById(elemId);
  12990. if (!sel) return;
  12991. sel.innerHTML = '<option value="">Select interface...</option>';
  12992. const ifaces = state.interfaces || [];
  12993. ifaces.forEach(i => {
  12994. if (i.name === 'lo') return;
  12995. const opt = document.createElement('option');
  12996. opt.value = i.name;
  12997. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12998. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12999. if (i.name === selectedVal) opt.selected = true;
  13000. sel.appendChild(opt);
  13001. });
  13002. }
  13003. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13004. function initTableSorting() {
  13005. document.querySelectorAll('table').forEach(setupSortableTable);
  13006. }
  13007. function setupSortableTable(table) {
  13008. const thead = table.querySelector('thead');
  13009. const tbody = table.querySelector('tbody');
  13010. if (!thead || !tbody) return;
  13011. const headerRows = thead.querySelectorAll('tr');
  13012. if (headerRows.length === 0) return;
  13013. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13014. ths.forEach((th, colIdx) => {
  13015. if (th._sortBound) return;
  13016. th._sortBound = true;
  13017. const rawText = th.innerText.trim().toLowerCase();
  13018. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13019. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13020. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13021. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13022. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13023. return;
  13024. }
  13025. th.classList.add('table-sortable', 'group');
  13026. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13027. let icon = th.querySelector('.table-sort-icon');
  13028. if (!icon) {
  13029. icon = document.createElement('span');
  13030. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13031. icon.innerHTML = '⇅';
  13032. th.appendChild(icon);
  13033. }
  13034. th.addEventListener('click', (e) => {
  13035. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13036. handleHeaderClick(table, th, colIdx);
  13037. });
  13038. });
  13039. if (!tbody._sortObserved) {
  13040. tbody._sortObserved = true;
  13041. let sortDebounceTimer = null;
  13042. const observer = new MutationObserver((mutations) => {
  13043. if (tbody._isSorting) return;
  13044. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13045. if (!hasChildChanges) return;
  13046. clearTimeout(sortDebounceTimer);
  13047. sortDebounceTimer = setTimeout(() => {
  13048. if (tbody._isSorting) return;
  13049. if (table._activeSort && table._activeSort.dir !== 'none') {
  13050. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13051. } else {
  13052. tagOriginalRowOrder(tbody);
  13053. }
  13054. }, 50);
  13055. });
  13056. tbody._sortObserver = observer;
  13057. observer.observe(tbody, { childList: true });
  13058. }
  13059. tagOriginalRowOrder(tbody);
  13060. }
  13061. function tagOriginalRowOrder(tbody) {
  13062. let idx = 0;
  13063. Array.from(tbody.children).forEach(tr => {
  13064. if (!tr.querySelector('td[colspan]')) {
  13065. if (!tr.hasAttribute('data-orig-idx')) {
  13066. tr.setAttribute('data-orig-idx', idx++);
  13067. }
  13068. }
  13069. });
  13070. }
  13071. function handleHeaderClick(table, th, colIdx) {
  13072. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13073. let newDir = 'asc';
  13074. if (currentSort.colIdx === colIdx) {
  13075. if (currentSort.dir === 'asc') newDir = 'desc';
  13076. else if (currentSort.dir === 'desc') newDir = 'none';
  13077. else newDir = 'asc';
  13078. } else {
  13079. newDir = 'asc';
  13080. }
  13081. table._activeSort = { colIdx, dir: newDir };
  13082. updateHeaderIcons(table, colIdx, newDir);
  13083. applyTableSort(table, colIdx, newDir, true);
  13084. }
  13085. function updateHeaderIcons(table, activeColIdx, dir) {
  13086. const thead = table.querySelector('thead');
  13087. if (!thead) return;
  13088. const ths = thead.querySelectorAll('th');
  13089. ths.forEach((th, idx) => {
  13090. const icon = th.querySelector('.table-sort-icon');
  13091. if (!icon) return;
  13092. if (idx === activeColIdx && dir !== 'none') {
  13093. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13094. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13095. th.classList.add('table-sorted-active');
  13096. } else {
  13097. icon.innerHTML = '⇅';
  13098. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13099. th.classList.remove('table-sorted-active');
  13100. }
  13101. });
  13102. }
  13103. function applyTableSort(table, colIdx, dir, userInitiated) {
  13104. const tbody = table.querySelector('tbody');
  13105. if (!tbody || tbody.children.length <= 1) return;
  13106. tbody._isSorting = true;
  13107. tagOriginalRowOrder(tbody);
  13108. // Group parent rows and any attached drawer/sub-rows
  13109. const groups = [];
  13110. let currentGroup = null;
  13111. Array.from(tbody.children).forEach(tr => {
  13112. if (tr.querySelector('td[colspan]')) {
  13113. if (currentGroup) {
  13114. currentGroup.subRows.push(tr);
  13115. } else {
  13116. groups.push({ mainRow: tr, subRows: [] });
  13117. }
  13118. } else {
  13119. currentGroup = { mainRow: tr, subRows: [] };
  13120. groups.push(currentGroup);
  13121. }
  13122. });
  13123. if (dir === 'none') {
  13124. groups.sort((a, b) => {
  13125. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13126. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13127. return idxA - idxB;
  13128. });
  13129. } else {
  13130. groups.sort((a, b) => {
  13131. const cellA = a.mainRow.children[colIdx];
  13132. const cellB = b.mainRow.children[colIdx];
  13133. const res = compareTableCells(cellA, cellB);
  13134. return dir === 'asc' ? res : -res;
  13135. });
  13136. }
  13137. // Check if rows are already in correct order to avoid modifying DOM
  13138. let alreadyOrdered = true;
  13139. let childIdx = 0;
  13140. for (const g of groups) {
  13141. if (tbody.children[childIdx] !== g.mainRow) {
  13142. alreadyOrdered = false;
  13143. break;
  13144. }
  13145. childIdx++;
  13146. for (const sub of g.subRows) {
  13147. if (tbody.children[childIdx] !== sub) {
  13148. alreadyOrdered = false;
  13149. break;
  13150. }
  13151. childIdx++;
  13152. }
  13153. }
  13154. if (alreadyOrdered) {
  13155. tbody._isSorting = false;
  13156. return;
  13157. }
  13158. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13159. if (tbody._sortObserver) {
  13160. tbody._sortObserver.disconnect();
  13161. }
  13162. // Re-append rows in sorted order
  13163. groups.forEach(g => {
  13164. tbody.appendChild(g.mainRow);
  13165. g.subRows.forEach(sub => tbody.appendChild(sub));
  13166. });
  13167. // Drain any queued mutations and re-connect observer
  13168. if (tbody._sortObserver) {
  13169. tbody._sortObserver.takeRecords();
  13170. tbody._sortObserver.observe(tbody, { childList: true });
  13171. }
  13172. tbody._isSorting = false;
  13173. }
  13174. function getCellRawText(cell) {
  13175. if (!cell) return '';
  13176. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13177. const input = cell.querySelector('input, select');
  13178. if (input) {
  13179. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13180. return input.value;
  13181. }
  13182. return cell.innerText.trim();
  13183. }
  13184. function parseTrafficToNumber(str) {
  13185. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13186. if (!m) return null;
  13187. const num = parseFloat(m[1].replace(/,/g, ''));
  13188. if (isNaN(num)) return null;
  13189. const unit = m[2].toUpperCase();
  13190. let mult = 1;
  13191. if (unit.startsWith('K')) mult = 1024;
  13192. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13193. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13194. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13195. return num * mult;
  13196. }
  13197. function parseIpToNumber(str) {
  13198. const clean = str.replace(/^[!~]/, '').trim();
  13199. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13200. if (!m) return null;
  13201. const o1 = parseInt(m[1], 10);
  13202. const o2 = parseInt(m[2], 10);
  13203. const o3 = parseInt(m[3], 10);
  13204. const o4 = parseInt(m[4], 10);
  13205. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13206. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13207. }
  13208. function parseCompoundPackets(str) {
  13209. const m = str.match(/^([\d,]+)p/);
  13210. if (!m) return null;
  13211. return parseInt(m[1].replace(/,/g, ''), 10);
  13212. }
  13213. function compareTableCells(cellA, cellB) {
  13214. const a = getCellRawText(cellA);
  13215. const b = getCellRawText(cellB);
  13216. if (a === '' && b !== '') return 1;
  13217. if (b === '' && a !== '') return -1;
  13218. if (a === b) return 0;
  13219. // 1. IP Addresses / CIDR
  13220. const ipA = parseIpToNumber(a);
  13221. const ipB = parseIpToNumber(b);
  13222. if (ipA !== null && ipB !== null) return ipA - ipB;
  13223. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13224. const pktA = parseCompoundPackets(a);
  13225. const pktB = parseCompoundPackets(b);
  13226. if (pktA !== null && pktB !== null) return pktA - pktB;
  13227. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13228. const trafA = parseTrafficToNumber(a);
  13229. const trafB = parseTrafficToNumber(b);
  13230. if (trafA !== null && trafB !== null) return trafA - trafB;
  13231. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13232. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13233. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13234. const numA = Number(cleanNumA);
  13235. const numB = Number(cleanNumB);
  13236. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13237. return numA - numB;
  13238. }
  13239. // 5. Natural case-insensitive string compare
  13240. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13241. }
  13242. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13243. async function loadVRRP(showToastNotification = false) {
  13244. try {
  13245. const [instRes, sumRes] = await Promise.all([
  13246. fetch(`${API_BASE}/vrrp/instances`),
  13247. fetch(`${API_BASE}/vrrp/summary`)
  13248. ]);
  13249. if (instRes.ok) {
  13250. state.vrrpInstances = await instRes.json();
  13251. renderVRRP();
  13252. }
  13253. if (sumRes.ok) {
  13254. state.vrrpSummary = await sumRes.json();
  13255. renderVRRPSummary();
  13256. }
  13257. if (showToastNotification) {
  13258. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13259. }
  13260. } catch (err) {
  13261. console.error('Failed to load VRRP:', err);
  13262. }
  13263. }
  13264. function renderVRRPSummary() {
  13265. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13266. const elTotal = document.getElementById('vrrp-stat-total');
  13267. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13268. const elMaster = document.getElementById('vrrp-stat-master');
  13269. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13270. const elBackup = document.getElementById('vrrp-stat-backup');
  13271. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13272. const bCount = document.getElementById('badge-vrrp-count');
  13273. if (bCount) bCount.innerText = s.total_instances || 0;
  13274. const dot = document.getElementById('badge-vrrp-dot');
  13275. if (dot) {
  13276. if (s.master_instances > 0) {
  13277. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13278. } else if (s.backup_instances > 0) {
  13279. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13280. } else {
  13281. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13282. }
  13283. }
  13284. }
  13285. function renderVRRP() {
  13286. const tbody = document.getElementById('vrrp-table-tbody');
  13287. const empty = document.getElementById('vrrp-table-empty');
  13288. if (!tbody) return;
  13289. tbody.innerHTML = '';
  13290. const instances = state.vrrpInstances || [];
  13291. if (instances.length === 0) {
  13292. empty?.classList.remove('hidden');
  13293. return;
  13294. }
  13295. empty?.classList.add('hidden');
  13296. instances.forEach(inst => {
  13297. const tr = document.createElement('tr');
  13298. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13299. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13300. 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>`;
  13301. if (inst.disabled) {
  13302. 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>`;
  13303. } else if (inst.state === 'MASTER') {
  13304. 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>`;
  13305. } else if (inst.state === 'BACKUP') {
  13306. 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>`;
  13307. } else if (inst.state === 'FAULT') {
  13308. 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>`;
  13309. }
  13310. // Render State Badge
  13311. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13312. if (!inst.disabled) {
  13313. if (inst.state === 'MASTER') {
  13314. 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>`;
  13315. } else if (inst.state === 'BACKUP') {
  13316. 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>`;
  13317. } else if (inst.state === 'FAULT') {
  13318. 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>`;
  13319. }
  13320. }
  13321. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13322. tr.innerHTML = `
  13323. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13324. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13325. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13326. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13327. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13328. <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>
  13329. <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>
  13330. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13331. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13332. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13333. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13334. <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>
  13335. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13336. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13337. </td>
  13338. `;
  13339. tbody.appendChild(tr);
  13340. });
  13341. }
  13342. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13343. const sel = document.getElementById(elemId);
  13344. if (!sel) return;
  13345. sel.innerHTML = '<option value="">Select interface...</option>';
  13346. const ifaces = state.interfaces || [];
  13347. ifaces.forEach(i => {
  13348. const opt = document.createElement('option');
  13349. opt.value = i.name;
  13350. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13351. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13352. sel.appendChild(opt);
  13353. });
  13354. }
  13355. function openAddVRRPModal() {
  13356. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13357. document.getElementById('modal-vrrp-id').value = '';
  13358. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13359. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13360. document.getElementById('modal-vrrp-priority').value = 100;
  13361. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13362. document.getElementById('modal-vrrp-version').value = '3';
  13363. document.getElementById('modal-vrrp-interval').value = 1;
  13364. document.getElementById('modal-vrrp-authtype').value = 'none';
  13365. document.getElementById('modal-vrrp-authpass').value = '';
  13366. document.getElementById('modal-vrrp-comment').value = '';
  13367. document.getElementById('modal-vrrp-preempt').checked = true;
  13368. document.getElementById('modal-vrrp-disabled').checked = false;
  13369. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13370. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13371. }
  13372. function openEditVRRPModal(id) {
  13373. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13374. if (!inst) return;
  13375. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13376. document.getElementById('modal-vrrp-id').value = inst.id;
  13377. document.getElementById('modal-vrrp-name').value = inst.name;
  13378. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13379. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13380. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13381. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13382. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13383. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13384. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13385. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13386. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13387. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13388. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13389. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13390. }
  13391. function closeVRRPModal() {
  13392. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13393. }
  13394. async function submitSaveVRRP(e) {
  13395. e.preventDefault();
  13396. const id = document.getElementById('modal-vrrp-id').value;
  13397. const name = document.getElementById('modal-vrrp-name').value.trim();
  13398. const iface = document.getElementById('modal-vrrp-iface').value;
  13399. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13400. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13401. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13402. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13403. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13404. const authType = document.getElementById('modal-vrrp-authtype').value;
  13405. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13406. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13407. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13408. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13409. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13410. try {
  13411. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13412. method: 'POST',
  13413. headers: { 'Content-Type': 'application/json' },
  13414. body: JSON.stringify({
  13415. id,
  13416. name,
  13417. interface: iface,
  13418. vrid,
  13419. priority,
  13420. virtual_ips: vips,
  13421. version,
  13422. interval,
  13423. auth_type: authType,
  13424. auth_password: authPass,
  13425. comment,
  13426. preempt,
  13427. disabled
  13428. })
  13429. });
  13430. if (res.ok) {
  13431. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13432. closeVRRPModal();
  13433. loadVRRP(false);
  13434. fetchData(false);
  13435. } else {
  13436. const err = await res.text();
  13437. showToast('Error', err, 'error');
  13438. }
  13439. } catch (err) {
  13440. showToast('Error', err.message, 'error');
  13441. }
  13442. }
  13443. async function deleteVRRP(id, name) {
  13444. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13445. try {
  13446. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13447. if (res.ok) {
  13448. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13449. loadVRRP(false);
  13450. fetchData(false);
  13451. } else {
  13452. const err = await res.text();
  13453. showToast('Error', err, 'error');
  13454. }
  13455. } catch (err) {
  13456. showToast('Error', err.message, 'error');
  13457. }
  13458. }
  13459. async function toggleVRRPState(id, disabled) {
  13460. try {
  13461. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13462. method: 'POST',
  13463. headers: { 'Content-Type': 'application/json' },
  13464. body: JSON.stringify({ disabled })
  13465. });
  13466. if (res.ok) {
  13467. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13468. loadVRRP(false);
  13469. fetchData(false);
  13470. } else {
  13471. const err = await res.text();
  13472. showToast('Error', err, 'error');
  13473. }
  13474. } catch (err) {
  13475. showToast('Error', err.message, 'error');
  13476. }
  13477. }
  13478. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13479. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13480. let docSortDebounce = null;
  13481. const docTableObserver = new MutationObserver((mutations) => {
  13482. let needsInit = false;
  13483. for (const m of mutations) {
  13484. for (const node of m.addedNodes) {
  13485. if (node.nodeType === 1) {
  13486. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13487. needsInit = true;
  13488. break;
  13489. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13490. needsInit = true;
  13491. break;
  13492. }
  13493. }
  13494. }
  13495. if (needsInit) break;
  13496. }
  13497. if (needsInit) {
  13498. clearTimeout(docSortDebounce);
  13499. docSortDebounce = setTimeout(initTableSorting, 100);
  13500. }
  13501. });
  13502. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13503. }
  13504. // =========================================================================
  13505. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13506. // =========================================================================
  13507. const bwtestState = {
  13508. running: false,
  13509. pollTimer: null,
  13510. eventSource: null,
  13511. chartPoints: [],
  13512. maxChartPoints: 60,
  13513. serverConfig: null,
  13514. peakTx: 0,
  13515. peakRx: 0,
  13516. targetDuration: 10,
  13517. lastSampleElapsed: -1,
  13518. sessionID: null
  13519. };
  13520. async function loadBwTestView() {
  13521. resizeBwTestCanvas();
  13522. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  13523. }
  13524. async function fetchBwTestServerStatus() {
  13525. try {
  13526. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13527. if (!res.ok) return;
  13528. const s = await res.json();
  13529. bwtestState.serverConfig = s;
  13530. // Update indicator and badges
  13531. const indicator = document.getElementById('bwtest-server-indicator');
  13532. const badge = document.getElementById('bwtest-server-badge');
  13533. const sideBadge = document.getElementById('badge-bwtest-server');
  13534. if (s.enabled && s.running) {
  13535. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13536. if (badge) {
  13537. badge.innerText = `Port ${s.port} (Active)`;
  13538. badge.className = 'text-emerald-400 font-bold';
  13539. }
  13540. if (sideBadge) {
  13541. sideBadge.innerText = s.port;
  13542. 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';
  13543. }
  13544. } else {
  13545. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13546. if (badge) {
  13547. badge.innerText = `Disabled`;
  13548. badge.className = 'text-slate-500 font-bold';
  13549. }
  13550. if (sideBadge) {
  13551. sideBadge.innerText = 'Off';
  13552. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13553. }
  13554. }
  13555. // Modal fields
  13556. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13557. const serverModal = document.getElementById('modal-bwtest-server');
  13558. const editing = serverModal && !serverModal.classList.contains('hidden');
  13559. if (toggle && !editing) toggle.checked = !!s.enabled;
  13560. const portInp = document.getElementById('bwtest-server-port-input');
  13561. if (portInp && !editing) portInp.value = s.port || 2000;
  13562. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13563. if (actSess) actSess.innerText = s.active_sessions || 0;
  13564. const totServ = document.getElementById('bwtest-modal-total-served');
  13565. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13566. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13567. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13568. } catch (err) {
  13569. console.error('Failed to fetch BwTest server status:', err);
  13570. }
  13571. }
  13572. function openBwTestServerModal() {
  13573. const cfg = bwtestState.serverConfig;
  13574. if (cfg) {
  13575. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  13576. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  13577. }
  13578. fetchBwTestServerStatus();
  13579. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13580. }
  13581. function closeBwTestServerModal() {
  13582. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13583. }
  13584. async function submitBwTestServerSettings(e) {
  13585. e.preventDefault();
  13586. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13587. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13588. try {
  13589. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13590. method: 'POST',
  13591. headers: { 'Content-Type': 'application/json' },
  13592. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13593. });
  13594. if (!res.ok) {
  13595. const err = await res.json();
  13596. throw new Error(err.error || 'Failed to update server configuration');
  13597. }
  13598. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13599. closeBwTestServerModal();
  13600. fetchBwTestServerStatus();
  13601. } catch (err) {
  13602. showToast('Server Configuration Error', err.message, 'error');
  13603. }
  13604. }
  13605. function setBwTestTarget(target) {
  13606. const inp = document.getElementById('bwtest-input-target');
  13607. if (inp) inp.value = target;
  13608. }
  13609. function setBwTestProtocol(proto) {
  13610. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13611. if (hiddenInp) hiddenInp.value = proto;
  13612. const btnUdp = document.getElementById('bwtest-proto-udp');
  13613. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13614. const badge = document.getElementById('bwtest-proto-badge');
  13615. const pktField = document.getElementById('bwtest-field-pktsize');
  13616. 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';
  13617. 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';
  13618. 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';
  13619. if (proto === 'udp') {
  13620. if (btnUdp) {
  13621. btnUdp.className = activeUdpCls;
  13622. const dot = btnUdp.querySelector('span');
  13623. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13624. }
  13625. if (btnTcp) {
  13626. btnTcp.className = inactiveCls;
  13627. const dot = btnTcp.querySelector('span');
  13628. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13629. }
  13630. if (badge) {
  13631. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13632. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13633. }
  13634. if (pktField) pktField.classList.remove('opacity-40');
  13635. } else {
  13636. if (btnUdp) {
  13637. btnUdp.className = inactiveCls;
  13638. const dot = btnUdp.querySelector('span');
  13639. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13640. }
  13641. if (btnTcp) {
  13642. btnTcp.className = activeTcpCls;
  13643. const dot = btnTcp.querySelector('span');
  13644. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13645. }
  13646. if (badge) {
  13647. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13648. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13649. }
  13650. if (pktField) pktField.classList.add('opacity-40');
  13651. }
  13652. }
  13653. function setBwTestDirection(dir) {
  13654. const hiddenInp = document.getElementById('bwtest-input-direction');
  13655. if (hiddenInp) hiddenInp.value = dir;
  13656. const btnBoth = document.getElementById('bwtest-dir-both');
  13657. const btnTx = document.getElementById('bwtest-dir-tx');
  13658. const btnRx = document.getElementById('bwtest-dir-rx');
  13659. 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';
  13660. 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';
  13661. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13662. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13663. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13664. }
  13665. function setBwTestLimit(bps) {
  13666. const sel = document.getElementById('bwtest-input-limit');
  13667. if (sel) sel.value = String(bps);
  13668. }
  13669. async function checkActiveBwTest() {
  13670. try {
  13671. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13672. if (!res.ok) return;
  13673. const st = await res.json();
  13674. if (st.running) {
  13675. setBwTestRunningUI(true);
  13676. processBwTestStatus(st);
  13677. startBwTestTelemetry();
  13678. }
  13679. } catch (err) {
  13680. console.error('Failed to check active BwTest:', err);
  13681. }
  13682. }
  13683. async function startBwTest(e) {
  13684. if (e && e.preventDefault) e.preventDefault();
  13685. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13686. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13687. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13688. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13689. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13690. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13691. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13692. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13693. bwtestState.targetDuration = duration;
  13694. bwtestState.chartPoints = [];
  13695. bwtestState.peakTx = 0;
  13696. bwtestState.peakRx = 0;
  13697. bwtestState.lastSampleElapsed = -1;
  13698. bwtestState.sessionID = null;
  13699. // Clear UI elements
  13700. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13701. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13702. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13703. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13704. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13705. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13706. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13707. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13708. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13709. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13710. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13711. const tbody = document.getElementById('bwtest-samples-tbody');
  13712. if (tbody) tbody.innerHTML = '';
  13713. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13714. setBwTestRunningUI(true);
  13715. try {
  13716. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13717. method: 'POST',
  13718. headers: { 'Content-Type': 'application/json' },
  13719. body: JSON.stringify({
  13720. target,
  13721. port,
  13722. direction,
  13723. protocol,
  13724. bandwidth_limit,
  13725. packet_size,
  13726. streams,
  13727. duration
  13728. })
  13729. });
  13730. if (!res.ok) {
  13731. const err = await res.json();
  13732. throw new Error(err.error || 'Failed to start bandwidth test');
  13733. }
  13734. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13735. startBwTestTelemetry();
  13736. } catch (err) {
  13737. setBwTestRunningUI(false);
  13738. showToast('Start Failed', err.message, 'error');
  13739. }
  13740. }
  13741. function setBwTestRunningUI(running) {
  13742. bwtestState.running = running;
  13743. const startBtn = document.getElementById('bwtest-btn-start');
  13744. const stopBtn = document.getElementById('bwtest-btn-stop');
  13745. const badge = document.getElementById('bwtest-run-status-badge');
  13746. const ph = document.getElementById('bwtest-chart-placeholder');
  13747. if (running) {
  13748. if (startBtn) {
  13749. startBtn.disabled = true;
  13750. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13751. }
  13752. if (stopBtn) {
  13753. stopBtn.disabled = false;
  13754. stopBtn.classList.remove('opacity-40');
  13755. }
  13756. if (badge) {
  13757. badge.innerText = 'TESTING...';
  13758. 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';
  13759. }
  13760. if (ph) ph.style.display = 'none';
  13761. } else {
  13762. if (startBtn) {
  13763. startBtn.disabled = false;
  13764. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13765. }
  13766. if (stopBtn) {
  13767. stopBtn.disabled = true;
  13768. stopBtn.classList.add('opacity-40');
  13769. }
  13770. if (badge) {
  13771. badge.innerText = 'IDLE';
  13772. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13773. }
  13774. }
  13775. }
  13776. async function stopBwTest() {
  13777. try {
  13778. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13779. if (!res.ok) throw new Error(await responseError(res));
  13780. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  13781. if (!bwtestState.pollTimer) startBwTestTelemetry();
  13782. } catch (err) {
  13783. showToast('Stop Failed', err.message, 'error');
  13784. }
  13785. }
  13786. async function responseError(res) {
  13787. const text = await res.text();
  13788. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  13789. catch { return text || `HTTP ${res.status}`; }
  13790. }
  13791. function processBwTestStatus(st) {
  13792. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  13793. bwtestState.sessionID = st.session_id;
  13794. bwtestState.lastSampleElapsed = -1;
  13795. }
  13796. for (const sample of st.recent_samples || []) {
  13797. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  13798. handleBwTestSample(sample);
  13799. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  13800. }
  13801. }
  13802. if (!st.running) {
  13803. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13804. bwtestState.pollTimer = null;
  13805. setBwTestRunningUI(false);
  13806. handleBwTestFinish(st.summary, st.error);
  13807. }
  13808. }
  13809. function startBwTestTelemetry() {
  13810. if (!state.currentUser) return;
  13811. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13812. let busy = false;
  13813. const poll = async () => {
  13814. if (busy || !state.currentUser || document.hidden) return;
  13815. busy = true;
  13816. try {
  13817. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13818. if (!res.ok) throw new Error(await responseError(res));
  13819. processBwTestStatus(await res.json());
  13820. } catch (err) {
  13821. console.error('BwTest polling error:', err);
  13822. } finally { busy = false; }
  13823. };
  13824. bwtestState.pollTimer = setInterval(poll, 400);
  13825. poll();
  13826. }
  13827. function handleBwTestSample(s) {
  13828. if (!s) return;
  13829. const payloadHint = document.getElementById('bwtest-effective-payload');
  13830. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  13831. const txMbps = s.tx_mbps || 0;
  13832. const rxMbps = s.rx_mbps || 0;
  13833. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13834. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13835. // KPI updates
  13836. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13837. if (elTx) {
  13838. elTx.innerText = txMbps.toFixed(2);
  13839. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  13840. }
  13841. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13842. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13843. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13844. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13845. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13846. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13847. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13848. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13849. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13850. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13851. const elLoss = document.getElementById('bwtest-stat-loss');
  13852. if (elLoss) {
  13853. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13854. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13855. }
  13856. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13857. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13858. const elJitter = document.getElementById('bwtest-stat-jitter');
  13859. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13860. const elTime = document.getElementById('bwtest-stat-time');
  13861. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13862. const elData = document.getElementById('bwtest-stat-data');
  13863. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13864. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13865. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13866. // Append point to chart buffer
  13867. bwtestState.chartPoints.push({
  13868. elapsed: s.elapsed_sec || 0,
  13869. tx: txMbps,
  13870. rx: rxMbps
  13871. });
  13872. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13873. bwtestState.chartPoints.shift();
  13874. }
  13875. drawBwTestChart();
  13876. // Add row to breakdown table
  13877. const tbody = document.getElementById('bwtest-samples-tbody');
  13878. if (tbody) {
  13879. const tr = document.createElement('tr');
  13880. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13881. tr.innerHTML = `
  13882. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13883. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13884. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13885. <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>
  13886. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13887. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13888. `;
  13889. tbody.insertBefore(tr, tbody.firstChild);
  13890. const countEl = document.getElementById('bwtest-sample-count');
  13891. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13892. }
  13893. }
  13894. function handleBwTestFinish(summary, error) {
  13895. const badge = document.getElementById('bwtest-run-status-badge');
  13896. if (error) {
  13897. showToast('Benchmark Error', error, 'error');
  13898. if (badge) {
  13899. badge.innerText = 'ERROR';
  13900. 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';
  13901. }
  13902. } else if (summary) {
  13903. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13904. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13905. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13906. if (badge) {
  13907. badge.innerText = 'COMPLETED';
  13908. 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';
  13909. }
  13910. }
  13911. loadBwTestHistory();
  13912. fetchBwTestServerStatus();
  13913. }
  13914. function resizeBwTestCanvas() {
  13915. const canvas = document.getElementById('bwtest-chart');
  13916. if (!canvas || !canvas.parentElement) return;
  13917. const rect = canvas.parentElement.getBoundingClientRect();
  13918. const dpr = window.devicePixelRatio || 1;
  13919. canvas.width = rect.width * dpr;
  13920. canvas.height = rect.height * dpr;
  13921. const ctx = canvas.getContext('2d');
  13922. ctx.scale(dpr, dpr);
  13923. drawBwTestChart();
  13924. }
  13925. window.addEventListener('resize', () => {
  13926. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13927. });
  13928. function drawBwTestChart() {
  13929. const canvas = document.getElementById('bwtest-chart');
  13930. if (!canvas) return;
  13931. const ctx = canvas.getContext('2d');
  13932. const dpr = window.devicePixelRatio || 1;
  13933. const width = canvas.width / dpr;
  13934. const height = canvas.height / dpr;
  13935. ctx.clearRect(0, 0, width, height);
  13936. const points = bwtestState.chartPoints;
  13937. if (!points || points.length === 0) return;
  13938. // Determine scale ceiling
  13939. let maxRate = 10;
  13940. for (const p of points) {
  13941. if (p.tx > maxRate) maxRate = p.tx;
  13942. if (p.rx > maxRate) maxRate = p.rx;
  13943. }
  13944. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13945. const paddingLeft = 55;
  13946. const paddingBottom = 24;
  13947. const paddingTop = 12;
  13948. const paddingRight = 16;
  13949. const chartW = width - paddingLeft - paddingRight;
  13950. const chartH = height - paddingTop - paddingBottom;
  13951. // Grid Lines and Y-Axis labels
  13952. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13953. ctx.lineWidth = 1;
  13954. ctx.fillStyle = '#94a3b8';
  13955. ctx.font = '10px monospace';
  13956. ctx.textAlign = 'right';
  13957. const gridSteps = 4;
  13958. for (let i = 0; i <= gridSteps; i++) {
  13959. const val = (maxRate / gridSteps) * i;
  13960. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13961. ctx.beginPath();
  13962. ctx.moveTo(paddingLeft, y);
  13963. ctx.lineTo(width - paddingRight, y);
  13964. ctx.stroke();
  13965. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13966. }
  13967. // Draw TX Line (Cyan #22d3ee)
  13968. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13969. // Draw RX Line (Purple #a855f7)
  13970. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13971. }
  13972. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13973. if (points.length < 2) return;
  13974. const stepX = w / Math.max(points.length - 1, 1);
  13975. // Gradient area fill
  13976. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13977. grad.addColorStop(0, fillColor);
  13978. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13979. ctx.beginPath();
  13980. points.forEach((p, idx) => {
  13981. const x = left + idx * stepX;
  13982. const val = valFn(p);
  13983. const y = top + h - (val / maxVal) * h;
  13984. if (idx === 0) {
  13985. ctx.moveTo(x, y);
  13986. } else {
  13987. ctx.lineTo(x, y);
  13988. }
  13989. });
  13990. // Complete path for fill
  13991. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13992. ctx.lineTo(left, top + h);
  13993. ctx.closePath();
  13994. ctx.fillStyle = grad;
  13995. ctx.fill();
  13996. // Draw line stroke
  13997. ctx.beginPath();
  13998. ctx.lineWidth = 2.5;
  13999. ctx.strokeStyle = strokeColor;
  14000. points.forEach((p, idx) => {
  14001. const x = left + idx * stepX;
  14002. const val = valFn(p);
  14003. const y = top + h - (val / maxVal) * h;
  14004. if (idx === 0) {
  14005. ctx.moveTo(x, y);
  14006. } else {
  14007. ctx.lineTo(x, y);
  14008. }
  14009. });
  14010. ctx.stroke();
  14011. // Draw end point halo
  14012. const lastP = points[points.length - 1];
  14013. const lastX = left + (points.length - 1) * stepX;
  14014. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14015. ctx.fillStyle = strokeColor;
  14016. ctx.beginPath();
  14017. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14018. ctx.fill();
  14019. }
  14020. async function loadBwTestHistory() {
  14021. try {
  14022. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14023. if (!res.ok) return;
  14024. const list = await res.json();
  14025. renderBwTestHistory(Array.isArray(list) ? list : []);
  14026. } catch (err) {
  14027. console.error('Failed to load BwTest history:', err);
  14028. }
  14029. }
  14030. function renderBwTestHistory(list) {
  14031. const tbody = document.getElementById('bwtest-history-tbody');
  14032. if (!tbody) return;
  14033. if (list.length === 0) {
  14034. 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>`;
  14035. return;
  14036. }
  14037. tbody.innerHTML = '';
  14038. list.forEach(item => {
  14039. const s = item.summary || {};
  14040. const tr = document.createElement('tr');
  14041. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14042. const dirBadge = item.direction === 'both'
  14043. ? `<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>`
  14044. : item.direction === 'tx'
  14045. ? `<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>`
  14046. : `<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>`;
  14047. const protoBadge = item.protocol === 'tcp'
  14048. ? `<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>`
  14049. : `<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>`;
  14050. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14051. tr.innerHTML = `
  14052. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14053. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14054. <td class="py-2.5 px-4">${protoBadge}</td>
  14055. <td class="py-2.5 px-4">${dirBadge}</td>
  14056. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14057. <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>
  14058. <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>
  14059. <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>
  14060. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14061. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14062. `;
  14063. tbody.appendChild(tr);
  14064. });
  14065. }
  14066. // ======================== SETTINGS & ROUTER DNS ========================
  14067. state.settingsSubTab = 'dns';
  14068. state.dnsSettings = null;
  14069. state.dnsStaticRecords = [];
  14070. state.dnsStatus = null;
  14071. function switchSettingsSubTab(sub) {
  14072. state.settingsSubTab = sub;
  14073. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14074. const btnSys = document.getElementById('btn-settings-subtab-system');
  14075. const tabDns = document.getElementById('settings-subtab-dns');
  14076. const tabSys = document.getElementById('settings-subtab-system');
  14077. if (sub === 'dns') {
  14078. if (btnDns) {
  14079. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  14080. }
  14081. if (btnSys) {
  14082. btnSys.className = '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';
  14083. }
  14084. tabDns?.classList.remove('hidden');
  14085. tabSys?.classList.add('hidden');
  14086. loadDNSSettings();
  14087. } else {
  14088. if (btnSys) {
  14089. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  14090. }
  14091. if (btnDns) {
  14092. btnDns.className = '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';
  14093. }
  14094. tabSys?.classList.remove('hidden');
  14095. tabDns?.classList.add('hidden');
  14096. loadSystemSettings();
  14097. }
  14098. }
  14099. async function loadSettingsData(showLoading = false) {
  14100. if (state.settingsSubTab === 'system') {
  14101. await loadSystemSettings();
  14102. } else {
  14103. await loadDNSSettings();
  14104. }
  14105. }
  14106. async function loadDNSSettings() {
  14107. try {
  14108. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14109. fetch(`${API_BASE}/dns/settings`),
  14110. fetch(`${API_BASE}/dns/static`),
  14111. fetch(`${API_BASE}/dns/status`)
  14112. ]);
  14113. if (settingsRes.ok) {
  14114. state.dnsSettings = await settingsRes.json();
  14115. populateDNSSettingsForm(state.dnsSettings);
  14116. }
  14117. if (staticRes.ok) {
  14118. state.dnsStaticRecords = await staticRes.json();
  14119. renderStaticDNSList();
  14120. }
  14121. if (statusRes.ok) {
  14122. state.dnsStatus = await statusRes.json();
  14123. updateDNSStatusView(state.dnsStatus);
  14124. }
  14125. } catch (err) {
  14126. console.error('Failed to load DNS settings:', err);
  14127. }
  14128. }
  14129. function populateDNSSettingsForm(s) {
  14130. if (!s) return;
  14131. const dnsForm = document.getElementById('form-dns-settings');
  14132. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14133. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14134. if (dynamicEl) {
  14135. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14136. 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(' ');
  14137. } else {
  14138. dynamicEl.innerText = 'None';
  14139. }
  14140. }
  14141. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14142. if (isEditing) return;
  14143. const serversInput = document.getElementById('dns-servers-input');
  14144. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14145. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14146. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14147. const domainInput = document.getElementById('dns-domain-input');
  14148. if (domainInput) domainInput.value = s.domain || '';
  14149. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14150. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14151. }
  14152. function updateDNSStatusView(st) {
  14153. if (!st) return;
  14154. const preview = document.getElementById('dns-resolv-preview');
  14155. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14156. const pillText = document.getElementById('dns-live-status-text');
  14157. const pill = document.getElementById('dns-live-status-pill');
  14158. if (pill && pillText) {
  14159. if (st.service_running) {
  14160. 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';
  14161. pillText.innerText = 'DNS Service Active';
  14162. } else {
  14163. 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';
  14164. pillText.innerText = 'DNS Service Inactive';
  14165. }
  14166. }
  14167. }
  14168. function appendDNSPreset(preset) {
  14169. const input = document.getElementById('dns-servers-input');
  14170. if (!input) return;
  14171. const dnsForm = document.getElementById('form-dns-settings');
  14172. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14173. const current = input.value.trim();
  14174. if (!current) {
  14175. input.value = preset;
  14176. } else {
  14177. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14178. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14179. toAdd.forEach(ip => {
  14180. if (!existing.includes(ip)) existing.push(ip);
  14181. });
  14182. input.value = existing.join(', ');
  14183. }
  14184. }
  14185. async function saveDNSSettings(e) {
  14186. e.preventDefault();
  14187. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14188. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14189. if (servers.length === 0) {
  14190. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14191. return;
  14192. }
  14193. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14194. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14195. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14196. try {
  14197. const res = await fetch(`${API_BASE}/dns/settings`, {
  14198. method: 'POST',
  14199. headers: { 'Content-Type': 'application/json' },
  14200. body: JSON.stringify({
  14201. servers: servers,
  14202. cache_size: cacheSize,
  14203. domain: domain,
  14204. allow_remote_requests: allowRemote
  14205. })
  14206. });
  14207. const data = await res.json();
  14208. if (res.ok) {
  14209. const dnsForm = document.getElementById('form-dns-settings');
  14210. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14211. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14212. loadDNSSettings();
  14213. } else {
  14214. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14215. }
  14216. } catch (err) {
  14217. showToast('Error', err.message, 'error');
  14218. }
  14219. }
  14220. async function flushDNSCache() {
  14221. try {
  14222. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14223. if (res.ok) {
  14224. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14225. loadDNSSettings();
  14226. } else {
  14227. const err = await res.json();
  14228. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14229. }
  14230. } catch (err) {
  14231. showToast('Error', err.message, 'error');
  14232. }
  14233. }
  14234. function renderStaticDNSList() {
  14235. const tbody = document.getElementById('dns-static-tbody');
  14236. const empty = document.getElementById('dns-static-empty');
  14237. const badge = document.getElementById('dns-static-count-badge');
  14238. if (!tbody) return;
  14239. tbody.innerHTML = '';
  14240. const records = state.dnsStaticRecords || [];
  14241. if (badge) badge.innerText = `${records.length} Records`;
  14242. if (records.length === 0) {
  14243. empty?.classList.remove('hidden');
  14244. return;
  14245. }
  14246. empty?.classList.add('hidden');
  14247. records.forEach(rec => {
  14248. const tr = document.createElement('tr');
  14249. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14250. tr.innerHTML = `
  14251. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14252. <td class="py-2.5 px-4">
  14253. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14254. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14255. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14256. }">
  14257. ${rec.type || 'A'}
  14258. </span>
  14259. </td>
  14260. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14261. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14262. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14263. <td class="py-2.5 px-4">
  14264. <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'}">
  14265. ${rec.disabled ? 'Disabled' : 'Active'}
  14266. </span>
  14267. </td>
  14268. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14269. <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>
  14270. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14271. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14272. </td>
  14273. `;
  14274. tbody.appendChild(tr);
  14275. });
  14276. }
  14277. function openStaticDNSModal(id = null) {
  14278. const modal = document.getElementById('modal-static-dns');
  14279. const title = document.getElementById('modal-static-dns-title');
  14280. const form = document.getElementById('form-static-dns');
  14281. if (!modal || !form) return;
  14282. form.reset();
  14283. document.getElementById('modal-static-dns-id').value = '';
  14284. if (id) {
  14285. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14286. if (rec) {
  14287. if (title) title.innerText = 'Edit Static DNS Record';
  14288. document.getElementById('modal-static-dns-id').value = rec.id;
  14289. document.getElementById('modal-static-dns-name').value = rec.name;
  14290. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14291. document.getElementById('modal-static-dns-addr').value = rec.address;
  14292. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14293. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14294. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14295. }
  14296. } else {
  14297. if (title) title.innerText = 'Add Static DNS Record';
  14298. }
  14299. modal.classList.remove('hidden');
  14300. }
  14301. function closeStaticDNSModal() {
  14302. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14303. }
  14304. async function submitSaveStaticDNS(e) {
  14305. e.preventDefault();
  14306. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14307. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14308. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14309. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14310. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14311. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14312. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14313. if (!name || !address) {
  14314. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14315. return;
  14316. }
  14317. try {
  14318. const res = await fetch(`${API_BASE}/dns/static`, {
  14319. method: 'POST',
  14320. headers: { 'Content-Type': 'application/json' },
  14321. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14322. });
  14323. const data = await res.json();
  14324. if (res.ok) {
  14325. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14326. closeStaticDNSModal();
  14327. loadDNSSettings();
  14328. } else {
  14329. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14330. }
  14331. } catch (err) {
  14332. showToast('Error', err.message, 'error');
  14333. }
  14334. }
  14335. async function deleteStaticDNS(id) {
  14336. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14337. try {
  14338. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14339. if (res.ok) {
  14340. showToast('Deleted', 'Static DNS record deleted', 'success');
  14341. loadDNSSettings();
  14342. }
  14343. } catch (err) {
  14344. showToast('Error', err.message, 'error');
  14345. }
  14346. }
  14347. async function toggleStaticDNS(id, disabled) {
  14348. try {
  14349. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14350. method: 'POST',
  14351. headers: { 'Content-Type': 'application/json' },
  14352. body: JSON.stringify({ disabled })
  14353. });
  14354. if (res.ok) {
  14355. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14356. loadDNSSettings();
  14357. }
  14358. } catch (err) {
  14359. showToast('Error', err.message, 'error');
  14360. }
  14361. }
  14362. async function loadSystemSettings() {
  14363. try {
  14364. const sysForm = document.getElementById('form-system-settings');
  14365. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14366. const res = await fetch(`${API_BASE}/system/settings`);
  14367. if (res.ok) {
  14368. const data = await res.json();
  14369. if (!isEditing) {
  14370. const hostInput = document.getElementById('system-hostname-input');
  14371. if (hostInput) hostInput.value = data.hostname || '';
  14372. const tzInput = document.getElementById('system-timezone-input');
  14373. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14374. }
  14375. }
  14376. } catch (err) {
  14377. console.error('Failed to load system settings:', err);
  14378. }
  14379. }
  14380. async function saveSystemSettings(e) {
  14381. e.preventDefault();
  14382. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14383. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14384. try {
  14385. const res = await fetch(`${API_BASE}/system/settings`, {
  14386. method: 'POST',
  14387. headers: { 'Content-Type': 'application/json' },
  14388. body: JSON.stringify({ hostname, timezone })
  14389. });
  14390. const data = await res.json();
  14391. if (res.ok) {
  14392. const sysForm = document.getElementById('form-system-settings');
  14393. if (sysForm) sysForm.dataset.dirty = 'false';
  14394. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14395. const sideH = document.getElementById('side-hostname');
  14396. if (sideH) sideH.innerText = data.hostname;
  14397. } else {
  14398. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14399. }
  14400. } catch (err) {
  14401. showToast('Error', err.message, 'error');
  14402. }
  14403. }
  14404. // =============================================================================
  14405. // AUTHENTICATION & USER MANAGER
  14406. // =============================================================================
  14407. async function checkAuthStatus() {
  14408. try {
  14409. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14410. headers: {
  14411. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14412. }
  14413. });
  14414. if (res.ok) {
  14415. const user = await res.json();
  14416. state.currentUser = user;
  14417. updateUserProfileHeader(user);
  14418. hideLoginScreen();
  14419. state.isPolling = true;
  14420. fetchData();
  14421. initLiveTrafficStream();
  14422. return true;
  14423. } else {
  14424. showLoginScreen(false);
  14425. return false;
  14426. }
  14427. } catch (err) {
  14428. showLoginScreen(false);
  14429. return false;
  14430. }
  14431. }
  14432. function showLoginScreen(isExpired = false) {
  14433. const el = document.getElementById('login-screen');
  14434. if (el) el.classList.remove('hidden');
  14435. const errEl = document.getElementById('login-error');
  14436. const errTxt = document.getElementById('login-error-text');
  14437. if (isExpired && errEl && errTxt) {
  14438. errTxt.innerText = 'Session expired. Please sign in again.';
  14439. errEl.classList.remove('hidden');
  14440. } else if (errEl) {
  14441. errEl.classList.add('hidden');
  14442. }
  14443. const pwInput = document.getElementById('login-password');
  14444. if (pwInput) pwInput.value = '';
  14445. const userInput = document.getElementById('login-username');
  14446. if (userInput && !userInput.value) userInput.focus();
  14447. else if (pwInput) pwInput.focus();
  14448. }
  14449. function hideLoginScreen() {
  14450. const el = document.getElementById('login-screen');
  14451. if (el) el.classList.add('hidden');
  14452. const errEl = document.getElementById('login-error');
  14453. if (errEl) errEl.classList.add('hidden');
  14454. }
  14455. async function handleLoginSubmit(event) {
  14456. event.preventDefault();
  14457. const username = (document.getElementById('login-username')?.value || '').trim();
  14458. const password = document.getElementById('login-password')?.value || '';
  14459. const errEl = document.getElementById('login-error');
  14460. const errTxt = document.getElementById('login-error-text');
  14461. const btn = document.getElementById('login-submit-btn');
  14462. const btnText = document.getElementById('login-btn-text');
  14463. const spinner = document.getElementById('login-btn-spinner');
  14464. if (!username || !password) {
  14465. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14466. if (errEl) errEl.classList.remove('hidden');
  14467. return;
  14468. }
  14469. if (errEl) errEl.classList.add('hidden');
  14470. if (btn) btn.disabled = true;
  14471. if (btnText) btnText.innerText = 'Authenticating...';
  14472. if (spinner) spinner.classList.remove('hidden');
  14473. try {
  14474. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14475. method: 'POST',
  14476. headers: { 'Content-Type': 'application/json' },
  14477. body: JSON.stringify({ username, password })
  14478. });
  14479. const data = await res.json();
  14480. if (res.ok && data.success) {
  14481. localStorage.setItem('debtik_token', data.token);
  14482. state.currentUser = data.user;
  14483. updateUserProfileHeader(data.user);
  14484. hideLoginScreen();
  14485. state.isPolling = true;
  14486. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14487. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14488. navigate(hash);
  14489. fetchData();
  14490. initLiveTrafficStream();
  14491. // Ensure background telemetry polling is active
  14492. if (!window._telemetryInterval) {
  14493. window._telemetryInterval = setInterval(() => {
  14494. if (state.isPolling && state.currentUser && !document.hidden) {
  14495. fetchData(false);
  14496. }
  14497. }, 5000);
  14498. }
  14499. } else {
  14500. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14501. if (errEl) errEl.classList.remove('hidden');
  14502. }
  14503. } catch (err) {
  14504. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14505. if (errEl) errEl.classList.remove('hidden');
  14506. } finally {
  14507. if (btn) btn.disabled = false;
  14508. if (btnText) btnText.innerText = 'Sign In to Controller';
  14509. if (spinner) spinner.classList.add('hidden');
  14510. }
  14511. }
  14512. async function handleLogoutClick() {
  14513. try {
  14514. await originalFetch(`${API_BASE}/auth/logout`, {
  14515. method: 'POST',
  14516. headers: {
  14517. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14518. }
  14519. });
  14520. } catch (e) {}
  14521. stopSessionPolling();
  14522. localStorage.removeItem('debtik_token');
  14523. state.currentUser = null;
  14524. state.isPolling = false;
  14525. if (window._telemetryInterval) {
  14526. clearInterval(window._telemetryInterval);
  14527. window._telemetryInterval = null;
  14528. }
  14529. if (trafficEventSource) {
  14530. trafficEventSource.close();
  14531. trafficEventSource = null;
  14532. }
  14533. if (trafficPollFallback) {
  14534. clearInterval(trafficPollFallback);
  14535. trafficPollFallback = null;
  14536. }
  14537. showLoginScreen(false);
  14538. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14539. }
  14540. function togglePasswordVisibility(id) {
  14541. const input = document.getElementById(id);
  14542. if (!input) return;
  14543. input.type = input.type === 'password' ? 'text' : 'password';
  14544. }
  14545. function toggleUserMenu() {
  14546. const menu = document.getElementById('user-menu-dropdown');
  14547. if (menu) menu.classList.toggle('hidden');
  14548. }
  14549. function closeUserMenu() {
  14550. const menu = document.getElementById('user-menu-dropdown');
  14551. if (menu) menu.classList.add('hidden');
  14552. }
  14553. // Close user menu on outside click
  14554. document.addEventListener('click', (e) => {
  14555. const menu = document.getElementById('user-menu-dropdown');
  14556. if (!menu || menu.classList.contains('hidden')) return;
  14557. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14558. menu.classList.add('hidden');
  14559. }
  14560. });
  14561. function updateUserProfileHeader(user) {
  14562. if (!user) return;
  14563. const navName = document.getElementById('nav-user-name');
  14564. if (navName) navName.innerText = user.username;
  14565. const dropName = document.getElementById('dropdown-user-name');
  14566. if (dropName) dropName.innerText = user.username;
  14567. const navRole = document.getElementById('nav-user-role');
  14568. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14569. const navAvatar = document.getElementById('nav-user-avatar');
  14570. if (navAvatar) {
  14571. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14572. navAvatar.innerText = initials;
  14573. }
  14574. const statCurUser = document.getElementById('stat-current-user');
  14575. if (statCurUser) statCurUser.innerText = user.username;
  14576. const statCurRole = document.getElementById('stat-current-role');
  14577. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14578. // Role permissions UI visibility: hide user management for non-admins
  14579. const isFullAdmin = user.role === 'full';
  14580. const navUsers = document.getElementById('nav-users');
  14581. if (navUsers) {
  14582. if (isFullAdmin) navUsers.classList.remove('hidden');
  14583. else navUsers.classList.add('hidden');
  14584. }
  14585. const dropdownUsers = document.getElementById('dropdown-item-users');
  14586. if (dropdownUsers) {
  14587. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14588. else dropdownUsers.classList.add('hidden');
  14589. }
  14590. }
  14591. // ================= User Management CRUD =================
  14592. async function loadUsers(isManual = false) {
  14593. try {
  14594. const res = await fetch(`${API_BASE}/users`);
  14595. if (res.status === 403) {
  14596. const tbody = document.getElementById('users-table-tbody');
  14597. if (tbody) {
  14598. tbody.innerHTML = `
  14599. <tr>
  14600. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14601. <div class="inline-flex items-center gap-2">
  14602. <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>
  14603. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14604. </div>
  14605. </td>
  14606. </tr>
  14607. `;
  14608. }
  14609. return;
  14610. }
  14611. if (res.ok) {
  14612. state.users = await res.json();
  14613. renderUsersTable();
  14614. const totalUsers = document.getElementById('stat-total-users');
  14615. if (totalUsers) totalUsers.innerText = state.users.length;
  14616. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14617. const adminUsers = document.getElementById('stat-admin-users');
  14618. if (adminUsers) adminUsers.innerText = adminCount;
  14619. const badgeCount = document.getElementById('badge-users-count');
  14620. if (badgeCount) badgeCount.innerText = state.users.length;
  14621. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14622. }
  14623. } catch (err) {
  14624. console.error('Failed to load users:', err);
  14625. }
  14626. }
  14627. function renderUsersTable() {
  14628. const tbody = document.getElementById('users-table-tbody');
  14629. const emptyState = document.getElementById('users-empty-state');
  14630. if (!tbody) return;
  14631. tbody.innerHTML = '';
  14632. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14633. const filtered = (state.users || []).filter(u => {
  14634. if (!query) return true;
  14635. return u.username.toLowerCase().includes(query) ||
  14636. (u.role || '').toLowerCase().includes(query) ||
  14637. (u.comment || '').toLowerCase().includes(query);
  14638. });
  14639. if (filtered.length === 0) {
  14640. if (emptyState) emptyState.classList.remove('hidden');
  14641. return;
  14642. }
  14643. if (emptyState) emptyState.classList.add('hidden');
  14644. const currentAuthUser = state.currentUser?.username || '';
  14645. filtered.forEach(u => {
  14646. const isSelf = u.username === currentAuthUser;
  14647. const isFull = u.role === 'full';
  14648. const isWrite = u.role === 'write';
  14649. 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>`;
  14650. if (isFull) {
  14651. 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>`;
  14652. } else if (isWrite) {
  14653. 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>`;
  14654. }
  14655. const statusBadge = u.disabled
  14656. ? `<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>`
  14657. : `<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>`;
  14658. let lastLoginText = 'Never';
  14659. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14660. const dt = new Date(u.last_login_at);
  14661. lastLoginText = dt.toLocaleString();
  14662. }
  14663. const initials = u.username.slice(0, 2).toUpperCase();
  14664. const tr = document.createElement('tr');
  14665. tr.className = 'hover:bg-slate-800/40 transition group';
  14666. tr.innerHTML = `
  14667. <td class="py-3 px-4">
  14668. <div class="flex items-center gap-3">
  14669. <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">
  14670. ${initials}
  14671. </div>
  14672. <div>
  14673. <div class="font-bold text-white text-xs flex items-center gap-2">
  14674. <span>${escapeHtml(u.username)}</span>
  14675. ${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>' : ''}
  14676. </div>
  14677. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14678. </div>
  14679. </div>
  14680. </td>
  14681. <td class="py-3 px-4 font-sans">
  14682. ${roleBadge}
  14683. </td>
  14684. <td class="py-3 px-4 font-sans">
  14685. ${statusBadge}
  14686. </td>
  14687. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14688. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14689. </td>
  14690. <td class="py-3 px-4 text-slate-400 text-xs">
  14691. ${lastLoginText}
  14692. </td>
  14693. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14694. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14695. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14696. <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>
  14697. </button>
  14698. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14699. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14700. <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>
  14701. </button>
  14702. ${!isSelf ? `
  14703. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14704. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14705. <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>
  14706. </button>
  14707. ` : ''}
  14708. </td>
  14709. `;
  14710. tbody.appendChild(tr);
  14711. });
  14712. }
  14713. function openAddUserModal() {
  14714. document.getElementById('user-add-username').value = '';
  14715. document.getElementById('user-add-password').value = '';
  14716. document.getElementById('user-add-confirm').value = '';
  14717. document.getElementById('user-add-role').value = 'full';
  14718. document.getElementById('user-add-comment').value = '';
  14719. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14720. document.getElementById('user-add-username')?.focus();
  14721. }
  14722. function closeAddUserModal() {
  14723. document.getElementById('modal-add-user')?.classList.add('hidden');
  14724. }
  14725. async function submitAddUser(event) {
  14726. event.preventDefault();
  14727. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14728. const password = document.getElementById('user-add-password')?.value || '';
  14729. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14730. const role = document.getElementById('user-add-role')?.value || 'full';
  14731. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14732. if (password !== confirm) {
  14733. showToast('Validation Error', 'Passwords do not match', 'warning');
  14734. return;
  14735. }
  14736. if (password.length < 4) {
  14737. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14738. return;
  14739. }
  14740. try {
  14741. const res = await fetch(`${API_BASE}/users`, {
  14742. method: 'POST',
  14743. headers: { 'Content-Type': 'application/json' },
  14744. body: JSON.stringify({ username, password, role, comment })
  14745. });
  14746. const data = await res.json();
  14747. if (res.ok) {
  14748. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14749. closeAddUserModal();
  14750. loadUsers(false);
  14751. } else {
  14752. showToast('Error', data.message || 'Failed to create user', 'error');
  14753. }
  14754. } catch (err) {
  14755. showToast('Error', err.message, 'error');
  14756. }
  14757. }
  14758. function openEditUserModal(username) {
  14759. const user = (state.users || []).find(u => u.username === username);
  14760. if (!user) return;
  14761. document.getElementById('user-edit-username').value = user.username;
  14762. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14763. document.getElementById('user-edit-role').value = user.role || 'read';
  14764. document.getElementById('user-edit-comment').value = user.comment || '';
  14765. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14766. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14767. }
  14768. function closeEditUserModal() {
  14769. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14770. }
  14771. async function submitEditUser(event) {
  14772. event.preventDefault();
  14773. const username = document.getElementById('user-edit-username')?.value;
  14774. const role = document.getElementById('user-edit-role')?.value || 'read';
  14775. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14776. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14777. try {
  14778. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14779. method: 'PUT',
  14780. headers: { 'Content-Type': 'application/json' },
  14781. body: JSON.stringify({ role, comment, disabled })
  14782. });
  14783. const data = await res.json();
  14784. if (res.ok) {
  14785. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14786. closeEditUserModal();
  14787. loadUsers(false);
  14788. // If updated own role/disabled status, refresh self profile
  14789. if (username === state.currentUser?.username) {
  14790. checkAuthStatus();
  14791. }
  14792. } else {
  14793. showToast('Error', data.message || 'Failed to update user', 'error');
  14794. }
  14795. } catch (err) {
  14796. showToast('Error', err.message, 'error');
  14797. }
  14798. }
  14799. function openAdminResetPasswordModal(username) {
  14800. document.getElementById('admin-reset-username').value = username;
  14801. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14802. document.getElementById('admin-reset-new-pw').value = '';
  14803. document.getElementById('admin-reset-confirm-pw').value = '';
  14804. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14805. document.getElementById('admin-reset-new-pw')?.focus();
  14806. }
  14807. function closeAdminResetPasswordModal() {
  14808. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14809. }
  14810. async function submitAdminResetPassword(event) {
  14811. event.preventDefault();
  14812. const username = document.getElementById('admin-reset-username')?.value;
  14813. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14814. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14815. if (newPassword !== confirm) {
  14816. showToast('Validation Error', 'Passwords do not match', 'warning');
  14817. return;
  14818. }
  14819. if (newPassword.length < 4) {
  14820. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14821. return;
  14822. }
  14823. try {
  14824. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14825. method: 'POST',
  14826. headers: { 'Content-Type': 'application/json' },
  14827. body: JSON.stringify({ new_password: newPassword })
  14828. });
  14829. const data = await res.json();
  14830. if (res.ok) {
  14831. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14832. closeAdminResetPasswordModal();
  14833. } else {
  14834. showToast('Error', data.message || 'Failed to reset password', 'error');
  14835. }
  14836. } catch (err) {
  14837. showToast('Error', err.message, 'error');
  14838. }
  14839. }
  14840. async function deleteUser(username) {
  14841. if (username === state.currentUser?.username) {
  14842. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14843. return;
  14844. }
  14845. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14846. return;
  14847. }
  14848. try {
  14849. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14850. method: 'DELETE'
  14851. });
  14852. const data = await res.json();
  14853. if (res.ok) {
  14854. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14855. loadUsers(false);
  14856. } else {
  14857. showToast('Error', data.message || 'Failed to delete user', 'error');
  14858. }
  14859. } catch (err) {
  14860. showToast('Error', err.message, 'error');
  14861. }
  14862. }
  14863. function openSelfPasswordModal() {
  14864. document.getElementById('self-current-password').value = '';
  14865. document.getElementById('self-new-password').value = '';
  14866. document.getElementById('self-confirm-password').value = '';
  14867. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14868. document.getElementById('self-current-password')?.focus();
  14869. }
  14870. function closeSelfPasswordModal() {
  14871. document.getElementById('modal-self-password')?.classList.add('hidden');
  14872. }
  14873. async function submitSelfPassword(event) {
  14874. event.preventDefault();
  14875. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14876. const newPassword = document.getElementById('self-new-password')?.value || '';
  14877. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14878. if (newPassword !== confirm) {
  14879. showToast('Validation Error', 'New passwords do not match', 'warning');
  14880. return;
  14881. }
  14882. if (newPassword.length < 4) {
  14883. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14884. return;
  14885. }
  14886. try {
  14887. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14888. method: 'POST',
  14889. headers: { 'Content-Type': 'application/json' },
  14890. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14891. });
  14892. const data = await res.json();
  14893. if (res.ok) {
  14894. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14895. closeSelfPasswordModal();
  14896. } else {
  14897. showToast('Error', data.message || 'Failed to change password', 'error');
  14898. }
  14899. } catch (err) {
  14900. showToast('Error', err.message, 'error');
  14901. }
  14902. }
  14903. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14904. state.services = [];
  14905. async function loadServices(manual = false) {
  14906. try {
  14907. const res = await fetch(`${API_BASE}/system/services`);
  14908. if (!res.ok) throw new Error('Failed to load services');
  14909. const data = await res.json();
  14910. state.services = data || [];
  14911. renderServicesTable();
  14912. updateCertificatesBadges();
  14913. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14914. } catch (err) {
  14915. if (manual) showToast('Error', err.message, 'error');
  14916. }
  14917. }
  14918. function renderServicesTable() {
  14919. const tbody = document.getElementById('services-table-body');
  14920. if (!tbody) return;
  14921. if (!state.services || state.services.length === 0) {
  14922. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14923. return;
  14924. }
  14925. tbody.innerHTML = state.services.map(s => {
  14926. const isOff = s.disabled;
  14927. const statusBadge = isOff
  14928. ? '<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>'
  14929. : '<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>';
  14930. const toggleBtn = isOff
  14931. ? `<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>`
  14932. : `<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>`;
  14933. let certBadge = '';
  14934. if (s.name === 'www-ssl') {
  14935. if (s.certificate) {
  14936. 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>`;
  14937. } else {
  14938. 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>`;
  14939. }
  14940. }
  14941. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  14942. return `
  14943. <tr class="hover:bg-slate-800/40 transition">
  14944. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  14945. <td class="py-3 px-4">
  14946. <div class="flex items-center gap-2">
  14947. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14948. <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">
  14949. <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>
  14950. </button>
  14951. </div>
  14952. </td>
  14953. <td class="py-3 px-4">${statusBadge}</td>
  14954. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14955. <td class="py-3 px-4 text-right">
  14956. <div class="flex items-center justify-end gap-2">
  14957. <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">
  14958. <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>
  14959. <span>Edit</span>
  14960. </button>
  14961. ${toggleBtn}
  14962. </div>
  14963. </td>
  14964. </tr>
  14965. `;
  14966. }).join('');
  14967. }
  14968. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  14969. document.getElementById('modal-service-name').value = serviceName;
  14970. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14971. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14972. document.getElementById('modal-service-port').value = currentPort;
  14973. const hintEl = document.getElementById('modal-service-port-hint');
  14974. const warnEl = document.getElementById('modal-service-warning');
  14975. const certGroup = document.getElementById('modal-service-cert-group');
  14976. const certSelect = document.getElementById('modal-service-cert-select');
  14977. if (serviceName === 'www') {
  14978. hintEl.textContent = 'Default HTTP web port: 80';
  14979. warnEl.classList.remove('hidden');
  14980. certGroup.classList.add('hidden');
  14981. } else if (serviceName === 'www-ssl') {
  14982. hintEl.textContent = 'Default HTTPS web port: 443';
  14983. warnEl.classList.remove('hidden');
  14984. certGroup.classList.remove('hidden');
  14985. const populateCertOptions = (certs) => {
  14986. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  14987. (certs || []).forEach(c => {
  14988. const opt = document.createElement('option');
  14989. opt.value = c.name;
  14990. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  14991. if (c.name === currentCert) opt.selected = true;
  14992. certSelect.appendChild(opt);
  14993. });
  14994. };
  14995. if (state.certificates && state.certificates.length > 0) {
  14996. populateCertOptions(state.certificates);
  14997. } else {
  14998. loadCertificates(false).then(() => {
  14999. populateCertOptions(state.certificates);
  15000. });
  15001. }
  15002. } else if (serviceName === 'telnet') {
  15003. hintEl.textContent = 'Default Telnet console port: 8282';
  15004. warnEl.classList.add('hidden');
  15005. certGroup.classList.add('hidden');
  15006. } else if (serviceName === 'ssh') {
  15007. hintEl.textContent = 'Default SSH port: 2222';
  15008. warnEl.classList.add('hidden');
  15009. certGroup.classList.add('hidden');
  15010. } else {
  15011. hintEl.textContent = '';
  15012. warnEl.classList.add('hidden');
  15013. certGroup.classList.add('hidden');
  15014. }
  15015. const modal = document.getElementById('modal-service-edit');
  15016. modal.classList.remove('hidden');
  15017. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  15018. }
  15019. function closeEditServiceModal() {
  15020. const modal = document.getElementById('modal-service-edit');
  15021. if (modal) modal.classList.add('hidden');
  15022. }
  15023. async function submitSaveServicePort(event) {
  15024. event.preventDefault();
  15025. const name = document.getElementById('modal-service-name').value;
  15026. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  15027. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  15028. if (isNaN(port) || port < 1 || port > 65535) {
  15029. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  15030. return;
  15031. }
  15032. const certSelect = document.getElementById('modal-service-cert-select');
  15033. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  15034. try {
  15035. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  15036. method: 'POST',
  15037. headers: { 'Content-Type': 'application/json' },
  15038. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  15039. });
  15040. if (!res.ok) {
  15041. const errData = await res.json();
  15042. throw new Error(errData.message || 'Failed to update service settings');
  15043. }
  15044. closeEditServiceModal();
  15045. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  15046. await loadServices();
  15047. } catch (err) {
  15048. showToast('Error', err.message, 'error');
  15049. }
  15050. }
  15051. async function toggleServiceState(serviceName, newDisabled) {
  15052. if (serviceName === 'www' && newDisabled) {
  15053. 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?")) {
  15054. return;
  15055. }
  15056. }
  15057. if (serviceName === 'www-ssl' && !newDisabled) {
  15058. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15059. if (!sslSvc || !sslSvc.certificate) {
  15060. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  15061. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  15062. return;
  15063. }
  15064. }
  15065. try {
  15066. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  15067. method: 'POST',
  15068. headers: { 'Content-Type': 'application/json' },
  15069. body: JSON.stringify({ disabled: newDisabled })
  15070. });
  15071. if (!res.ok) {
  15072. const errData = await res.json();
  15073. throw new Error(errData.message || 'Failed to update service');
  15074. }
  15075. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  15076. await loadServices();
  15077. } catch (err) {
  15078. showToast('Error', err.message, 'error');
  15079. }
  15080. }
  15081. // ==================== SYSTEM LOGS (/log) ====================
  15082. state.logs = [];
  15083. let logsTimer = null;
  15084. async function loadLogs(manual = false) {
  15085. const limitEl = document.getElementById('logs-limit-select');
  15086. const limit = limitEl ? limitEl.value : '100';
  15087. try {
  15088. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  15089. if (!res.ok) throw new Error('Failed to load logs');
  15090. const data = await res.json();
  15091. state.logs = data.logs || [];
  15092. renderLogsTable();
  15093. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  15094. } catch (err) {
  15095. if (manual) showToast('Error', err.message, 'error');
  15096. }
  15097. // Setup auto-refresh if enabled and on logs tab
  15098. if (!logsTimer && state.currentUser) {
  15099. logsTimer = setInterval(() => {
  15100. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  15101. const auto = document.getElementById('logs-auto-refresh');
  15102. if (auto && auto.checked) {
  15103. loadLogs(false);
  15104. }
  15105. }
  15106. }, 3000);
  15107. }
  15108. }
  15109. function renderLogsTable() {
  15110. const tbody = document.getElementById('logs-table-body');
  15111. if (!tbody) return;
  15112. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  15113. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  15114. const filtered = state.logs.filter(entry => {
  15115. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  15116. return false;
  15117. }
  15118. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  15119. return false;
  15120. }
  15121. return true;
  15122. });
  15123. if (filtered.length === 0) {
  15124. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  15125. return;
  15126. }
  15127. tbody.innerHTML = filtered.map(l => {
  15128. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  15129. const topLower = l.topics.toLowerCase();
  15130. if (topLower.includes('auth')) {
  15131. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  15132. } else if (topLower.includes('dhcp')) {
  15133. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  15134. } else if (topLower.includes('route')) {
  15135. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  15136. } else if (topLower.includes('firewall')) {
  15137. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  15138. } else if (topLower.includes('error')) {
  15139. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15140. } else if (topLower.includes('system')) {
  15141. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15142. }
  15143. const d = new Date(l.time);
  15144. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15145. return `
  15146. <tr class="hover:bg-slate-800/40 transition">
  15147. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15148. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15149. <td class="py-2 px-3 whitespace-nowrap">
  15150. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15151. </td>
  15152. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15153. </tr>
  15154. `;
  15155. }).join('');
  15156. }
  15157. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15158. state.certificates = [];
  15159. async function loadCertificates(manual = false) {
  15160. try {
  15161. const res = await fetch(`${API_BASE}/certificates`);
  15162. if (!res.ok) throw new Error('Failed to load certificates');
  15163. state.certificates = await res.json() || [];
  15164. updateCertificatesBadges();
  15165. renderCertificatesTable();
  15166. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15167. } catch (err) {
  15168. if (manual) showToast('Error', err.message, 'error');
  15169. }
  15170. }
  15171. function updateCertificatesBadges() {
  15172. const total = (state.certificates || []).length;
  15173. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15174. const bCount = document.getElementById('badge-certs-count');
  15175. if (bCount) bCount.innerText = total;
  15176. const kpiTotal = document.getElementById('kpi-certs-total');
  15177. if (kpiTotal) kpiTotal.innerText = total;
  15178. const kpiCA = document.getElementById('kpi-certs-ca');
  15179. if (kpiCA) kpiCA.innerText = caCount;
  15180. const kpiHttps = document.getElementById('kpi-https-status');
  15181. if (kpiHttps) {
  15182. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15183. if (sslSvc) {
  15184. if (!sslSvc.disabled) {
  15185. 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>`;
  15186. } else {
  15187. 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>`;
  15188. }
  15189. }
  15190. }
  15191. }
  15192. function renderCertificatesTable() {
  15193. const tbody = document.getElementById('certs-table-body');
  15194. if (!tbody) return;
  15195. if (!state.certificates || state.certificates.length === 0) {
  15196. 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>';
  15197. return;
  15198. }
  15199. tbody.innerHTML = state.certificates.map(c => {
  15200. let typeBadge = '';
  15201. if (c.is_ca) {
  15202. 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>';
  15203. } else if (c.type === 'acme') {
  15204. 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>';
  15205. } else if (c.issuer && c.issuer !== c.common_name) {
  15206. 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>';
  15207. } else {
  15208. 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>';
  15209. }
  15210. const sansHtml = (c.sans && c.sans.length > 0)
  15211. ? 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('')
  15212. : '<span class="text-slate-500">-</span>';
  15213. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15214. let validStr = '-';
  15215. let validBadge = '';
  15216. if (validTo && !isNaN(validTo.getTime())) {
  15217. const now = new Date();
  15218. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15219. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15220. if (daysLeft < 0) {
  15221. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15222. } else if (daysLeft < 30) {
  15223. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15224. } else {
  15225. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15226. }
  15227. }
  15228. return `
  15229. <tr class="hover:bg-slate-800/40 transition">
  15230. <td class="py-3 px-4">${typeBadge}</td>
  15231. <td class="py-3 px-4">
  15232. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15233. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15234. </td>
  15235. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15236. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15237. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15238. <span>${validStr}</span> ${validBadge}
  15239. ${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>` : ''}
  15240. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15241. </td>
  15242. <td class="py-3 px-4 text-right whitespace-nowrap">
  15243. <div class="flex items-center justify-end gap-1.5">
  15244. <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">
  15245. <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>
  15246. <span>View</span>
  15247. </button>
  15248. <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">
  15249. <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>
  15250. </button>
  15251. </div>
  15252. </td>
  15253. </tr>
  15254. `;
  15255. }).join('');
  15256. }
  15257. // Create CA
  15258. function openCreateCAModal() {
  15259. document.getElementById('form-create-ca').reset();
  15260. document.getElementById('ca-days').value = '3650';
  15261. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15262. document.getElementById('ca-country').value = 'GR';
  15263. document.getElementById('ca-key-type').value = 'RSA-2048';
  15264. document.getElementById('modal-create-ca').classList.remove('hidden');
  15265. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15266. }
  15267. function closeCreateCAModal() {
  15268. document.getElementById('modal-create-ca').classList.add('hidden');
  15269. }
  15270. async function submitCreateCA(event) {
  15271. event.preventDefault();
  15272. const payload = {
  15273. name: document.getElementById('ca-name').value.trim(),
  15274. common_name: document.getElementById('ca-cn').value.trim(),
  15275. organization: document.getElementById('ca-org').value.trim(),
  15276. country: document.getElementById('ca-country').value.trim(),
  15277. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15278. key_type: document.getElementById('ca-key-type').value
  15279. };
  15280. try {
  15281. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15282. method: 'POST',
  15283. headers: { 'Content-Type': 'application/json' },
  15284. body: JSON.stringify(payload)
  15285. });
  15286. if (!res.ok) {
  15287. const errData = await res.json();
  15288. throw new Error(errData.message || 'Failed to create CA');
  15289. }
  15290. closeCreateCAModal();
  15291. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15292. await loadCertificates();
  15293. } catch (err) {
  15294. showToast('Error', err.message, 'error');
  15295. }
  15296. }
  15297. // Create Cert
  15298. function openCreateCertModal() {
  15299. document.getElementById('form-create-cert').reset();
  15300. document.getElementById('cert-days').value = '730';
  15301. document.getElementById('cert-key-type').value = 'RSA-2048';
  15302. const caSelect = document.getElementById('cert-ca-select');
  15303. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15304. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15305. const opt = document.createElement('option');
  15306. opt.value = ca.name;
  15307. opt.textContent = `${ca.name} (${ca.common_name})`;
  15308. caSelect.appendChild(opt);
  15309. });
  15310. document.getElementById('modal-create-cert').classList.remove('hidden');
  15311. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15312. }
  15313. function closeCreateCertModal() {
  15314. document.getElementById('modal-create-cert').classList.add('hidden');
  15315. }
  15316. async function submitCreateCert(event) {
  15317. event.preventDefault();
  15318. const rawSans = document.getElementById('cert-sans').value;
  15319. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15320. const caName = document.getElementById('cert-ca-select').value;
  15321. const payload = {
  15322. name: document.getElementById('cert-name').value.trim(),
  15323. common_name: document.getElementById('cert-cn').value.trim(),
  15324. ca_name: caName,
  15325. sans: sansList,
  15326. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15327. key_type: document.getElementById('cert-key-type').value,
  15328. is_server: true
  15329. };
  15330. try {
  15331. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15332. method: 'POST',
  15333. headers: { 'Content-Type': 'application/json' },
  15334. body: JSON.stringify(payload)
  15335. });
  15336. if (!res.ok) {
  15337. const errData = await res.json();
  15338. throw new Error(errData.message || 'Failed to issue certificate');
  15339. }
  15340. closeCreateCertModal();
  15341. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15342. await loadCertificates();
  15343. } catch (err) {
  15344. showToast('Error', err.message, 'error');
  15345. }
  15346. }
  15347. // Let's Encrypt
  15348. function openLetsEncryptModal() {
  15349. document.getElementById('form-letsencrypt').reset();
  15350. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15351. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15352. }
  15353. function closeLetsEncryptModal() {
  15354. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15355. }
  15356. async function submitLetsEncrypt(event) {
  15357. event.preventDefault();
  15358. const domain = document.getElementById('le-domain').value.trim();
  15359. const email = document.getElementById('le-email').value.trim();
  15360. let name = document.getElementById('le-name').value.trim();
  15361. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15362. const staging = document.getElementById('le-staging').checked;
  15363. const btn = document.getElementById('btn-submit-letsencrypt');
  15364. const origBtnHtml = btn.innerHTML;
  15365. btn.disabled = true;
  15366. 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>`;
  15367. try {
  15368. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15369. method: 'POST',
  15370. headers: { 'Content-Type': 'application/json' },
  15371. body: JSON.stringify({
  15372. name: name,
  15373. domain: domain,
  15374. email: email,
  15375. staging: staging
  15376. })
  15377. });
  15378. if (!res.ok) {
  15379. const errData = await res.json();
  15380. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15381. }
  15382. closeLetsEncryptModal();
  15383. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15384. await loadCertificates();
  15385. } catch (err) {
  15386. showToast('Let\'s Encrypt Error', err.message, 'error');
  15387. } finally {
  15388. btn.disabled = false;
  15389. btn.innerHTML = origBtnHtml;
  15390. }
  15391. }
  15392. // Import Cert
  15393. function openImportCertModal() {
  15394. document.getElementById('form-import-cert').reset();
  15395. document.getElementById('modal-import-cert').classList.remove('hidden');
  15396. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15397. }
  15398. function closeImportCertModal() {
  15399. document.getElementById('modal-import-cert').classList.add('hidden');
  15400. }
  15401. async function submitImportCert(event) {
  15402. event.preventDefault();
  15403. const payload = {
  15404. name: document.getElementById('import-cert-name').value.trim(),
  15405. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15406. key_pem: document.getElementById('import-key-pem').value.trim()
  15407. };
  15408. try {
  15409. const res = await fetch(`${API_BASE}/certificates/import`, {
  15410. method: 'POST',
  15411. headers: { 'Content-Type': 'application/json' },
  15412. body: JSON.stringify(payload)
  15413. });
  15414. if (!res.ok) {
  15415. const errData = await res.json();
  15416. throw new Error(errData.message || 'Failed to import certificate');
  15417. }
  15418. closeImportCertModal();
  15419. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15420. await loadCertificates();
  15421. } catch (err) {
  15422. showToast('Error', err.message, 'error');
  15423. }
  15424. }
  15425. // View / Export Modal
  15426. async function openViewCertModal(name) {
  15427. const c = (state.certificates || []).find(x => x.name === name);
  15428. if (!c) return;
  15429. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15430. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15431. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15432. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15433. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15434. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15435. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15436. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15437. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15438. document.getElementById('modal-view-cert').classList.remove('hidden');
  15439. try {
  15440. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15441. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15442. const data = await res.json();
  15443. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15444. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15445. } catch (err) {
  15446. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15447. document.getElementById('view-key-pem-text').value = '';
  15448. }
  15449. }
  15450. function closeViewCertModal() {
  15451. document.getElementById('modal-view-cert').classList.add('hidden');
  15452. }
  15453. function copyCertPEM() {
  15454. const text = document.getElementById('view-cert-pem-text').value;
  15455. if (!text) return;
  15456. navigator.clipboard.writeText(text).then(() => {
  15457. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15458. }).catch(() => {
  15459. showToast('Error', 'Failed to copy to clipboard', 'error');
  15460. });
  15461. }
  15462. function copyKeyPEM() {
  15463. const text = document.getElementById('view-key-pem-text').value;
  15464. if (!text) return;
  15465. navigator.clipboard.writeText(text).then(() => {
  15466. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15467. }).catch(() => {
  15468. showToast('Error', 'Failed to copy to clipboard', 'error');
  15469. });
  15470. }
  15471. async function deleteCertificate(name) {
  15472. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15473. return;
  15474. }
  15475. try {
  15476. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15477. method: 'DELETE'
  15478. });
  15479. if (!res.ok) {
  15480. const errData = await res.json();
  15481. throw new Error(errData.message || 'Failed to delete certificate');
  15482. }
  15483. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15484. await loadCertificates();
  15485. } catch (err) {
  15486. showToast('Error', err.message, 'error');
  15487. }
  15488. }
  15489. // Refresh immediately when returning to a backgrounded controller tab.
  15490. document.addEventListener('visibilitychange', () => {
  15491. if (!state.currentUser) return;
  15492. if (document.hidden) {
  15493. if (trafficEventSource) trafficEventSource.close();
  15494. trafficEventSource = null;
  15495. if (trafficPollFallback) clearInterval(trafficPollFallback);
  15496. trafficPollFallback = null;
  15497. } else {
  15498. fetchData(false);
  15499. initLiveTrafficStream();
  15500. if (state.activeTab === 'bwtest') loadBwTestView();
  15501. }
  15502. });
  15503. async function loadUpdateStatus(populate = true) {
  15504. try {
  15505. const res = await fetch(`${API_BASE}/update/status`);
  15506. if (!res.ok) throw new Error(await responseError(res));
  15507. const data = await res.json();
  15508. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  15509. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  15510. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  15511. document.getElementById('update-state').textContent = data.state || 'idle';
  15512. document.getElementById('update-log').textContent = data.log || '';
  15513. } catch (err) { showToast('Update Status', err.message, 'error'); }
  15514. }
  15515. async function saveUpdateConfig() {
  15516. try {
  15517. const repository = document.getElementById('update-repository').value.trim();
  15518. const branch = 'master';
  15519. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  15520. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  15521. if (!res.ok) throw new Error(await responseError(res));
  15522. document.getElementById('update-install-button').disabled = true;
  15523. document.getElementById('update-available').textContent = '—';
  15524. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  15525. await loadUpdateStatus(false);
  15526. } catch (err) { showToast('Update Source', err.message, 'error'); }
  15527. }
  15528. async function checkUpdate() {
  15529. try {
  15530. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  15531. if (!res.ok) throw new Error(await responseError(res));
  15532. const data = await res.json();
  15533. document.getElementById('update-available').textContent = data.available_version;
  15534. document.getElementById('update-install-button').disabled = !data.update_available;
  15535. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  15536. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  15537. }
  15538. async function startUpdate(action) {
  15539. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  15540. try {
  15541. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  15542. if (!res.ok) throw new Error(await responseError(res));
  15543. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  15544. await loadUpdateStatus(false);
  15545. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  15546. }
  15547. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  15548. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  15549. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  15550. function safeFirewallRow(row) {
  15551. const result = {...row};
  15552. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  15553. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  15554. return result;
  15555. }
  15556. function setFirewallDays(prefix, days) {
  15557. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  15558. 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); }
  15559. }
  15560. function getFirewallDays(prefix) {
  15561. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  15562. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  15563. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  15564. return selected.join(',');
  15565. }
  15566. async function resetFirewallRuleCounter(kind, resetDisplay) {
  15567. const id = document.getElementById(kind+'-modal-id')?.value;
  15568. if (!id) { resetDisplay(); return; }
  15569. try {
  15570. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  15571. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  15572. resetDisplay(); await loadFirewall(false);
  15573. } catch(error) { showToast('Error', error.message, 'error'); }
  15574. }
  15575. function reviewLegacyFirewallSettings(kind, id) {
  15576. if (!id) return true;
  15577. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  15578. const rule = (rows || []).find(r => r.id === id);
  15579. if (!rule) return true;
  15580. 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'];
  15581. const present = unsupported.filter(key => rule[key]);
  15582. if (!present.length) return true;
  15583. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  15584. }
  15585. function refreshFirewallRejectTypes() {
  15586. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  15587. const old=select.value;
  15588. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  15589. 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'];
  15590. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  15591. if(types.includes(old))select.value=old;
  15592. }
  15593. function setFirewallActionSelection(kind, value) {
  15594. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  15595. if(!Array.from(select.options).some(option=>option.value===value)) {
  15596. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  15597. }
  15598. select.value=value;
  15599. }